import{s as e}from"./DrKWWDpL.js";import{t}from"./DYP3EJMY.js";import"./DeO5NWhN.js";import"./C0nwgWmB.js";import"./D-eE9s2f.js";import{a as n,r}from"./bG-fsHMS.js";import"./BVC3q6GM.js";import{a as i,s as a}from"./Cx_-1PHK2.js";import{t as o}from"./CvFbqtf9.js";var{DatabaseSync:s}=(0,e(t(),1).createRequire)(import.meta.url)(`node:sqlite`),c=/(?:^|\s|['"`(])([a-zA-Z0-9_\-./]+\.(?:ts|tsx|js|jsx|rs|go|py|mjs|cjs))(?:$|\s|['"`)])/g,l=/\b([a-zA-Z_][a-zA-Z0-9_]*(?:[A-Z][a-zA-Z0-9_]*)+|[a-zA-Z_]{4,}[a-zA-Z0-9_]*)\b/g,u=new Set(`true.false.null.undefined.const.async.await.return.export.import.from.type.interface.function.class.this.super.extends.implements.with.that.then.when.have.been.will.should.could.would.error.result.value.data.info.note.todo.done.fail.pass`.split(`.`));function d(e){let t=new Set;for(let n of e.matchAll(c)){let e=n[1];e&&t.add(e)}return Array.from(t)}function f(e){let t=new Set;for(let n of e.matchAll(l)){let e=n[1];e&&e.length>=4&&!u.has(e.toLowerCase())&&t.add(e)}return Array.from(t)}function p(e){if(!e)return``;try{let t=JSON.parse(e);return Object.values(t).filter(e=>typeof e==`string`).join(` `)}catch{return``}}async function m(e,t,i,o){let s=0;if(!t)return 0;try{await r(i);let c=n();if(!c)return 0;let l=o??a();if(!l)return 0;let u=JSON.parse(t);if(!Array.isArray(u))return 0;let d=new Date().toISOString().replace(`T`,` `).slice(0,19);for(let t of u){if(!t||typeof t!=`string`)continue;let n=l.prepare(`SELECT id FROM nexus_nodes WHERE file_path = ? LIMIT 1`).get(t);if(n)try{c.prepare(`
            INSERT OR IGNORE INTO brain_page_edges
              (from_id, to_id, edge_type, weight, provenance, created_at)
            VALUES (?, ?, 'modified_by', 1.0, 'auto:file-modify', ?)
          `).run(n.id,e,d),s++}catch(e){console.warn(`[graph-memory-bridge] modified_by edge insert failed:`,e)}}}catch(e){console.warn(`[graph-memory-bridge] linkObservationToModifiedFiles failed:`,e)}return s}async function h(e,t,i,s){let c=0;if(!t||t.length===0)return 0;try{await r(i);let l=n();if(!l)return 0;let u=s??a();if(!u)return 0;let d=o(u.prepare(`SELECT id, name FROM nexus_nodes WHERE name IS NOT NULL LIMIT 10000`));if(d.length===0)return 0;let f=new Set(d.map(e=>e.name)),p=Array.from(f),m=[];for(let e of p)RegExp(`\\b${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}\\b`).test(t)&&m.push(e);let h=m.slice(0,20),g=new Date().toISOString().replace(`T`,` `).slice(0,19);for(let t of h){let n=d.find(e=>e.name===t);if(n)try{l.prepare(`
            INSERT OR IGNORE INTO brain_page_edges
              (from_id, to_id, edge_type, weight, provenance, created_at)
            VALUES (?, ?, 'mentions', 1.0, 'auto:symbol-ner', ?)
          `).run(e,n.id,g),c++}catch(e){console.warn(`[graph-memory-bridge] mentions edge insert failed:`,e)}}}catch(e){console.warn(`[graph-memory-bridge] linkObservationToMentionedSymbols failed:`,e)}return c}async function g(e,t,i,s){let c=0;if(!t||t.length===0)return 0;try{await r(i);let l=n();if(!l)return 0;let u=s??a();if(!u)return 0;let d=o(u.prepare(`SELECT id, name FROM nexus_nodes WHERE name IS NOT NULL LIMIT 10000`));if(d.length===0)return 0;let f=new Set(d.map(e=>e.name)),p=Array.from(f),m=[];for(let e of p)RegExp(`\\b${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}\\b`).test(t)&&m.push(e);let h=m.slice(0,20),g=new Date().toISOString().replace(`T`,` `).slice(0,19);for(let t of h){let n=d.find(e=>e.name===t);if(n)try{l.prepare(`
            INSERT OR IGNORE INTO brain_page_edges
              (from_id, to_id, edge_type, weight, provenance, created_at)
            VALUES (?, ?, 'documents', 1.0, 'auto:decision-ner', ?)
          `).run(e,n.id,g),c++}catch(e){console.warn(`[graph-memory-bridge] documents edge insert failed:`,e)}}}catch(e){console.warn(`[graph-memory-bridge] linkDecisionToSymbols failed:`,e)}return c}async function _(e){let t={scanned:0,linked:0,alreadyLinked:0,links:[]};try{await r(e);let s=n();await i();let c=a();if(!s||!c)return t;let l=o(s.prepare(`
        SELECT id, node_type, label, quality_score, metadata_json
        FROM brain_page_nodes
        WHERE node_type IN ('observation', 'decision', 'pattern', 'learning')
          AND quality_score >= 0.3
        ORDER BY quality_score DESC
        LIMIT 500
      `));if(t.scanned=l.length,l.length===0)return t;let u=o(c.prepare(`
        SELECT id, label, name, file_path, kind
        FROM nexus_nodes
        WHERE kind NOT IN ('community', 'process', 'folder')
        LIMIT 20000
      `));if(u.length===0)return t;let _=new Map,v=new Map,y=new Map;for(let e of u){if(e.file_path){let t=e.file_path.toLowerCase(),n=_.get(t)??[];n.push(e),_.set(t,n)}if(e.name){let t=v.get(e.name)??[];t.push(e),v.set(e.name,t);let n=e.name.toLowerCase(),r=y.get(n)??[];r.push(e),y.set(n,r)}}let b=new Date().toISOString().replace(`T`,` `).slice(0,19),x=new Set,S=o(s.prepare(`
        SELECT from_id, to_id FROM brain_page_edges WHERE edge_type = 'code_reference'
      `));for(let e of S)x.add(`${e.from_id}|${e.to_id}`);for(let e of l){let n=`${e.label} ${p(e.metadata_json)}`,r=d(n),i=f(n),a=[];for(let e of r){let t=_.get(e.toLowerCase());if(t)for(let e of t)a.push({nexusNode:e,strategy:`exact-file`,weight:1})}for(let e of i){let t=v.get(e);if(t)for(let e of t)a.push({nexusNode:e,strategy:`exact-symbol`,weight:1})}let o=new Set(i.flatMap(e=>v.get(e)??[]).map(e=>e.id));for(let e of i){if(e.length<5)continue;let t=e.toLowerCase(),n=y.get(t);if(n)for(let e of n)o.has(e.id)||a.push({nexusNode:e,strategy:`fuzzy-symbol`,weight:.6})}let c=new Map;for(let e of a){let t=c.get(e.nexusNode.id);(!t||e.weight>t.weight)&&c.set(e.nexusNode.id,e)}let l=Array.from(c.values()).sort((e,t)=>t.weight-e.weight).slice(0,10);for(let{nexusNode:n,strategy:r,weight:i}of l){let a=`${e.id}|${n.id}`;if(x.has(a)){t.alreadyLinked++;continue}s.prepare(`
            INSERT OR IGNORE INTO brain_page_nodes
              (id, node_type, label, quality_score, content_hash, metadata_json, last_activity_at, created_at, updated_at)
            VALUES (?, ?, ?, ?, NULL, NULL, ?, ?, ?)
          `).run(e.id,e.node_type,e.label,e.quality_score,b,b,b);try{s.prepare(`
              INSERT OR IGNORE INTO brain_page_edges
                (from_id, to_id, edge_type, weight, provenance, created_at)
              VALUES (?, ?, 'code_reference', ?, ?, ?)
            `).run(e.id,n.id,i,`auto:${r}`,b),x.add(a),t.linked++,t.links.push({brainNodeId:e.id,nexusNodeId:n.id,nexusLabel:n.label,matchStrategy:r,weight:i})}catch(e){console.warn(`[graph-memory-bridge] edge insert failed:`,e)}}}try{let n=o(s.prepare(`
          SELECT id, files_modified_json, narrative
          FROM brain_observations
          WHERE quality_score >= 0.3
          LIMIT 200
        `));for(let r of n){if(r.files_modified_json){let n=await m(`observation:${r.id}`,r.files_modified_json,e,c);t.linked+=n}if(r.narrative){let n=await h(`observation:${r.id}`,r.narrative,e,c);t.linked+=n}}let r=o(s.prepare(`
          SELECT id, decision, rationale
          FROM brain_decisions
          WHERE quality_score >= 0.3
          LIMIT 200
        `));for(let n of r){let r=`${n.decision??``} ${n.rationale??``}`;if(r.trim().length>0){let i=await g(`decision:${n.id}`,r,e,c);t.linked+=i}}}catch(e){console.warn(`[graph-memory-bridge] specialized edge writers failed:`,e)}}catch(e){console.warn(`[graph-memory-bridge] autoLinkMemories failed:`,e)}return t}export{_ as autoLinkMemories};