@precisionutilityguild/liquid-shadow 1.0.7 → 1.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/data/migrations/000_baseline.sql +10 -0
- package/dist/data/migrations/013_file_claims.sql +18 -0
- package/dist/entry/cli/index.js +259 -204
- package/dist/entry/ember/index.js +81 -28
- package/dist/entry/mcp/server.js +281 -226
- package/dist/index.js +282 -227
- package/dist/logic/parser/index.js +16 -14
- package/dist/web-manifest.json +4 -1
- package/package.json +1 -1
package/dist/entry/cli/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var sl=Object.create;var as=Object.defineProperty;var rl=Object.getOwnPropertyDescriptor;var ol=Object.getOwnPropertyNames;var al=Object.getPrototypeOf,cl=Object.prototype.hasOwnProperty;var ll=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ee=(s,e)=>()=>(s&&(e=s(s=0)),e);var pl=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),cs=(s,e)=>{for(var t in e)as(s,t,{get:e[t],enumerable:!0})},ul=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ol(e))!cl.call(s,i)&&i!==t&&as(s,i,{get:()=>e[i],enumerable:!(n=rl(e,i))||n.enumerable});return s};var dl=(s,e,t)=>(t=s!=null?sl(al(s)):{},ul(e||!s||!s.__esModule?as(t,"default",{value:s,enumerable:!0}):t,s));import ml from"pino";var hl,fl,w,G=ee(()=>{"use strict";hl={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},fl=ml({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:hl[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),w=fl});import Pt from"fs";import Nn from"path";import{fileURLToPath as bl}from"url";function Sl(){let s=El;if(Pt.readdirSync(s).some(n=>n.match(/^\d{3}_.*\.sql$/)))return s;let t=Nn.resolve(s,"../../data/migrations");return Pt.existsSync(t)&&Pt.readdirSync(t).some(n=>n.match(/^\d{3}_.*\.sql$/))?t:s}function wl(s){s.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
4
4
|
version INTEGER PRIMARY KEY,
|
|
5
5
|
name TEXT NOT NULL,
|
|
6
6
|
applied_at REAL DEFAULT (unixepoch())
|
|
7
7
|
);
|
|
8
|
-
`)}function
|
|
8
|
+
`)}function xl(s){wl(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function vl(s){return Pt.readdirSync(s).filter(t=>t.match(/^\d{3}_.*\.sql$/)&&!t.startsWith("000_")).sort().map(t=>{let n=t.match(/^(\d{3})_(.+)\.sql$/),i=parseInt(n[1],10),r=n[2],a=Pt.readFileSync(Nn.join(s,t),"utf-8").split(/^-- DOWN$/m);return{version:i,name:r,up:a[0].trim(),down:a[1]?.trim()}})}function Rl(s,e){bt.info({version:e.version,name:e.name},"Applying migration"),s.transaction(()=>{s.exec(e.up),s.prepare("INSERT INTO schema_migrations (version, name) VALUES (?, ?)").run(e.version,e.name)})(),bt.info({version:e.version},"Migration applied successfully")}function Tl(s,e,t){let n=Nn.join(e,"000_baseline.sql");if(!Pt.existsSync(n)){bt.warn("000_baseline.sql not found \u2014 falling back to incremental migrations");return}bt.info("Fresh database detected \u2014 applying consolidated baseline schema");let i=Pt.readFileSync(n,"utf-8");s.transaction(()=>{s.exec(i);let r=s.prepare("INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (?, ?)");for(let o of t)r.run(o.version,o.name)})(),bt.info({stamped:t.length},"Baseline applied \u2014 incremental migrations stamped")}function Rr(s){let e=xl(s),t=Sl(),n=vl(t);if(e.size===0){Tl(s,t,n);return}let i=n.filter(r=>!e.has(r.version));if(i.length===0){bt.debug("No pending migrations");return}bt.info({count:i.length},"Running pending migrations");for(let r of i)Rl(s,r);bt.info("All migrations complete")}var bt,_l,El,Tr=ee(()=>{"use strict";G();bt=w.child({module:"migrations"}),_l=bl(import.meta.url),El=Nn.dirname(_l)});import kl from"better-sqlite3";import Dn from"path";import ps from"fs";import kr from"crypto";import Cl from"os";function Fn(s){let e=Cl.homedir(),t=Dn.join(e,".mcp-liquid-shadow"),n=Dn.join(t,"dbs");ps.existsSync(n)||ps.mkdirSync(n,{recursive:!0});let i=kr.createHash("sha256").update(s).digest("hex").substring(0,12),o=`${Dn.basename(s).replace(/[^a-zA-Z0-9-_]/g,"_")}_${i}.db`;return Dn.join(n,o)}function Il(s,e){let t=e||Fn(s);lt.debug({repoPath:s,dbPath:t},"Initializing database");let n=new kl(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),Rr(n),On.set(s,t),_t.set(t,n),lt.debug({repoPath:s,dbPath:t},"Database initialized successfully"),n}function Jt(s){return kr.createHash("sha256").update(s,"utf8").digest("hex")}function Cr(s,e){return e?Jt(s)!==e:!0}function De(s){let e=On.get(s)||Fn(s),t=_t.get(e);if(t){if(t.open)return t;_t.delete(e)}let n=Il(s);return _t.set(e,n),n}function pt(s){let e=Fn(s);if(!ps.existsSync(e))return!1;try{let t=De(s);return t.prepare(`
|
|
9
9
|
SELECT value FROM index_metadata
|
|
10
10
|
WHERE key = 'index_completed'
|
|
11
|
-
`).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return
|
|
11
|
+
`).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return lt.debug({repoPath:s,error:t},"Error checking index status"),!1}}function us(s,e){let t=De(s),n=t.prepare("INSERT OR REPLACE INTO index_metadata (key, value, updated_at) VALUES (?, ?, unixepoch())");t.transaction(()=>{n.run("index_completed","true"),n.run("last_indexed_at",Date.now().toString()),e&&n.run("last_indexed_commit",e)})(),lt.debug({repoPath:s,commitSha:e},"Repository marked as indexed")}function fn(s){try{return De(s).prepare(`
|
|
12
12
|
SELECT value FROM index_metadata
|
|
13
13
|
WHERE key = 'last_indexed_commit'
|
|
14
|
-
`).get()?.value||null}catch(e){return
|
|
14
|
+
`).get()?.value||null}catch(e){return lt.debug({repoPath:s,error:e},"Error getting last indexed commit"),null}}function Wn(s){let e=On.get(s)||Fn(s),t=_t.get(e);t&&(t.open&&(lt.debug({repoPath:s,dbPath:e},"Closing database connection"),t.close()),_t.delete(e)),On.delete(s)}function Ir(){for(let[s,e]of _t.entries())try{e.open&&(lt.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){lt.error({dbPath:s,err:t},"Error closing database execution")}_t.clear()}var lt,_t,On,Lr,ut=ee(()=>{"use strict";G();Tr();lt=w.child({module:"db"});_t=new Map,On=new Map;process.on("exit",()=>Ir());Lr=s=>{lt.debug({signal:s},"Received termination signal, closing databases"),Ir(),process.exit(0)};process.on("SIGINT",()=>Lr("SIGINT"));process.on("SIGTERM",()=>Lr("SIGTERM"))});var pe,Ge=ee(()=>{"use strict";pe=class{db;constructor(e){this.db=e}get database(){return this.db}all(e,...t){return this.db.prepare(e).all(...t)}get(e,...t){return this.db.prepare(e).get(...t)}run(e,...t){return this.db.prepare(e).run(...t).changes}insert(e,...t){return this.db.prepare(e).run(...t).lastInsertRowid}transaction(e){return this.db.transaction(e)()}}});function Ml(s,e){if(!s)return!1;let t=s.trim();return!t||Ll.has(t.toLowerCase())||e.has(t)?!1:/^[A-Za-z_$][A-Za-z0-9_$.]*$/.test(t)}function Al(s){return s.split(/[,|&]/).map(e=>e.trim()).filter(Boolean)}function $l(s){let e=s.replace(/^[({\[]+/,"").replace(/[)}\]]+$/,"").replace(/^readonly\s+/,"").trim();return e&&e.match(/^([A-Za-z_$][A-Za-z0-9_$.]*)/)?.[1]||null}function Pl(s){let e=[],t=0,n="",i=!1;for(let r of s){if(r==="<"&&(t++,t===1)){i=!0,n="";continue}if(r===">"&&(t>0&&t--,t===0&&i)){i=!1,n.trim()&&e.push(n),n="";continue}i&&(n+=r)}return e}function Nl(s){let e=new Set;for(let t of s){let n=t.split(",").map(i=>i.trim());for(let i of n){let r=i.match(/^([A-Za-z_$][A-Za-z0-9_$]*)/);r?.[1]&&e.add(r[1])}}return e}function ds(s,e){let t=[];for(let n of Al(s)){let i=$l(n);i&&Ml(i,e)&&t.push(i)}return t}function Mr(s){if(!s)return[];let e=s.replace(/\s+/g," ").trim();if(!e)return[];let t=Pl(e),n=Nl(t),i=[],r=new Set,o=(l,p,u)=>{let d=`${l}:${p}`;r.has(d)||(r.add(d),i.push({relationship:l,targetName:p,...u?{metadata:u}:{}}))},a=e.match(/\bextends\s+(.+?)(?=\bimplements\b|\{|=|$)/);if(a?.[1]){let l=ds(a[1],n);for(let p of l)o("extends",p,a[1].trim())}let c=e.match(/\bimplements\s+(.+?)(?=\{|=|$)/);if(c?.[1]){let l=ds(c[1],n);for(let p of l)o("implements",p,c[1].trim())}for(let l of t){let p=/([A-Za-z_$][A-Za-z0-9_$]*)\s+extends\s+([^,>]+)/g,u=null;for(;(u=p.exec(l))!==null;){let d=u[2]?.trim();if(!d)continue;let h=ds(d,n);for(let m of h)o("constrained_by",m,d)}}return i}var Ll,Ar=ee(()=>{"use strict";Ll=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","symbol","object","bigint","readonly","keyof","infer","extends","implements","class","interface","type","function","new"])});import Dl from"path";var zn,$r=ee(()=>{"use strict";Ge();Ar();zn=class extends pe{findByPath(e){return this.get("SELECT * FROM files WHERE path = ?",e)}findAll(e){let t="SELECT * FROM files ORDER BY path ASC";return e&&(t+=` LIMIT ${e}`),this.all(t)}getAllPaths(){return this.all("SELECT path FROM files").map(t=>t.path)}findInSubPath(e,t){let n=Dl.resolve(e,t),i=n.endsWith("/")?n:n+"/";return this.all(`
|
|
15
15
|
SELECT * FROM files
|
|
16
16
|
WHERE (path LIKE ? OR path = ?)
|
|
17
17
|
ORDER BY path ASC
|
|
@@ -87,7 +87,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
|
|
|
87
87
|
SUBSTR(path, LENGTH(?) + 2) as relPath
|
|
88
88
|
FROM files
|
|
89
89
|
WHERE path LIKE ? || '/%/package.json'
|
|
90
|
-
`,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(i=>{for(let r of i)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,i){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),a=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),l=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),p=this.db.prepare("DELETE FROM type_graph_edges WHERE file_path = ?"),u=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),h=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),f=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),
|
|
90
|
+
`,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(i=>{for(let r of i)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,i){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),a=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),l=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),p=this.db.prepare("DELETE FROM type_graph_edges WHERE file_path = ?"),u=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),h=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),f=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),S=this.db.prepare("INSERT INTO type_graph_edges (file_path, source_symbol_id, source_symbol_name, target_symbol_name, relationship, line_number, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)"),y=this.db.prepare(`
|
|
91
91
|
INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
|
|
92
92
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
93
93
|
ON CONFLICT(path) DO UPDATE SET
|
|
@@ -97,7 +97,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
|
|
|
97
97
|
summary=excluded.summary,
|
|
98
98
|
embedding=excluded.embedding,
|
|
99
99
|
content_hash=excluded.content_hash
|
|
100
|
-
`),
|
|
100
|
+
`),_=this.db.transaction(R=>{for(let T of R){let{meta:k,exports:F,imports:B,configs:M,events:v,content:I,classification:$,summary:P,embedding:U,contentHash:A}=T;r.run(k.path),o.run(k.path),a.run(k.path),c.run(k.path),l.run(k.path),p.run(k.path);let H=A??(I&&n?n(I):null);if(y.run(k.path,k.mtime,Date.now(),$||"Unknown",P||"",U?JSON.stringify(U):null,H),F){let L=(D,J,z)=>{for(let g of J){let x=g.embedding?JSON.stringify(g.embedding):null,O=u.run(D,g.name,g.kind,g.signature,g.doc||"",g.line,g.endLine||g.line,g.classification||"Other",g.capabilities||"[]",z,x),C=Number(O.lastInsertRowid);if(Number.isFinite(C)){let W=Mr(g.signature);for(let j of W)j.targetName!==g.name&&S.run(D,C,g.name,j.targetName,j.relationship,g.line,j.metadata||null)}g.members&&g.members.length>0&&L(D,g.members,O.lastInsertRowid)}};L(k.path,F,null)}if(B)for(let L of B){let D=L.resolved_path!==void 0?L.resolved_path:i?.(L.module,k.path,t)??"";d.run(k.path,L.module,L.name,D)}if(M)for(let L of M)h.run(k.path,L.key,L.value,L.kind);if(I!==void 0&&m.run(k.path,I),v)for(let L of v)f.run(k.path,L.type,L.name,L.direction,L.line,L.snippet)}}),E=500;for(let R=0;R<e.length;R+=E)_(e.slice(R,R+E))}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}buildContentFtsQuery(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>=2).slice(0,12);if(t.length===0)return"";if(t.length===1)return`${t[0]}*`;let n=`"${t.join(" ")}"`,i=t.map(r=>`${r}*`).join(" OR ");return`${n} OR ${i}`}}});var Hn,Pr=ee(()=>{"use strict";Ge();Hn=class s extends pe{static HTTP_METHOD_EXPORTS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]);findByNameAndFile(e,t){return this.all("SELECT * FROM exports WHERE file_path = ? AND name = ?",t,e)}findByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ?",e)}findAtLine(e,t){return this.get(`
|
|
101
101
|
SELECT * FROM exports
|
|
102
102
|
WHERE file_path = ? AND start_line <= ? AND end_line >= ?
|
|
103
103
|
ORDER BY (end_line - start_line) ASC -- Get innermost symbol
|
|
@@ -215,7 +215,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
|
|
|
215
215
|
AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
|
|
216
216
|
ORDER BY e.file_path, e.start_line
|
|
217
217
|
LIMIT ?
|
|
218
|
-
`,t*2).filter(m=>!this.isFrameworkEntrypointExport(m)).map(m=>{let{confidence:f,reason:
|
|
218
|
+
`,t*2).filter(m=>!this.isFrameworkEntrypointExport(m)).map(m=>{let{confidence:f,reason:S}=this.scoreDeadExportConfidence(m);return{...m,confidence:f,reason:S}}),h=d;return a==="high"?h=d.filter(m=>m.confidence==="high"):a==="medium"&&(h=d.filter(m=>m.confidence==="high"||m.confidence==="medium")),h.slice(0,t)}scoreDeadExportConfidence(e){let t=e.file_path.toLowerCase(),n=e.name;return t.includes("/index.")||t.endsWith("index.ts")||t.endsWith("index.js")?{confidence:"low",reason:"Barrel/index file - likely re-export"}:e.kind==="TsInterfaceDeclaration"||e.kind==="TsTypeAliasDeclaration"?{confidence:"medium",reason:"Type definition - may be used externally"}:t.includes("/entry/")||t.includes("/bin/")||t.includes("main.")||t.includes("server.")||t.includes("cli.")?{confidence:"medium",reason:"Entry point - may be invoked externally"}:(t.includes("/components/")||t.endsWith(".tsx")||t.endsWith(".jsx"))&&/^[A-Z][A-Za-z0-9_]*$/.test(n)?{confidence:"medium",reason:"Component export - may be used by runtime composition"}:(t.includes("/contexts/")||t.includes("/context/"))&&(/Provider$/.test(n)||n.startsWith("use"))?{confidence:"medium",reason:"Context/provider export - may be wired dynamically"}:n.startsWith("create")||n.endsWith("Factory")||n.endsWith("Builder")?{confidence:"medium",reason:"Factory/builder pattern - may be used dynamically"}:n.startsWith("use")&&n.length>3?{confidence:"medium",reason:"Hook pattern - may be used in components"}:{confidence:"high",reason:"No detected usage"}}isFrameworkEntrypointExport(e){let n=e.file_path.toLowerCase().replace(/\\/g,"/"),i=e.name;return!!(/(^|\/)(src\/)?app\/.*\/route\.(t|j)sx?$/.test(n)&&s.HTTP_METHOD_EXPORTS.has(i)||/(^|\/)(src\/)?app\/.*\/(page|layout|loading|error|not-found|default|template)\.(t|j)sx?$/.test(n)||/(^|\/)(src\/)?middleware\.(t|j)sx?$/.test(n)||n.includes("/routes/")&&["loader","action","meta","headers"].includes(i))}getGravityMap(e=[],t){let n={},i=`
|
|
219
219
|
SELECT ws.symbol_id, m.name as mission_name, m.status
|
|
220
220
|
FROM working_set ws
|
|
221
221
|
JOIN missions m ON ws.mission_id = m.id
|
|
@@ -270,7 +270,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
|
|
|
270
270
|
'inbound' AS direction
|
|
271
271
|
FROM type_graph_edges
|
|
272
272
|
WHERE target_symbol_name = ?
|
|
273
|
-
`,p=[e];r&&(l+=" AND relationship = ?",p.push(r)),l+=" ORDER BY file_path ASC, line_number ASC, source_symbol_name ASC LIMIT ?",p.push(a),c.push(...this.all(l,...p))}return c.slice(0,a)}findTypeGraphEdgesBySymbolId(e,t={}){let n=this.findById(e);return n?this.findTypeGraphEdges(n.name,{...t,filePath:n.file_path}):[]}}});var
|
|
273
|
+
`,p=[e];r&&(l+=" AND relationship = ?",p.push(r)),l+=" ORDER BY file_path ASC, line_number ASC, source_symbol_name ASC LIMIT ?",p.push(a),c.push(...this.all(l,...p))}return c.slice(0,a)}findTypeGraphEdgesBySymbolId(e,t={}){let n=this.findById(e);return n?this.findTypeGraphEdges(n.name,{...t,filePath:n.file_path}):[]}}});var Nr,Dr=ee(()=>{"use strict";Nr=`
|
|
274
274
|
WITH RECURSIVE dependency_chain AS (
|
|
275
275
|
-- Base case: Direct dependents of the target symbol
|
|
276
276
|
-- Meaning: Files that import the file where the symbol is defined
|
|
@@ -321,7 +321,7 @@ SELECT DISTINCT
|
|
|
321
321
|
dc.imported_symbols
|
|
322
322
|
FROM dependency_chain dc
|
|
323
323
|
ORDER BY dc.depth, dc.consumer_path;
|
|
324
|
-
`});var
|
|
324
|
+
`});var Bn,Or=ee(()=>{"use strict";Ge();Dr();Bn=class extends pe{findByFile(e){return this.all("SELECT * FROM imports WHERE file_path = ?",e)}findByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM imports WHERE file_path IN (${t}) ORDER BY file_path`,...e)}getAllResolved(){return this.all(`
|
|
325
325
|
SELECT * FROM imports
|
|
326
326
|
WHERE resolved_path IS NOT NULL AND resolved_path != ''
|
|
327
327
|
`)}findDependents(e){return this.all("SELECT * FROM imports WHERE resolved_path = ?",e)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM imports WHERE file_path = ?",e)?.count||0}countDependents(e){return this.get("SELECT COUNT(*) as count FROM imports WHERE resolved_path = ?",e)?.count||0}getImportsForFile(e){return this.all("SELECT module_specifier, imported_symbols, resolved_path FROM imports WHERE file_path = ?",e)}findImportSource(e,t){return this.get(`
|
|
@@ -347,7 +347,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
347
347
|
SELECT COUNT(*) as count FROM imports
|
|
348
348
|
WHERE resolved_path IN (${n})
|
|
349
349
|
AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
|
|
350
|
-
`,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(
|
|
350
|
+
`,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(Nr,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});import{fileURLToPath as Ol}from"node:url";import{dirname as ms,join as Wr,resolve as Fl}from"node:path";import{existsSync as Wl}from"node:fs";function Hl(){let s=Fr;for(;s!==ms(s);){if(Wl(Wr(s,"package.json")))return s;s=ms(s)}return Fl(Fr,"..","..")}function Le(...s){return Wr(Hl(),...s)}var zl,Fr,Nt=ee(()=>{"use strict";zl=Ol(import.meta.url),Fr=ms(zl)});import{Worker as Bl}from"node:worker_threads";import{cpus as Ul}from"node:os";import{fileURLToPath as jl}from"node:url";import{dirname as Gl,join as zr}from"node:path";import{existsSync as Hr}from"node:fs";function ql(){if(Ur.endsWith(".ts")){let e=zr(Br,"worker.ts");if(Hr(e))return e}let s=zr(Br,"worker.js");return Hr(s)?s:Le("dist/logic/domain/embeddings/worker.js")}function Kt(s){return Yt||(Yt=new gn(s)),Yt}async function Un(){Yt&&(await Yt.shutdown(),Yt=null)}var Ur,Br,gn,Yt,jr=ee(()=>{"use strict";G();Nt();Ur=jl(import.meta.url),Br=Gl(Ur);gn=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;cacheDir;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(2,Ul().length-1)),this.cacheDir=e.cacheDir??"./.cache",this.initTimeout=e.initTimeout??6e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{w.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((n,i)=>{e=setTimeout(()=>i(new Error(`Worker pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0,w.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,w.info({numWorkers:this.workers.length},"Embedding worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=ql();w.debug({workerPath:e},"Resolved worker path");let t=[];for(let n=0;n<this.numWorkers;n++)n>0&&await new Promise(i=>setTimeout(i,25)),t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new Bl(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),a={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){w.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(a),w.debug({workerIndex:t},"Worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(a,c.id,c.embeddings||[]):c.type==="error"&&c.id&&this.handleTaskError(a,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),w.error({err:c,workerIndex:t},"Worker error"),a.currentTaskId&&this.handleTaskError(a,a.currentTaskId,c),!this.initialized){i(c);return}let l=this.workers.indexOf(a);l!==-1&&this.workers.splice(l,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{w.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&w.warn({workerIndex:t,code:c},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=128,n){if(this.initialized||await this.initialize(),e.length===0)return[];let i=[];for(let l=0;l<e.length;l+=t)i.push(e.slice(l,l+t));let r=new Array(i.length),o=0,a=i.map((l,p)=>new Promise((u,d)=>{let m={id:`task_${++this.taskIdCounter}`,texts:l,resolve:f=>{if(r[p]=f,o++,n){let S=Math.min(o*t,e.length);n(S,e.length)}u()},reject:f=>{if(r[p]=new Array(l.length).fill(null),o++,w.warn({err:f,chunkIndex:p},"Chunk embedding failed"),n){let S=Math.min(o*t,e.length);n(S,e.length)}u()}};this.taskQueue.push(m),this.processQueue()}));await Promise.all(a);let c=[];for(let l of r)c.push(...l);return w.info({total:e.length,successful:c.filter(l=>l!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),c}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}w.info({numWorkers:this.workers.length},"Shutting down embedding worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,w.info("Embedding worker pool shutdown complete")}},Yt=null});var Et={};cs(Et,{EmbeddingPriorityQueue:()=>fs,EmbeddingWorkerPool:()=>gn,cosineSimilarity:()=>qn,generateEmbedding:()=>ys,generateEmbeddingsBatch:()=>bs,getDefaultPool:()=>Kt,setUseWorkerThreads:()=>Gn,shutdownDefaultPool:()=>Un});async function Vl(){return yn||(yn=await import("@xenova/transformers"),yn.env.cacheDir="./.cache",yn.env.allowLocalModels=!0),yn}function Gn(s){gs=s,w.info({useWorkerThreads:s},"Worker thread mode updated")}function Gr(s=!1){let e=(bn||"").toLowerCase(),t={};return bn&&(t.dtype=bn),s?(t.quantized=!1,t):(e==="fp32"||e==="fp16"||e==="float32"||e==="float16"?t.quantized=!1:e.startsWith("q")&&(t.quantized=!0),t)}async function Jl(){w.info({model:jn,dtype:bn},"Loading embedding model...");let{pipeline:s}=await Vl(),e=Gr(!1);try{return await s("feature-extraction",jn,e)}catch(t){let n=t?.message||"";if(!(n.includes("/onnx/model_quantized.onnx")||n.includes("model_quantized.onnx")))throw t;return w.warn({model:jn,dtype:bn},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",jn,Gr(!0))}}async function Vr(){return hs||(hs=Jl()),hs}async function ys(s){try{let t=await(await Vr())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return w.error({err:e},"Failed to generate embedding"),null}}async function bs(s,e=qr,t){return s.length===0?[]:gs?Kt().generateEmbeddings(s,e,t):Jr(s,e,t)}async function Jr(s,e,t){let n=new Array(s.length).fill(null),i=await Vr();for(let r=0;r<s.length;r+=e){let o=Math.min(r+e,s.length),a=s.slice(r,o);try{let c=await i(a,{pooling:"mean",normalize:!0}),[l,p]=c.dims;for(let u=0;u<l;u++){let d=u*p,h=d+p;n[r+u]=Array.from(c.data.slice(d,h))}}catch(c){w.error({err:c,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let l=0;l<a.length;l++)try{let p=a[l];if(!p||p.trim().length===0)continue;let u=await i(p,{pooling:"mean",normalize:!0});n[r+l]=Array.from(u.data)}catch{n[r+l]=null}}t&&t(o,s.length)}return w.debug({total:s.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function qn(s,e){let t=0,n=0,i=0;for(let r=0;r<s.length;r++)t+=s[r]*e[r],n+=s[r]*s[r],i+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(i))}var jn,bn,yn,qr,gs,hs,fs,qe=ee(()=>{"use strict";G();jr();jn=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",bn=process.env.EMBEDDING_DTYPE??"fp32",yn=null;qr=128,gs=!1;hs=null;fs=class{queue=[];processing=!1;results=new Map;enqueue(e){this.queue.push(e),this.queue.sort((t,n)=>n.priority-t.priority)}enqueueMany(e){this.queue.push(...e),this.queue.sort((t,n)=>n.priority-t.priority)}get size(){return this.queue.length}get isProcessing(){return this.processing}getResult(e){return this.results.get(e)}async processQueue(e=qr,t){if(this.processing)return w.warn("Queue processing already in progress"),this.results;this.processing=!0;let n=this.queue.length;try{gs?await this.processQueueParallel(e,n,t):await this.processQueueSequential(e,n,t)}finally{this.processing=!1}return this.results}async processQueueSequential(e,t,n){for(;this.queue.length>0;){let i=this.queue.splice(0,e),r=i.map(a=>a.text),o=await Jr(r,r.length);if(i.forEach((a,c)=>{this.results.set(a.id,o[c])}),n){let a=t-this.queue.length;n(a,t)}}}async processQueueParallel(e,t,n){let i=this.queue.splice(0),r=i.map(c=>c.text),a=await Kt().generateEmbeddings(r,e,(c,l)=>{n&&n(c,l)});i.forEach((c,l)=>{this.results.set(c.id,a[l])})}clear(){this.queue=[],this.results.clear()}}});var Vn,Yr=ee(()=>{"use strict";Ge();Vn=class extends pe{findById(e){return this.get("SELECT * FROM missions WHERE id = ?",e)}findByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM missions WHERE id IN (${t})`,...e)}findActive(e){let t="SELECT * FROM missions WHERE status IN ('in-progress', 'planned', 'verifying')",n=[];return e&&(t+=" AND git_branch = ?",n.push(e)),t+=` ORDER BY
|
|
351
351
|
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
352
352
|
created_at ASC`,this.all(t,...n)}findAll(e){let t="SELECT * FROM missions",n=[];return e&&(t+=" WHERE status = ?",n.push(e)),t+=` ORDER BY
|
|
353
353
|
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
@@ -438,7 +438,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
438
438
|
SELECT linked_repo_path, linked_mission_id, relationship, direction
|
|
439
439
|
FROM cross_repo_links
|
|
440
440
|
WHERE mission_id = ?
|
|
441
|
-
`,e)}catch{return[]}}findLastMission(){return this.get("SELECT * FROM missions ORDER BY updated_at DESC, id DESC LIMIT 1")}findActiveByPriority(){return this.get("SELECT * FROM missions WHERE status IN ('in-progress', 'active', 'verifying') ORDER BY CASE WHEN status = 'in-progress' THEN 0 ELSE 1 END, created_at ASC LIMIT 1")}addHandoff(e,t){let n=JSON.stringify(t),i=e??0,r=this.insert("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",i,"handoff",t.kind,n),o=[`[handoff:${t.kind}]`,...t.findings.map(a=>a.statement),...t.risks.map(a=>a.description),...t.gaps].filter(Boolean).join(" ");return Promise.resolve().then(()=>(
|
|
441
|
+
`,e)}catch{return[]}}findLastMission(){return this.get("SELECT * FROM missions ORDER BY updated_at DESC, id DESC LIMIT 1")}findActiveByPriority(){return this.get("SELECT * FROM missions WHERE status IN ('in-progress', 'active', 'verifying') ORDER BY CASE WHEN status = 'in-progress' THEN 0 ELSE 1 END, created_at ASC LIMIT 1")}addHandoff(e,t){let n=JSON.stringify(t),i=e??0,r=this.insert("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",i,"handoff",t.kind,n),o=[`[handoff:${t.kind}]`,...t.findings.map(a=>a.statement),...t.risks.map(a=>a.description),...t.gaps].filter(Boolean).join(" ");return Promise.resolve().then(()=>(qe(),Et)).then(({generateEmbedding:a})=>a(o)).then(a=>{a&&this.run("UPDATE mission_artifacts SET embedding = ? WHERE id = ?",JSON.stringify(a),r)}).catch(()=>{}),r}getHandoffs(e,t,n=20){let i=["type = 'handoff'"],r=[];e!==void 0&&(i.push("mission_id = ?"),r.push(e??0)),t&&(i.push("identifier = ?"),r.push(t));let o=`SELECT * FROM mission_artifacts WHERE ${i.join(" AND ")} ORDER BY created_at DESC LIMIT ?`;return r.push(n),this.all(o,...r)}async findSemanticHandoffs(e,t=5){let{cosineSimilarity:n}=await Promise.resolve().then(()=>(qe(),Et)),i=this.all("SELECT * FROM mission_artifacts WHERE type = 'handoff' AND embedding IS NOT NULL"),r=[];for(let o of i)try{let a=JSON.parse(o.embedding),c=n(e,a);c>.3&&r.push({...o,similarity:c})}catch{}return r.sort((o,a)=>a.similarity-o.similarity).slice(0,t)}}});var Jn,Kr=ee(()=>{"use strict";Ge();G();Jn=class s extends pe{findByMission(e,t=50){return this.all(`
|
|
442
442
|
SELECT
|
|
443
443
|
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
444
444
|
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
@@ -459,7 +459,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
459
459
|
`,e)}create(e){let t=this.insert(`
|
|
460
460
|
INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
|
|
461
461
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
462
|
-
`,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha);return s.EMBEDDABLE_TYPES.has(e.type)&&this.generateAndStoreEmbedding(Number(t),e).catch(n=>{
|
|
462
|
+
`,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha);return s.EMBEDDABLE_TYPES.has(e.type)&&this.generateAndStoreEmbedding(Number(t),e).catch(n=>{w.debug({err:n,intentLogId:t},"Failed to generate intent log embedding")}),t}static EMBEDDABLE_TYPES=new Set(["decision","discovery","fix","blocker","note","heritage","crystal"]);static buildEmbeddingText(e){let t=[`[${e.type}]`];return e.symbol_name&&t.push(`symbol: ${e.symbol_name}`),e.file_path&&t.push(`file: ${e.file_path.split("/").pop()}`),t.push(e.content),t.join(" ")}async generateAndStoreEmbedding(e,t){let{generateEmbedding:n}=await Promise.resolve().then(()=>(qe(),Et)),i=s.buildEmbeddingText(t),r=await n(i);r&&this.run("UPDATE intent_logs SET embedding = ? WHERE id = ?",JSON.stringify(r),e)}findWithEmbeddings(){return this.all("SELECT * FROM intent_logs WHERE embedding IS NOT NULL AND type NOT IN ('system', 'lapsed')")}async findSemanticMatches(e,t,n){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(qe(),Et)),r=this.findWithEmbeddings();if(r.length>5e3)return w.warn({count:r.length},"Intent log count exceeds brute-force vector scan limit (5000). Skipping semantic recall."),[];let o=[];for(let a of r)if(!(n&&a.symbol_id===n))try{let c=JSON.parse(a.embedding),l=i(e,c);l>.25&&o.push({id:a.id,mission_id:a.mission_id,type:a.type,content:a.content,symbol_name:a.symbol_name,file_path:a.file_path,similarity:l,created_at:a.created_at})}catch{}return o.sort((a,c)=>c.similarity-a.similarity).slice(0,t)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${i} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
|
|
463
463
|
SELECT id, file_path, symbol_name, signature
|
|
464
464
|
FROM intent_logs
|
|
465
465
|
WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
|
|
@@ -522,32 +522,85 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
522
522
|
FROM intent_logs
|
|
523
523
|
WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
524
524
|
AND created_at > ?
|
|
525
|
-
ORDER BY created_at DESC LIMIT ?`,e,n.created_at,t-1);return[n,...i]}return this.findByMission(e,t)}async findSemanticTheme(e,t,n=200){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(
|
|
526
|
-
VALUES (NULL, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,n);if(t.length>0){let r=t.map(()=>"?").join(",");this.run(`UPDATE intent_logs SET is_crystallized = 1, crystal_id = ? WHERE id IN (${r})`,i,...t)}return i})}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:n}=await Promise.resolve().then(()=>(
|
|
525
|
+
ORDER BY created_at DESC LIMIT ?`,e,n.created_at,t-1);return[n,...i]}return this.findByMission(e,t)}async findSemanticTheme(e,t,n=200){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(qe(),Et)),r=this.findWithEmbeddings(),o=[];for(let a of r)if(s.EMBEDDABLE_TYPES.has(a.type)&&!(t&&a.mission_id!==null&&!t.includes(a.mission_id)))try{let c=JSON.parse(a.embedding),l=i(e,c);l>.35&&o.push({...a,_similarity:l})}catch{}return o.sort((a,c)=>c._similarity-a._similarity).slice(0,n).map(({_similarity:a,...c})=>c)}crystallizeTheme(e,t,n){return this.transaction(()=>{let i=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
|
|
526
|
+
VALUES (NULL, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,n);if(t.length>0){let r=t.map(()=>"?").join(",");this.run(`UPDATE intent_logs SET is_crystallized = 1, crystal_id = ? WHERE id IN (${r})`,i,...t)}return i})}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:n}=await Promise.resolve().then(()=>(qe(),Et)),i=[...s.EMBEDDABLE_TYPES].map(p=>`'${p}'`).join(","),r=this.all(`SELECT * FROM intent_logs WHERE embedding IS NULL AND type IN (${i})`);if(r.length===0)return 0;let o=r.map(p=>s.buildEmbeddingText(p)),a=await n(o,e,t),c=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),l=0;return this.transaction(()=>{for(let p=0;p<r.length;p++)a[p]&&(c.run(JSON.stringify(a[p]),r[p].id),l++)}),w.info({total:r.length,embedded:l},"Intent log embedding backfill complete"),l}}});var Yn,Qr=ee(()=>{"use strict";Ge();Yn=class extends pe{findByKey(e,t=20){return this.all(`
|
|
527
527
|
SELECT file_path, key, value, kind
|
|
528
528
|
FROM configs
|
|
529
529
|
WHERE key LIKE ? OR value LIKE ?
|
|
530
530
|
LIMIT ?
|
|
531
|
-
`,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",i=[];return e&&(n+=" WHERE kind = ?",i.push(e)),n+=" LIMIT ?",i.push(t),this.all(n,...i)}findEnvValue(e){return this.get("SELECT value FROM configs WHERE key LIKE ? OR key = ? LIMIT 1",`%:env:${e}`,e)?.value}countByKind(e){return this.get("SELECT COUNT(*) as count FROM configs WHERE kind = ?",e)?.count||0}getAll(){return this.all("SELECT key, value, kind, file_path FROM configs")}}});var
|
|
531
|
+
`,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",i=[];return e&&(n+=" WHERE kind = ?",i.push(e)),n+=" LIMIT ?",i.push(t),this.all(n,...i)}findEnvValue(e){return this.get("SELECT value FROM configs WHERE key LIKE ? OR key = ? LIMIT 1",`%:env:${e}`,e)?.value}countByKind(e){return this.get("SELECT COUNT(*) as count FROM configs WHERE kind = ?",e)?.count||0}getAll(){return this.all("SELECT key, value, kind, file_path FROM configs")}}});var Kn,Zr=ee(()=>{"use strict";Ge();Kn=class extends pe{search(e,t=10){return this.all(`
|
|
532
532
|
SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
|
|
533
533
|
FROM content_fts
|
|
534
534
|
WHERE content_fts MATCH ?
|
|
535
535
|
LIMIT ?
|
|
536
|
-
`,e,t)}}});var
|
|
537
|
-
WHERE query LIKE ? ORDER BY created_at DESC LIMIT ?`,`${e}%`,t):this.findRecent(t)}pruneIfNeeded(){(this.get("SELECT COUNT(*) as count FROM search_history")?.count??0)<=
|
|
536
|
+
`,e,t)}}});var Xr,Qn,eo=ee(()=>{"use strict";Ge();Xr=500,Qn=class extends pe{record(e,t,n=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,n),this.pruneIfNeeded()}findRecent(e=20){return this.all("SELECT id, query, mode, branch, created_at FROM search_history ORDER BY created_at DESC LIMIT ?",e)}findRecentByQueryPrefix(e,t=10){return e.trim()?this.all(`SELECT id, query, mode, branch, created_at FROM search_history
|
|
537
|
+
WHERE query LIKE ? ORDER BY created_at DESC LIMIT ?`,`${e}%`,t):this.findRecent(t)}pruneIfNeeded(){(this.get("SELECT COUNT(*) as count FROM search_history")?.count??0)<=Xr||this.run(`DELETE FROM search_history WHERE id NOT IN (
|
|
538
538
|
SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
|
|
539
|
-
)`,
|
|
539
|
+
)`,Xr)}}});var Zn,to=ee(()=>{"use strict";Ge();Zn=class extends pe{getSection(e){return this.get("SELECT section, data, updated_at FROM hologram_snapshot WHERE section = ?",e)}getAllSections(){return this.all("SELECT section, data, updated_at FROM hologram_snapshot ORDER BY section")}upsertSection(e,t){this.run(`
|
|
540
540
|
INSERT INTO hologram_snapshot (section, data, updated_at)
|
|
541
541
|
VALUES (?, ?, unixepoch())
|
|
542
542
|
ON CONFLICT(section) DO UPDATE SET
|
|
543
543
|
data = excluded.data,
|
|
544
544
|
updated_at = excluded.updated_at
|
|
545
|
-
`,e,t)}deleteSection(e){this.run("DELETE FROM hologram_snapshot WHERE section = ?",e)}deleteAll(){this.run("DELETE FROM hologram_snapshot")}hasSection(e){return(this.get("SELECT COUNT(*) as count FROM hologram_snapshot WHERE section = ?",e)?.count??0)>0}}});var O,V=Z(()=>{"use strict";Ze();lr();pr();mr();Tr();Rr();kr();Cr();Lr();$r();O=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=Te(e),o=t.files?.database,a=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!a)return t;this.repositoryCache.delete(e)}let n=Te(e),i={files:new Cn(n),exports:new In(n),imports:new Ln(n),missions:new Nn(n),intentLogs:new Dn(n),configs:new On(n),content:new Fn(n),searchHistory:new Wn(n),hologram:new Hn(n)};return this.repositoryCache.set(e,i),i}static closeInstance(e){this.repositoryCache.delete(e),kn(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var Mr=jc((gh,is)=>{var Un=process||{},Ar=Un.argv||[],zn=Un.env||{},Cl=!(zn.NO_COLOR||Ar.includes("--no-color"))&&(!!zn.FORCE_COLOR||Ar.includes("--color")||Un.platform==="win32"||(Un.stdout||{}).isTTY&&zn.TERM!=="dumb"||!!zn.CI),Il=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+Ll(i,e,t,r)+e:s+i+e},Ll=(s,e,t,n)=>{let i="",r=0;do i+=s.substring(r,n)+t,r=n+e.length,n=s.indexOf(e,r);while(~n);return i+s.substring(r)},Pr=(s=Cl)=>{let e=s?Il:()=>String;return{isColorSupported:s,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};is.exports=Pr();is.exports.createColors=Pr});var ai,ci,Co,li,Io,Lo,$o,Ao,Po,Mo,No,Do,Oo,Fo,mn,pi,Wo,Ho,ys=Z(()=>{"use strict";ai=[/\/pages\/(?!_)[^/]+\.(tsx?|jsx?)$/i,/\/pages\/.*\/index\.(tsx?|jsx?)$/i,/\/app\/.*\/page\.(tsx?|jsx?)$/i,/\/app\/.*\/layout\.(tsx?|jsx?)$/i,/\/app\/api\/.*\/route\.(ts|js)$/i,/\/pages\/api\/.*\.(ts|js)$/i],ci=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],Co=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],li=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],Io=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],Lo=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],$o=[/\/commands?\/[^/]+\.(ts|js|py|php)$/i,/\/cli\/[^/]+\.(ts|js|py|php)$/i,/\/bin\/[^/]+\.(ts|js|py|php)$/i,/cli\.(ts|js|py|php)$/i,/main\.(ts|js|py|php)$/i],Ao=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],Po=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],Mo=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],No=[/\/stores?\//i,/\/slices?\//i,/\/reducers?\//i,/\/atoms?\//i,/\/selectors?\//i,/\.(store|slice|reducer|atom|selector)\.(ts|js)$/i,/.*Slice\.(ts|js)$/i,/.*Store\.(ts|js)$/i],Do=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],Oo=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],Fo=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],mn=[/\.(model|entity|schema|repository|repo|dao|migration|query|mutation|resolver|connection|db)\.(ts|js)$/i,/queries\.(ts|js)$/i,/mutations\.(ts|js)$/i,/resolvers\.(ts|js)$/i,/connection\.(ts|js)$/i,/\/models?\//i,/\/entities?\//i,/\/repositories?\//i,/\/repos?\//i,/\/data\//i,/\/database\//i,/\/prisma\//i,/\/drizzle\//i,/\/api\/.*client\.(ts|js|tsx)$/i,/(^|\/)[A-Z0-9_-]*API\.(tsx?|js|jsx)$/],pi=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],Wo=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],Ho=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var ui,Uo,di,jo,bs=Z(()=>{"use strict";ui=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],Uo=[/views\.py$/i,/forms\.py$/i,/serializers\.py$/i,/admin\.py$/i,/apps\.py$/i,/tasks\.py$/i,/middlewares?\.py$/i,/signals?\.py$/i,/context_processors\.py$/i],di=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],jo=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var mi,Go,hi,qo,_s=Z(()=>{"use strict";mi=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],Go=[/\/services?\/.*\.php$/i,/\/providers?\/.*\.php$/i,/\/middleware\/.*\.php$/i,/\/jobs?\/.*\.php$/i,/\/listeners?\/.*\.php$/i,/\/events?\/.*\.php$/i,/\/observers?\/.*\.php$/i,/\/console\/commands\/.*\.php$/i,/\/actions?\/.*\.php$/i,/\/traits?\/.*\.php$/i,/\/concerns?\/.*\.php$/i,/\/contracts?\/.*\.php$/i],hi=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],qo=["laravel","symfony","slim","cakephp","codeigniter"]});import Jo from"path";function Ct(s,e,t){let n=[],i="Unknown",r=0;t||(t=Rp(s,e));let{inDegree:o,outDegree:a}=t,c=(d,h,m,f)=>{for(let _ of d)if(_.test(s))return n.push(`${f}: ${_.source}`),i=h,r+=m,!0;return!1},l=!1;if(l||(l=c(ai,"Entry",45,"Next.js entry")),l||(l=c(Io,"Entry",40,"MCP handler")),l||(l=c($o,"Entry",40,"CLI command")),l||(l=c(mn,"Data",45,"Data layer/Repository")),l||(l=c(No,"Data",35,"State management")),l||(l=c(Co,"Logic",40,"React component")),l||(l=c(li,"Logic",35,"Logic pattern")),l||(l=c(Ao,"Logic",35,"Parser/AST")),l||(l=c(Po,"Logic",35,"Core module")),l||(l=c(Mo,"Logic",30,"UI layer")),l||(l=c(Fo,"Types",35,"Type definition")),l||(l=c(ui,"Entry",40,"Python Entry")),l||(l=c(di,"Data",40,"Python Data")),l||(l=c(Uo,"Logic",35,"Python Logic")),l||(l=c(mi,"Entry",40,"PHP Entry")),l||(l=c(hi,"Data",40,"PHP Data")),l||(l=c(Go,"Logic",35,"PHP Logic")),l||(l=c(Do,"Logic",35,"Hook/Context")),!l){for(let d of Lo)if(d.test(s)){n.push(`MCP utility: ${d.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,l=!0;break}}l||c(Oo,"Data",35,"Schema definition")&&(l=!0),l||(c(mn,"Data",30,"Path matches data pattern")||c(pi,"Utility",25,"Path matches utility pattern")||c(ci,"Entry",30,"Path matches entry pattern"))&&(l=!0);for(let d of Es)if(d.test(s)){n.push(`Test file: ${d.source}`),i="Test",r=50,l=!0;break}l||c(Ss,"Infrastructure",40,"Infrastructure")&&(l=!0);for(let d of Tp)d.test(s)&&(n.push(`Monorepo component: ${d.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let u=e.imports.getImportsForFile(s).map(d=>d.module_specifier.toLowerCase());for(let d of Ho)if(u.some(h=>h.includes(d))){n.push(`Imports JS data library: ${d}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let d of jo)if(u.some(h=>h.includes(d))){n.push(`Imports Python framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of qo)if(u.some(h=>h.includes(d))){n.push(`Imports PHP framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of Wo)if(u.some(h=>h.includes(d))){n.push(`Imports JS framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}if(o===0&&a>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),i==="Unknown"?(i="Entry",r+=30):i==="Entry"&&(r+=15)),o>5&&a<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),i==="Unknown"?(i="Utility",r+=25):i==="Utility"&&(r+=10)),i==="Unknown"&&o>0&&a>0){let d=o/(o+a);d>.3&&d<.7&&(n.push(`Balanced traffic: in=${o}, out=${a} (likely Logic layer)`),i="Logic",r+=25)}return i==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:i,confidence:r,signals:n}}function Rp(s,e){let t=e.imports.countDependents(s),n=e.imports.countByFile(s);return{inDegree:t,outDegree:n}}function mt(s,e){let t=s.files.getAllPaths().map(m=>({path:m})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let m of t){let f=Ct(m.path,s);n.set(m.path,f),i[f.layer].push({path:m.path,classification:f})}let r={Entry:dt(i.Entry,e),Logic:dt(i.Logic,e),Data:dt(i.Data,e),Utility:dt(i.Utility,e),Infrastructure:dt(i.Infrastructure,e),Test:dt(i.Test,e),Types:dt(i.Types,e),Unknown:dt(i.Unknown,e)},o={};t.forEach(m=>{let f=Jo.extname(m.path).toLowerCase();f&&(o[f]=(o[f]||0)+1)});let a={".ts":"TypeScript",".tsx":"Typescript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".php":"PHP",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".vue":"Vue"},c={};Object.entries(o).forEach(([m,f])=>{let _=a[m];_&&(c[_]=(c[_]||0)+f)});let l=Object.entries(c).sort((m,f)=>f[1]-m[1]),p=l.length>0?l[0][0]:"Unknown",{pattern:u,patternConfidence:d,insights:h}=kp(r,t.length,s);return{pattern:u,patternConfidence:d,layers:r,insights:h,primaryStack:p}}function dt(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:Jo.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function kp(s,e,t){let n=[],i="Unknown",r=0,o=s.Entry.count/e*100,a=s.Logic.count/e*100,c=s.Data.count/e*100,l=s.Utility.count/e*100,p=s.Unknown.count/e*100;o>5&&a>10&&c>5&&p<40?(i="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${a.toFixed(1)}%), Data (${c.toFixed(1)}%)`)):l>20?(i="Modular",r=50+l/2,n.push(`High shared module usage: ${l.toFixed(1)}% utility files`)):p>60&&(i="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let u=t.configs.countByKind("Service");return u>3&&(i="Microservices",r=55+u*5,n.push(`Detected ${u} service definitions (likely microservices)`)),s.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),s.Data.count===0&&n.push("\u26A0\uFE0F No data layer detected - repository may not use traditional ORM patterns"),l>30&&n.push(`High utility concentration (${l.toFixed(1)}%) - good reusability`),{pattern:i,patternConfidence:Math.min(100,r),insights:n}}var Es,Ss,Tp,It=Z(()=>{"use strict";ys();bs();_s();Es=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],Ss=[/Dockerfile/i,/docker-compose/i,/\.ya?ml$/i,/nginx\.conf/i,/\/infra\//i,/\/deploy\//i,/\/k8s\//i,/\/kubernetes\//i,/\/terraform\//i,/\/ansible\//i,/package\.json/i,/tsconfig.*\.json/i,/\.env/i],Tp=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});function wu(s){try{return JSON.stringify(s)}catch{return String(s)}}function At(s){if(s instanceof Error)return s.message;if(typeof s=="string")return s;if(s&&typeof s=="object"&&"message"in s){let e=s.message;if(typeof e=="string"&&e.trim())return e}return wu(s)}function ye(s){if(s instanceof Error){let e;return"cause"in s&&s.cause!==void 0&&(e=At(s.cause)),{errorName:s.name||"Error",errorMessage:s.message,errorStack:s.stack,...e?{errorCause:e}:{}}}return s&&typeof s=="object"?{errorName:s.constructor?.name||"Object",errorMessage:At(s)}:{errorName:typeof s,errorMessage:At(s)}}var gn=Z(()=>{"use strict"});var wa={};qi(wa,{HologramService:()=>Se});var Oe,Se,Gt=Z(()=>{"use strict";V();It();q();gn();Oe=S.child({module:"hologram"}),Se=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=O.getInstance(e)}updateTopography(e){Oe.debug({repoPath:this.repoPath},"Updating topography snapshot");let t=Object.values(e.layers).reduce((r,o)=>r+o.count,0),n={};for(let[r,o]of Object.entries(e.layers)){let a=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(a*10)/10,topFiles:o.topFiles.slice(0,3).map(c=>({path:c.path,confidence:c.confidence}))}}let i={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(i)),Oe.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=mt(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){Oe.debug({repoPath:this.repoPath,count:e.length},"Updating gravity zones");let t={hotspots:e.slice(0,50),updatedAt:Date.now()};this.repos.hologram.upsertSection("gravity",JSON.stringify(t)),Oe.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){Oe.debug({repoPath:this.repoPath,count:e.length},"Updating ghost bridges");let t={bridges:e.slice(0,20),updatedAt:Date.now()};this.repos.hologram.upsertSection("ghosts",JSON.stringify(t)),Oe.info({repoPath:this.repoPath},"Ghost bridges updated")}getSnapshot(){let e=this.repos.hologram.getAllSections(),t={metadata:{repoPath:this.repoPath,lastUpdated:Date.now(),version:"1.0.0"}};for(let n of e)try{let i=JSON.parse(n.data);switch(n.section){case"topography":t.topography=i;break;case"gravity":t.gravity=i;break;case"ghosts":t.ghosts=i;break}}catch(i){Oe.debug({repoPath:this.repoPath,section:n.section,...ye(i)},"Skipping malformed hologram section")}return t}getSection(e){let t=this.repos.hologram.getSection(e);if(!t)return null;try{return JSON.parse(t.data)}catch(n){return Oe.debug({repoPath:this.repoPath,section:e,...ye(n)},"Skipping malformed hologram section"),null}}computeGravityZones(){Oe.debug({repoPath:this.repoPath},"Computing gravity zones from import graph");let e=this.repos.files.getAllPaths(),t=new Map;for(let i of e){let r=Ct(i,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(i);if(o.length===0)continue;let a=this.repos.imports.countDependents(i),c=this.repos.imports.countByFile(i),l=a*2+c;if(l>0){let p=o.find(d=>d.kind!=="TsTypeAliasDeclaration"&&d.kind!=="TsInterfaceDeclaration")||o[0],u=`${i}::${p.name}`;t.set(u,{symbol:p.name,filePath:i,inDegree:a,outDegree:c,gravity:l})}}let n=Array.from(t.values()).sort((i,r)=>r.gravity-i.gravity).slice(0,50);return Oe.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),Oe.info({repoPath:this.repoPath},"Hologram cleared")}}});var pc={};qi(pc,{GraphExporterService:()=>Vs});var lc,Vs,uc=Z(()=>{"use strict";V();q();lc=S.child({module:"graph-exporter"}),Vs=class{constructor(e){this.repoPath=e;this.repos=O.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;lc.info({focusMissionId:i,depth:r,format:n,includeCompleted:t},"Generating mission graph");let a=this.buildMissionTree(i,t,r,o);return n==="json"?JSON.stringify(a,null,2):this.generateMermaidDiagram(a)}buildMissionTree(e,t,n,i){let r;if(e){let c=this.repos.missions.findById(e);r=c?[c]:[]}else r=this.repos.missions.findAll().filter(l=>!l.parent_id),t||(r=r.filter(l=>l.status!=="completed"));let o=0,a=[];for(let c of r){if(o>=i)break;let l=this.buildNode(c,t,n,1,{count:o,max:i});l&&(a.push(l),o+=this.countNodes(l))}return a}buildNode(e,t,n,i,r){if(i>n||r.count>=r.max)return null;let o;if(e.strategy_graph)try{let p=JSON.parse(e.strategy_graph);o=this.parseStrategySteps(p)}catch(p){lc.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let a={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},c=this.repos.missions.findByParentId(e.id),l=t?c:c.filter(p=>p.status!=="completed");for(let p of l){if(r.count>=r.max)break;let u=this.buildNode(p,t,n,i+1,r);u&&(a.children.push(u),r.count++)}return a}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,i)=>({id:n.id||`step-${i}`,description:n.description||n.content||n.name||`Step ${i+1}`,status:n.status,dependencies:n.dependencies||n.deps})):e.steps&&Array.isArray(e.steps)?this.parseStrategySteps(e.steps):typeof e=="object"?Object.entries(e).map(([n,i])=>({id:n,description:i.description||i.content||n,status:i.status,dependencies:i.dependencies||i.deps})):t}countNodes(e){let t=1;for(let n of e.children)t+=this.countNodes(n);return t}generateMermaidDiagram(e){let t=["graph TD"];for(let n of e)this.addMermaidNode(n,t);return t.join(`
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
${
|
|
549
|
-
|
|
550
|
-
|
|
545
|
+
`,e,t)}deleteSection(e){this.run("DELETE FROM hologram_snapshot WHERE section = ?",e)}deleteAll(){this.run("DELETE FROM hologram_snapshot")}hasSection(e){return(this.get("SELECT COUNT(*) as count FROM hologram_snapshot WHERE section = ?",e)?.count??0)>0}}});var Xn,no=ee(()=>{"use strict";Ge();Xn=class extends pe{claimFile(e,t){try{this.run(`
|
|
546
|
+
INSERT INTO file_claims (file_path, mission_id, claimed_at, updated_at)
|
|
547
|
+
VALUES (?, ?, unixepoch(), unixepoch())
|
|
548
|
+
`,e,t);let n=this.getClaim(e);if(!n)throw new Error(`Failed to hydrate claim after insert for file ${e}`);return{status:"claimed",claim:n}}catch{let n=this.getClaim(e);if(!n)throw new Error(`Failed to read existing claim for file ${e}`);return n.mission_id===t?(this.run("UPDATE file_claims SET updated_at = unixepoch() WHERE file_path = ?",e),{status:"already_claimed",claim:this.getClaim(e)??n}):{status:"conflict",claim:n}}}releaseFile(e,t){let n=this.getClaim(e);return n?t!==void 0&&n.mission_id!==t?{released:!1,reason:"not_owner",claim:n}:(this.run("DELETE FROM file_claims WHERE file_path = ?",e),{released:!0}):{released:!1,reason:"not_found"}}releaseAllForMission(e){return this.run("DELETE FROM file_claims WHERE mission_id = ?",e)}getClaim(e){return this.get(`
|
|
549
|
+
SELECT
|
|
550
|
+
fc.file_path,
|
|
551
|
+
fc.mission_id,
|
|
552
|
+
fc.claimed_at,
|
|
553
|
+
fc.updated_at,
|
|
554
|
+
m.name AS mission_name,
|
|
555
|
+
m.status AS mission_status,
|
|
556
|
+
m.git_branch AS mission_branch
|
|
557
|
+
FROM file_claims fc
|
|
558
|
+
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
559
|
+
WHERE fc.file_path = ?
|
|
560
|
+
`,e)}getClaimsForMission(e){return this.all(`
|
|
561
|
+
SELECT
|
|
562
|
+
fc.file_path,
|
|
563
|
+
fc.mission_id,
|
|
564
|
+
fc.claimed_at,
|
|
565
|
+
fc.updated_at,
|
|
566
|
+
m.name AS mission_name,
|
|
567
|
+
m.status AS mission_status,
|
|
568
|
+
m.git_branch AS mission_branch
|
|
569
|
+
FROM file_claims fc
|
|
570
|
+
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
571
|
+
WHERE fc.mission_id = ?
|
|
572
|
+
ORDER BY fc.file_path ASC
|
|
573
|
+
`,e)}listClaims(){return this.all(`
|
|
574
|
+
SELECT
|
|
575
|
+
fc.file_path,
|
|
576
|
+
fc.mission_id,
|
|
577
|
+
fc.claimed_at,
|
|
578
|
+
fc.updated_at,
|
|
579
|
+
m.name AS mission_name,
|
|
580
|
+
m.status AS mission_status,
|
|
581
|
+
m.git_branch AS mission_branch
|
|
582
|
+
FROM file_claims fc
|
|
583
|
+
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
584
|
+
ORDER BY fc.updated_at DESC, fc.file_path ASC
|
|
585
|
+
`)}getClaimsByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`
|
|
586
|
+
SELECT
|
|
587
|
+
fc.file_path,
|
|
588
|
+
fc.mission_id,
|
|
589
|
+
fc.claimed_at,
|
|
590
|
+
fc.updated_at,
|
|
591
|
+
m.name AS mission_name,
|
|
592
|
+
m.status AS mission_status,
|
|
593
|
+
m.git_branch AS mission_branch
|
|
594
|
+
FROM file_claims fc
|
|
595
|
+
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
596
|
+
WHERE fc.file_path IN (${t})
|
|
597
|
+
ORDER BY fc.file_path ASC
|
|
598
|
+
`,...e)}}});var N,Y=ee(()=>{"use strict";ut();$r();Pr();Or();Yr();Kr();Qr();Zr();eo();to();no();N=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=De(e),o=t.files?.database,c=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram||!t.claims;if(o===r&&r.open&&!c)return t;this.repositoryCache.delete(e)}let n=De(e),i={files:new zn(n),exports:new Hn(n),imports:new Bn(n),missions:new Vn(n),intentLogs:new Jn(n),configs:new Yn(n),content:new Kn(n),searchHistory:new Qn(n),hologram:new Zn(n),claims:new Xn(n)};return this.repositoryCache.set(e,i),i}static closeInstance(e){this.repositoryCache.delete(e),Wn(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var ro=pl((Oh,_s)=>{var ti=process||{},io=ti.argv||[],ei=ti.env||{},Yl=!(ei.NO_COLOR||io.includes("--no-color"))&&(!!ei.FORCE_COLOR||io.includes("--color")||ti.platform==="win32"||(ti.stdout||{}).isTTY&&ei.TERM!=="dumb"||!!ei.CI),Kl=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+Ql(i,e,t,r)+e:s+i+e},Ql=(s,e,t,n)=>{let i="",r=0;do i+=s.substring(r,n)+t,r=n+e.length,n=s.indexOf(e,r);while(~n);return i+s.substring(r)},so=(s=Yl)=>{let e=s?Kl:()=>String;return{isColorSupported:s,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};_s.exports=so();_s.exports.createColors=so});var Ei,Si,Xo,wi,ea,ta,na,ia,sa,ra,oa,aa,ca,la,Rn,xi,pa,ua,$s=ee(()=>{"use strict";Ei=[/\/pages\/(?!_)[^/]+\.(tsx?|jsx?)$/i,/\/pages\/.*\/index\.(tsx?|jsx?)$/i,/\/app\/.*\/page\.(tsx?|jsx?)$/i,/\/app\/.*\/layout\.(tsx?|jsx?)$/i,/\/app\/api\/.*\/route\.(ts|js)$/i,/\/pages\/api\/.*\.(ts|js)$/i],Si=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],Xo=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],wi=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],ea=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],ta=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],na=[/\/commands?\/[^/]+\.(ts|js|py|php)$/i,/\/cli\/[^/]+\.(ts|js|py|php)$/i,/\/bin\/[^/]+\.(ts|js|py|php)$/i,/cli\.(ts|js|py|php)$/i,/main\.(ts|js|py|php)$/i],ia=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],sa=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],ra=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],oa=[/\/stores?\//i,/\/slices?\//i,/\/reducers?\//i,/\/atoms?\//i,/\/selectors?\//i,/\.(store|slice|reducer|atom|selector)\.(ts|js)$/i,/.*Slice\.(ts|js)$/i,/.*Store\.(ts|js)$/i],aa=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],ca=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],la=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],Rn=[/\.(model|entity|schema|repository|repo|dao|migration|query|mutation|resolver|connection|db)\.(ts|js)$/i,/queries\.(ts|js)$/i,/mutations\.(ts|js)$/i,/resolvers\.(ts|js)$/i,/connection\.(ts|js)$/i,/\/models?\//i,/\/entities?\//i,/\/repositories?\//i,/\/repos?\//i,/\/data\//i,/\/database\//i,/\/prisma\//i,/\/drizzle\//i,/\/api\/.*client\.(ts|js|tsx)$/i,/(^|\/)[A-Z0-9_-]*API\.(tsx?|js|jsx)$/],xi=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],pa=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],ua=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var vi,ma,Ri,ha,Ps=ee(()=>{"use strict";vi=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],ma=[/views\.py$/i,/forms\.py$/i,/serializers\.py$/i,/admin\.py$/i,/apps\.py$/i,/tasks\.py$/i,/middlewares?\.py$/i,/signals?\.py$/i,/context_processors\.py$/i],Ri=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],ha=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var Ti,ga,ki,ya,Ns=ee(()=>{"use strict";Ti=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],ga=[/\/services?\/.*\.php$/i,/\/providers?\/.*\.php$/i,/\/middleware\/.*\.php$/i,/\/jobs?\/.*\.php$/i,/\/listeners?\/.*\.php$/i,/\/events?\/.*\.php$/i,/\/observers?\/.*\.php$/i,/\/console\/commands\/.*\.php$/i,/\/actions?\/.*\.php$/i,/\/traits?\/.*\.php$/i,/\/concerns?\/.*\.php$/i,/\/contracts?\/.*\.php$/i],ki=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],ya=["laravel","symfony","slim","cakephp","codeigniter"]});import _a from"path";function Bt(s,e,t){let n=[],i="Unknown",r=0;t||(t=Vp(s,e));let{inDegree:o,outDegree:a}=t,c=(d,h,m,f)=>{for(let S of d)if(S.test(s))return n.push(`${f}: ${S.source}`),i=h,r+=m,!0;return!1},l=!1;if(l||(l=c(Ei,"Entry",45,"Next.js entry")),l||(l=c(ea,"Entry",40,"MCP handler")),l||(l=c(na,"Entry",40,"CLI command")),l||(l=c(Rn,"Data",45,"Data layer/Repository")),l||(l=c(oa,"Data",35,"State management")),l||(l=c(Xo,"Logic",40,"React component")),l||(l=c(wi,"Logic",35,"Logic pattern")),l||(l=c(ia,"Logic",35,"Parser/AST")),l||(l=c(sa,"Logic",35,"Core module")),l||(l=c(ra,"Logic",30,"UI layer")),l||(l=c(la,"Types",35,"Type definition")),l||(l=c(vi,"Entry",40,"Python Entry")),l||(l=c(Ri,"Data",40,"Python Data")),l||(l=c(ma,"Logic",35,"Python Logic")),l||(l=c(Ti,"Entry",40,"PHP Entry")),l||(l=c(ki,"Data",40,"PHP Data")),l||(l=c(ga,"Logic",35,"PHP Logic")),l||(l=c(aa,"Logic",35,"Hook/Context")),!l){for(let d of ta)if(d.test(s)){n.push(`MCP utility: ${d.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,l=!0;break}}l||c(ca,"Data",35,"Schema definition")&&(l=!0),l||(c(Rn,"Data",30,"Path matches data pattern")||c(xi,"Utility",25,"Path matches utility pattern")||c(Si,"Entry",30,"Path matches entry pattern"))&&(l=!0);for(let d of Ds)if(d.test(s)){n.push(`Test file: ${d.source}`),i="Test",r=50,l=!0;break}l||c(Os,"Infrastructure",40,"Infrastructure")&&(l=!0);for(let d of qp)d.test(s)&&(n.push(`Monorepo component: ${d.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let u=e.imports.getImportsForFile(s).map(d=>d.module_specifier.toLowerCase());for(let d of ua)if(u.some(h=>h.includes(d))){n.push(`Imports JS data library: ${d}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let d of ha)if(u.some(h=>h.includes(d))){n.push(`Imports Python framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of ya)if(u.some(h=>h.includes(d))){n.push(`Imports PHP framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of pa)if(u.some(h=>h.includes(d))){n.push(`Imports JS framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}if(o===0&&a>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),i==="Unknown"?(i="Entry",r+=30):i==="Entry"&&(r+=15)),o>5&&a<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),i==="Unknown"?(i="Utility",r+=25):i==="Utility"&&(r+=10)),i==="Unknown"&&o>0&&a>0){let d=o/(o+a);d>.3&&d<.7&&(n.push(`Balanced traffic: in=${o}, out=${a} (likely Logic layer)`),i="Logic",r+=25)}return i==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:i,confidence:r,signals:n}}function Vp(s,e){let t=e.imports.countDependents(s),n=e.imports.countByFile(s);return{inDegree:t,outDegree:n}}function kt(s,e){let t=s.files.getAllPaths().map(m=>({path:m})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let m of t){let f=Bt(m.path,s);n.set(m.path,f),i[f.layer].push({path:m.path,classification:f})}let r={Entry:Tt(i.Entry,e),Logic:Tt(i.Logic,e),Data:Tt(i.Data,e),Utility:Tt(i.Utility,e),Infrastructure:Tt(i.Infrastructure,e),Test:Tt(i.Test,e),Types:Tt(i.Types,e),Unknown:Tt(i.Unknown,e)},o={};t.forEach(m=>{let f=_a.extname(m.path).toLowerCase();f&&(o[f]=(o[f]||0)+1)});let a={".ts":"TypeScript",".tsx":"Typescript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".php":"PHP",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".vue":"Vue"},c={};Object.entries(o).forEach(([m,f])=>{let S=a[m];S&&(c[S]=(c[S]||0)+f)});let l=Object.entries(c).sort((m,f)=>f[1]-m[1]),p=l.length>0?l[0][0]:"Unknown",{pattern:u,patternConfidence:d,insights:h}=Jp(r,t.length,s);return{pattern:u,patternConfidence:d,layers:r,insights:h,primaryStack:p}}function Tt(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:_a.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function Jp(s,e,t){let n=[],i="Unknown",r=0,o=s.Entry.count/e*100,a=s.Logic.count/e*100,c=s.Data.count/e*100,l=s.Utility.count/e*100,p=s.Unknown.count/e*100;o>5&&a>10&&c>5&&p<40?(i="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${a.toFixed(1)}%), Data (${c.toFixed(1)}%)`)):l>20?(i="Modular",r=50+l/2,n.push(`High shared module usage: ${l.toFixed(1)}% utility files`)):p>60&&(i="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let u=t.configs.countByKind("Service");return u>3&&(i="Microservices",r=55+u*5,n.push(`Detected ${u} service definitions (likely microservices)`)),s.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),s.Data.count===0&&n.push("\u26A0\uFE0F No data layer detected - repository may not use traditional ORM patterns"),l>30&&n.push(`High utility concentration (${l.toFixed(1)}%) - good reusability`),{pattern:i,patternConfidence:Math.min(100,r),insights:n}}var Ds,Os,qp,Ut=ee(()=>{"use strict";$s();Ps();Ns();Ds=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],Os=[/Dockerfile/i,/docker-compose/i,/\.ya?ml$/i,/nginx\.conf/i,/\/infra\//i,/\/deploy\//i,/\/k8s\//i,/\/kubernetes\//i,/\/terraform\//i,/\/ansible\//i,/package\.json/i,/tsconfig.*\.json/i,/\.env/i],qp=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});function Uu(s){try{return JSON.stringify(s)}catch{return String(s)}}function qt(s){if(s instanceof Error)return s.message;if(typeof s=="string")return s;if(s&&typeof s=="object"&&"message"in s){let e=s.message;if(typeof e=="string"&&e.trim())return e}return Uu(s)}function Re(s){if(s instanceof Error){let e;return"cause"in s&&s.cause!==void 0&&(e=qt(s.cause)),{errorName:s.name||"Error",errorMessage:s.message,errorStack:s.stack,...e?{errorCause:e}:{}}}return s&&typeof s=="object"?{errorName:s.constructor?.name||"Object",errorMessage:qt(s)}:{errorName:typeof s,errorMessage:qt(s)}}var Cn=ee(()=>{"use strict"});var Va={};cs(Va,{HologramService:()=>Ae});var Qe,Ae,rn=ee(()=>{"use strict";Y();Ut();G();Cn();Qe=w.child({module:"hologram"}),Ae=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=N.getInstance(e)}updateTopography(e){Qe.debug({repoPath:this.repoPath},"Updating topography snapshot");let t=Object.values(e.layers).reduce((r,o)=>r+o.count,0),n={};for(let[r,o]of Object.entries(e.layers)){let a=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(a*10)/10,topFiles:o.topFiles.slice(0,3).map(c=>({path:c.path,confidence:c.confidence}))}}let i={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(i)),Qe.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=kt(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){Qe.debug({repoPath:this.repoPath,count:e.length},"Updating gravity zones");let t={hotspots:e.slice(0,50),updatedAt:Date.now()};this.repos.hologram.upsertSection("gravity",JSON.stringify(t)),Qe.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){Qe.debug({repoPath:this.repoPath,count:e.length},"Updating ghost bridges");let t={bridges:e.slice(0,20),updatedAt:Date.now()};this.repos.hologram.upsertSection("ghosts",JSON.stringify(t)),Qe.info({repoPath:this.repoPath},"Ghost bridges updated")}getSnapshot(){let e=this.repos.hologram.getAllSections(),t={metadata:{repoPath:this.repoPath,lastUpdated:Date.now(),version:"1.0.0"}};for(let n of e)try{let i=JSON.parse(n.data);switch(n.section){case"topography":t.topography=i;break;case"gravity":t.gravity=i;break;case"ghosts":t.ghosts=i;break}}catch(i){Qe.debug({repoPath:this.repoPath,section:n.section,...Re(i)},"Skipping malformed hologram section")}return t}getSection(e){let t=this.repos.hologram.getSection(e);if(!t)return null;try{return JSON.parse(t.data)}catch(n){return Qe.debug({repoPath:this.repoPath,section:e,...Re(n)},"Skipping malformed hologram section"),null}}computeGravityZones(){Qe.debug({repoPath:this.repoPath},"Computing gravity zones from import graph");let e=this.repos.files.getAllPaths(),t=new Map;for(let i of e){let r=Bt(i,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(i);if(o.length===0)continue;let a=this.repos.imports.countDependents(i),c=this.repos.imports.countByFile(i),l=a*2+c;if(l>0){let p=o.find(d=>d.kind!=="TsTypeAliasDeclaration"&&d.kind!=="TsInterfaceDeclaration")||o[0],u=`${i}::${p.name}`;t.set(u,{symbol:p.name,filePath:i,inDegree:a,outDegree:c,gravity:l})}}let n=Array.from(t.values()).sort((i,r)=>r.gravity-i.gravity).slice(0,50);return Qe.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),Qe.info({repoPath:this.repoPath},"Hologram cleared")}}});var Dc={};cs(Dc,{GraphExporterService:()=>pr});var Nc,pr,Oc=ee(()=>{"use strict";Y();G();Nc=w.child({module:"graph-exporter"}),pr=class{constructor(e){this.repoPath=e;this.repos=N.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;Nc.info({focusMissionId:i,depth:r,format:n,includeCompleted:t},"Generating mission graph");let a=this.buildMissionTree(i,t,r,o);return n==="json"?JSON.stringify(a,null,2):this.generateMermaidDiagram(a)}buildMissionTree(e,t,n,i){let r;if(e){let c=this.repos.missions.findById(e);r=c?[c]:[]}else r=this.repos.missions.findAll().filter(l=>!l.parent_id),t||(r=r.filter(l=>l.status!=="completed"));let o=0,a=[];for(let c of r){if(o>=i)break;let l=this.buildNode(c,t,n,1,{count:o,max:i});l&&(a.push(l),o+=this.countNodes(l))}return a}buildNode(e,t,n,i,r){if(i>n||r.count>=r.max)return null;let o;if(e.strategy_graph)try{let p=JSON.parse(e.strategy_graph);o=this.parseStrategySteps(p)}catch(p){Nc.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let a={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},c=this.repos.missions.findByParentId(e.id),l=t?c:c.filter(p=>p.status!=="completed");for(let p of l){if(r.count>=r.max)break;let u=this.buildNode(p,t,n,i+1,r);u&&(a.children.push(u),r.count++)}return a}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,i)=>({id:n.id||`step-${i}`,description:n.description||n.content||n.name||`Step ${i+1}`,status:n.status,dependencies:n.dependencies||n.deps})):e.steps&&Array.isArray(e.steps)?this.parseStrategySteps(e.steps):typeof e=="object"?Object.entries(e).map(([n,i])=>({id:n,description:i.description||i.content||n,status:i.status,dependencies:i.dependencies||i.deps})):t}countNodes(e){let t=1;for(let n of e.children)t+=this.countNodes(n);return t}generateMermaidDiagram(e){let t=["graph TD"];for(let n of e)this.addMermaidNode(n,t);return t.join(`
|
|
599
|
+
`)}addMermaidNode(e,t,n){let i=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),a=`${r} ${e.name}`;if(t.push(` ${i}["${this.escapeMermaid(a)}"]:::${o}`),n&&t.push(` ${n} --> ${i}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let c of e.steps){let l=`S${e.id}_${c.id}`,p=c.status||"pending",u=this.getStatusIcon(p),d=this.getStatusClass(p),h=`${u} ${c.description}`;if(t.push(` ${l}["${this.escapeMermaid(h)}"]:::${d}`),t.push(` ${i} -.-> ${l}`),c.dependencies&&c.dependencies.length>0)for(let m of c.dependencies){let f=`S${e.id}_${m}`;t.push(` ${f} --> ${l}`)}}for(let c of e.children)this.addMermaidNode(c,t,i);n||(t.push(""),t.push(" classDef completed fill:#90EE90,stroke:#2E8B57,stroke-width:2px"),t.push(" classDef inProgress fill:#87CEEB,stroke:#4682B4,stroke-width:2px"),t.push(" classDef planned fill:#FFE4B5,stroke:#DAA520,stroke-width:2px"),t.push(" classDef suspended fill:#D3D3D3,stroke:#808080,stroke-width:2px"),t.push(" classDef failed fill:#FFB6C1,stroke:#DC143C,stroke-width:2px"),t.push(" classDef pending fill:#FFF8DC,stroke:#B8860B,stroke-width:1px"))}getStatusIcon(e){return{completed:"\u2713","in-progress":"\u26A1",planned:"\u{1F4CB}",suspended:"\u23F8",failed:"\u2717",pending:"\u25CB",verifying:"\u{1F50D}"}[e]||"\u25CB"}getStatusClass(e){return{completed:"completed","in-progress":"inProgress",planned:"planned",suspended:"suspended",failed:"failed",pending:"pending",verifying:"inProgress"}[e]||"pending"}escapeMermaid(e){return e.replace(/"/g,"#quot;").replace(/\n/g," ").replace(/\[/g,"#91;").replace(/]/g,"#93;").slice(0,100)}}});import"dotenv/config";import{Cli as fm}from"clerc";G();import wr from"fs";import gl from"path";import xr from"js-yaml";var vr={ignore:[],include:[],maxDepth:10},yl=[{name:".liquid-shadow.yaml",parse:s=>xr.load(s)??{}},{name:".liquid-shadow.yml",parse:s=>xr.load(s)??{}},{name:".ls.json",parse:s=>JSON.parse(s)},{name:".liquid-shadow.json",parse:s=>JSON.parse(s)},{name:".ls.rc",parse:s=>JSON.parse(s)},{name:".liquid-shadow.rc",parse:s=>JSON.parse(s)}];function ct(s){for(let{name:e,parse:t}of yl){let n=gl.join(s,e);if(wr.existsSync(n))try{let i=wr.readFileSync(n,"utf8"),r=t(i);return w.debug({repoPath:s,configFile:e},"Loaded repository configuration"),{...vr,...r}}catch(i){w.error({repoPath:s,file:e,err:i},"Failed to parse configuration file")}}return vr}function ls(s,e){let n=ct(s).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}Y();import Xl from"path";var ye=dl(ro(),1);import*as et from"@clack/prompts";var te={red:ye.default.red,green:ye.default.green,yellow:ye.default.yellow,blue:ye.default.blue,magenta:ye.default.magenta,cyan:ye.default.cyan,white:ye.default.white,gray:ye.default.gray,bold:ye.default.bold,dim:ye.default.dim,italic:ye.default.italic,underline:ye.default.underline,inverse:ye.default.inverse},St=s=>s.replace(/\x1b\[[0-9;]*m/g,""),ge=s=>et.intro(ye.default.bgCyan(ye.default.black(ye.default.bold(` ${s} `)))),Ve=s=>et.outro(ye.default.cyan(s)),ue=(s,e,t="blue")=>{let n=e.split(`
|
|
600
|
+
`),i=St(s),r=Math.max(i.length+4,...n.map(c=>St(c).length))+2,o="\u2500".repeat(r),a=te[t];console.log(a(`\u250C${o}\u2510`)),console.log(a("\u2502 ")+te.bold(s).padEnd(r+(s.length-i.length)-1)+a("\u2502")),console.log(a(`\u251C${o}\u2524`)),n.forEach(c=>{let l=St(c),p=" ".repeat(r-l.length-1);console.log(a("\u2502 ")+c+p+a("\u2502"))}),console.log(a(`\u2514${o}\u2518`))},ni=(s,e)=>{let t=s.map((i,r)=>Math.max(St(i).length,...e.map(o=>St(o[r]||"").length))+2),n=te.cyan("\u2502");console.log(n),console.log(n+" "+s.map((i,r)=>te.bold(te.cyan(i)).padEnd(t[r]+(i.length-St(i).length))).join(te.gray(" "))+" "),e.forEach(i=>{console.log(n+" "+i.map((r,o)=>(r||"").padEnd(t[o]+(r.length-St(r).length))).join(te.gray(" "))+" ")}),console.log(n)},oo=(s,e="\u2022")=>{s.forEach(t=>{console.log(`${te.cyan("\u2502")} ${te.cyan(e)} ${t}`)})},ii=(s,e=40)=>{let t=Math.max(...s.map(i=>i.value)),n=Math.max(...s.map(i=>St(i.label).length));console.log(te.cyan("\u2502")),s.forEach(i=>{let r=Math.round(i.value/t*e),o="\u2588".repeat(r)+te.dim("\u2591".repeat(e-r)),a=i.color?te[i.color]:te.cyan,c=i.label.padEnd(n);console.log(`${te.cyan("\u2502")} ${te.bold(c)} ${a(o)} ${te.white(i.value.toString())}`)}),console.log(te.cyan("\u2502"))},Es=(s,e="")=>{s.forEach((t,n)=>{let i=n===s.length-1,r=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?te[t.color]:t.children?te.blue:te.white,a=t.info?` ${te.gray(`(${t.info})`)}`:"";if(console.log(`${te.cyan("\u2502")} ${e}${te.gray(r)}${o(t.name)}${a}`),t.children&&t.children.length>0){let c=e+(i?" ":"\u2502 ");Es(t.children,c)}})},Oe=()=>et.spinner();async function si(s,e,t){if(e.length===0)return;let n=await et.select({message:s,options:e.map(i=>({value:i.value,label:i.label,...i.hint!=null&&{hint:i.hint}})),...t?.limit!=null&&{maxItems:t.limit}});if(!et.isCancel(n))return n}var Zl=s=>{console.error("");let e=s instanceof Error?s.message:String(s);console.error(` ${te.red("\u2716")} ${te.bold("Error: ")} ${e}`),s instanceof Error&&"cause"in s&&console.error(` ${te.dim("Cause: "+String(s.cause))}`),console.error(""),process.exit(1)},Q=async s=>{try{await s()}catch(e){Zl(e)}},b=te;qe();ut();G();async function ne(s){w.debug("Performing graceful shutdown...");try{await Un()}catch(e){w.error({err:e},"Error shutting down worker pool")}try{s&&Wn(s)}catch(e){w.error({err:e},"Error closing database")}w.debug("Shutdown complete")}async function ao(s){let e=Xl.resolve(s);try{await Q(async()=>{ge("\u{1F311} Liquid Shadow: Scouting Report");let t=N.getInstance(e),n=ct(e),i=n.ignore&&n.ignore.length>0,r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);ue("Intelligence Summary",`${b.bold("\u{1F4E1} Topology")}: ${b.cyan(r.toString())} files mapped
|
|
601
|
+
${b.bold("\u{1F9E9} Symbols")}: ${b.cyan(o.toString())} exports detected
|
|
602
|
+
${b.bold("\u{1F552} Last Sync")}: ${a?b.yellow(new Date(a).toLocaleString()):b.red("Never")}
|
|
603
|
+
${b.bold("\u2699\uFE0F Config")}: ${i?b.green("Custom Intelligence"):b.gray("Standard Sieve")}`,"blue"),c.length>0&&(console.log(""),console.log(` ${b.bold("Symbol Distribution (Top 5)")}`),ii(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),30)),console.log(""),console.log(` ${b.dim("Pro-tip: Try")} ${b.bold(b.cyan("liquid-shadow dashboard"))} ${b.dim("for the full tactical view.")}`),console.log(""),Ve("Scouting complete.")})}finally{await ne(e)}}Y();ut();import fo from"path";var Ss=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];searchHistoryFailureCount=0;recordIndexStart(){this.indexRuns+=1}recordIndexCacheHit(){this.indexCacheHits+=1}recordIndexEnd(e){this.lastIndexDurationMs=e,this.lastIndexCompletedAt=Date.now()}recordIndexPhase(e,t){this.lastRunPhases.push({phase:e,durationMs:t})}clearIndexPhases(){this.lastRunPhases=[]}recordQueryStart(){let e=performance.now();return()=>{this.queryCount+=1;let t=performance.now()-e;if(this.lastQueryLatencyMs=t,this.recentLatencies.push(t),this.recentLatencies.length>100){let n=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-n+t}else this.recentLatencySumMs+=t,this.recentLatencyCount=this.recentLatencies.length}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((n,i)=>n+i,0)/e:null;return{index:{runs:this.indexRuns,cacheHits:this.indexCacheHits,lastDurationMs:this.lastIndexDurationMs,lastCompletedAt:this.lastIndexCompletedAt,lastRunPhases:[...this.lastRunPhases]},query:{count:this.queryCount,lastLatencyMs:this.lastQueryLatencyMs,recentLatencySumMs:this.recentLatencySumMs,recentLatencyCount:e,avgLatencyMs:t,searchHistoryFailures:this.searchHistoryFailureCount},uptimeMs:Date.now()-this.startTime}}reset(){this.indexRuns=0,this.indexCacheHits=0,this.lastIndexDurationMs=null,this.lastIndexCompletedAt=null,this.lastRunPhases=[],this.queryCount=0,this.lastQueryLatencyMs=null,this.recentLatencySumMs=0,this.recentLatencyCount=0,this.recentLatencies=[],this.searchHistoryFailureCount=0}},wt=new Ss;function co(){wt.recordIndexStart()}function ws(){wt.recordIndexCacheHit()}function lo(s){wt.recordIndexEnd(s)}function _n(s,e){wt.recordIndexPhase(s,e)}function po(){wt.clearIndexPhases()}function ri(){return wt.recordQueryStart()}function Qt(){wt.recordSearchHistoryFailure()}function oi(){return wt.getSnapshot()}G();Nt();import se from"fs";import ep from"os";import tt from"path";var Dt=w.child({module:"git-hooks"}),tp="Generated by liquid-shadow",np=1e6,uo=["post-merge","post-checkout","post-commit"];function ip(){let s=process.env.LIQUID_SHADOW_CLI_ENTRY;if(s){let t=tt.resolve(s);if(se.existsSync(t))return t}let e=Le("dist/entry/cli/index.js");return se.existsSync(e)?e:null}function xs(s){return s.includes("liquid-shadow")||s.includes("mcp-liquid-shadow")||s.includes(tp)}function sp(){let s=tt.join(ep.homedir(),".mcp-liquid-shadow","logs"),e=tt.join(s,"post-checkout.log");try{if(!se.existsSync(e)||se.statSync(e).size<=np)return null;se.mkdirSync(s,{recursive:!0});let n=`${e}.1`;return se.existsSync(n)&&se.unlinkSync(n),se.renameSync(e,n),null}catch(t){return`Failed to rotate post-checkout.log: ${t}`}}function rp(s,e){return{"post-merge":`#!/bin/sh
|
|
551
604
|
# Liquid Shadow: Auto-refresh index after merge/pull
|
|
552
605
|
# Generated by liquid-shadow
|
|
553
606
|
|
|
@@ -588,30 +641,30 @@ REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
|
588
641
|
nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
589
642
|
|
|
590
643
|
exit 0
|
|
591
|
-
`}}function
|
|
592
|
-
${
|
|
593
|
-
${
|
|
594
|
-
${
|
|
595
|
-
${
|
|
596
|
-
${
|
|
597
|
-
${
|
|
598
|
-
${
|
|
599
|
-
${
|
|
600
|
-
${
|
|
601
|
-
${
|
|
602
|
-
${
|
|
603
|
-
${
|
|
604
|
-
${
|
|
605
|
-
${
|
|
606
|
-
${
|
|
607
|
-
${
|
|
608
|
-
${
|
|
609
|
-
${
|
|
610
|
-
${
|
|
611
|
-
${
|
|
612
|
-
${
|
|
613
|
-
`),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function
|
|
614
|
-
`)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function Zn(s,e,t){let n=s.toLowerCase(),i=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||i.startsWith("use")?"Hook":n.includes("models/")||i.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||i.endsWith("service")||i.endsWith("controller")||i.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||i.endsWith("repository")||i.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function cn(s){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(s)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(s)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(s)||/\.query\s*\(|\.execute\s*\(/i.test(s)&&/db|database|client|pool/i.test(s))&&e.push("Database"),(/\bfs\./i.test(s)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(s)||/import\s+.*\bfs\b/.test(s))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(s)||/\bdocument\.cookie\b/.test(s))&&e.push("Browser Storage"),e}function Ce(s,e){if(!s)return"";let t=s.trimStart();for(;/^\/\*[\s\S]*?\*\//.test(t);)t=t.replace(/^\/\*[\s\S]*?\*\/\s*/,"");for(;/^\/\/[^\n]*\n/.test(t);)t=t.replace(/^\/\/[^\n]*\n\s*/,"");if(t=t.replace(/^(?:import[^\n]*\n)+/,"").replace(/^(?:export\s+\{[^}]*\}\s+from\s+['"][^'"]+['"];?\s*\n?)+/,"").trim(),e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,i=0,r=t.length;for(let a=0;a<t.length;a++){let c=t[a];if(c==="(")n++;else if(c===")")n--;else if(c==="<")i++;else if(c===">")i--;else if(c==="{"){if(n===0&&i===0){r=a;break}}else if(c===";"&&n===0&&i===0){r=a;break}else if(c==="="&&t[a+1]===">"&&n===0&&i===0){r=a+2;break}}let o=t.substring(0,r).trim();return o.length>500?o.slice(0,497)+"...":o}function eo(s){let e=[];for(let t of s)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join(", ")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function Bl(s,e){for(let t of s){if((t.type==="FunctionDeclaration"||t.type==="ClassDeclaration")&&(t.identifier?.value||t.id?.value)===e)return t.span;if(t.type==="VariableDeclaration"){for(let n of t.declarations)if(n.id?.type==="Identifier"&&n.id.value===e)return n.span||t.span}if((t.type==="TsTypeAliasDeclaration"||t.type==="TsInterfaceDeclaration"||t.type==="TsEnumDeclaration")&&(t.id?.value||t.identifier?.value)===e)return t.span;if(t.type==="ExportDeclaration"){let n=t.declaration;if(!n)continue;if((n.type==="FunctionDeclaration"||n.type==="ClassDeclaration")&&(n.identifier?.value||n.id?.value)===e)return n.span||t.span;if(n.type==="VariableDeclaration"){for(let i of n.declarations)if(i.id?.type==="Identifier"&&i.id.value===e)return i.span||n.span||t.span}}}return null}function to(s,e,t,n,i,r,o,a,c){let l=c??(u=>Xn(u,t)),p=[];for(let u of s){if(u.type==="ExportDeclaration"){let d=u.declaration,h=d.type,m="";h==="VariableDeclaration"?m=d.declarations.map(x=>x.id.value).join("",""):m=d.id?.value||d.identifier?.value||"anonymous";let f=l(u.span.start-e),_=l(u.span.end-e),g=Ge(f,r,n),b=a(u.span),w=[];if(u.type==="ExportDeclaration"&&(h==="ClassDeclaration"||h==="ClassExpression")){let x=d.body||[];for(let R of x)if(R.type==="ClassMethod"||R.type==="ClassProperty"){let k=R.key.value;if(!k)continue;let D=l(R.span.start-e),U=l(R.span.end-e),P=a(R.span),E=Ge(D,r,n);w.push({name:k,kind:R.type,signature:Ce(P,R.type),line:te(D,i),endLine:te(U,i),doc:E,classification:R.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(h==="FunctionDeclaration"&&d.body?.type==="BlockStatement")w=ps(d.body.stmts,e,t,n,i,r,a,l);else if(h==="VariableDeclaration"){for(let x of d.declarations)if(x.init&&(x.init.type==="ArrowFunctionExpression"||x.init.type==="FunctionExpression")&&x.init.body?.type==="BlockStatement"){w=ps(x.init.body.stmts,e,t,n,i,r,a,l);break}}p.push({name:m,kind:h,signature:Ce(b,h),line:te(f,i),endLine:te(_,i),doc:g,classification:Zn(o,m,h),capabilities:JSON.stringify(cn(b)),members:w})}if(u.type==="ExportNamedDeclaration"){for(let d of u.specifiers)if(d.type==="ExportSpecifier"){let h=d.orig.value,m=d.exported?.value||h,_=Bl(s,h)||u.span,g=l(_.start-e),b=l(_.end-e),w=Ge(g,r,n);p.push({name:m,kind:"ExportSpecifier",signature:`export { ${h} }`,line:te(g,i),endLine:te(b,i),doc:w,classification:"Export mapping",capabilities:"[]"})}}if(u.type==="ExportDefaultDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=Ge(d,r,n),f=a(u.span),_=[];if(u.decl.type==="ClassExpression"||u.decl.type==="ClassDeclaration"){let g=u.decl.body||[];for(let b of g)if(b.type==="ClassMethod"||b.type==="ClassProperty"){let w=b.key.value;if(!w)continue;let x=l(b.span.start-e),R=l(b.span.end-e),k=a(b.span),D=Ge(x,r,n);_.push({name:w,kind:b.type,signature:Ce(k,b.type),line:te(x,i),endLine:te(R,i),doc:D,classification:b.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(u.decl.type==="FunctionExpression"||u.decl.type==="FunctionDeclaration"||u.decl.type==="ArrowFunctionExpression")&&u.decl.body?.type==="BlockStatement"&&(_=ps(u.decl.body.stmts,e,t,n,i,r,a,l));p.push({name:"default",kind:"DefaultExport",signature:Ce(f,"DefaultExport"),line:te(d,i),endLine:te(h,i),doc:m,classification:"Default Export",capabilities:JSON.stringify(cn(f)),members:_})}if(u.type==="ExportAllDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=u.source.value,f=Ge(d,r,n);p.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${m}"`,line:te(d,i),endLine:te(h,i),doc:f,classification:"Re-export",capabilities:"[]"})}}return p}function ps(s,e,t,n,i,r,o,a){let c=[];for(let l of s){if(l.type==="VariableDeclaration")for(let p of l.declarations){let u=[],d=m=>{if(m.type==="Identifier")u.push({name:m.value,span:m.span});else if(m.type==="ArrayPattern")for(let f of m.elements)f&&d(f);else if(m.type==="ObjectPattern")for(let f of m.properties)f.type==="AssignmentPatternProperty"?u.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&d(f.value)};d(p.id);let h=p.init&&(p.init.type==="ArrowFunctionExpression"||p.init.type==="FunctionExpression");for(let m of u){let f=h?p.init.span||p.span||m.span:p.span||m.span,_=h?p.init.type:"VariableDeclaration",g=h?"Internal Function":"Internal Variable",b=a(f.start-e),w=a(f.end-e),x=o(f),R=Ge(b,r,n);c.push({name:m.name,kind:_,signature:Ce(x,_),line:te(b,i),endLine:te(w,i),doc:R,classification:g,capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let p=l.identifier?.value||l.ident?.value||"anonymous",u=a(l.span.start-e),d=a(l.span.end-e),h=o(l.span),m=Ge(u,r,n);c.push({name:p,kind:"FunctionDeclaration",signature:Ce(h,"FunctionDeclaration"),line:te(u,i),endLine:te(d,i),doc:m,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let p of l.argument.properties){let u="",d=p.span||p.key?.span||p.ident?.span;if(p.type==="KeyValueProperty"){let h=p.key;u=h?.value||h?.raw||(h?.type==="Identifier"?h.value:"")}else p.type==="MethodProperty"?u=p.key?.value||p.key?.raw||"":p.type==="ShorthandProperty"?u=p.ident?.value||"":p.type==="Identifier"&&(u=p.value||"");if(u&&d){let h=a(d.start-e),m=a(d.end-e),f=o(d),_=Ge(h,r,n);c.push({name:u,kind:"ReturnProperty",signature:Ce(f,"ReturnProperty"),line:te(h,i),endLine:te(m,i),doc:_,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let p=l.expression;if(p.callee.type==="MemberExpression"&&(p.callee.property?.value==="on"||p.callee.property?.value==="once")){let u=p.arguments[0]?.expression?.value,d=p.arguments[1]?.expression;if(u&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let h=a(d.span.start-e),m=a(d.span.end-e),f=o(d.span);c.push({name:`on:${u}`,kind:d.type,signature:Ce(f,d.type),line:te(h,i),endLine:te(m,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(p.callee.type==="Identifier"&&p.callee.value==="addRoute"&&p.arguments.length>=3){let u=p.arguments[2].expression;if(u.type==="StringLiteral"){let d=u.value,h=a(p.span.start-e),m=a(p.span.end-e),f=o(p.span);c.push({name:d,kind:"HTTP Route",signature:Ce(f,"HTTP Route"),line:te(h,i),endLine:te(m,i),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:d})})}}}}return c}function no(s,e,t,n,i,r){let o=r??(l=>Xn(l,t)),a=[];function c(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let p=Gl(l);if(p){let u=o(l.span.start-e);a.push({...p,line:te(u,n),snippet:i(l.span)})}}for(let p of Object.keys(l)){if(p==="span")continue;let u=l[p];Array.isArray(u)?u.forEach(c):typeof u=="object"&&c(u)}}}return s.forEach(c),a}function Gl(s){let{callee:e,arguments:t}=s;if(!t||t.length===0)return null;if(e.type==="Identifier"&&e.value,e.type==="Identifier"&&e.value==="addRoute"&&t.length>=3){let n=t[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value,o=e.object.type==="Identifier"?e.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(o))return{type:"api_route",name:r,direction:"produce"};if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function ln(s){let{classification:e,capabilities:t,exports:n,fileName:i}=s,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(m=>r[m]).filter(Boolean).join(" and "),c={Component:(m,f)=>{let _=f.find(b=>b.kind==="FunctionDeclaration"||b.kind==="ClassDeclaration")?.name,g=_?`React component: ${_}`:"React UI component";return m?`${g} with ${m}`:g},Hook:(m,f)=>{let _=f.find(b=>b.name.startsWith("use"))?.name,g=_?`Custom React hook: ${_}`:"Custom React hook";return m?`${g} for ${m}`:g},Service:(m,f)=>{let g=`Service layer: ${f[0]?.name||"Service"}`;return m?`${g} handling ${m}`:g},Repository:(m,f)=>`Data repository: ${f[0]?.name||"Repository"} for ${m||"data access"}`,"Type Definition":(m,f)=>`Type definitions: ${f.slice(0,3).map(g=>g.name).join("")}${f.length>3?"...":""}`,Model:(m,f)=>`Data model: ${f[0]?.name||"Model"}`,"HTTP Route":(m,f)=>{let _=f.filter(g=>g.classification==="Service Boundary");return _.length>0?`API endpoints: ${_.slice(0,3).map(g=>g.name).join("")}`:"API route handler"},"Micro IR (PHP)":(m,f)=>{let _=f.some(b=>b.classification==="Service Boundary"),g=f.find(b=>b.kind==="ClassDeclaration")?.name;return _?"PHP controller with API routes":g?`PHP class: ${g}`:"PHP module"},"Micro IR (Python)":(m,f)=>{let _=f.some(b=>b.classification==="Service Boundary"),g=f.find(b=>b.kind==="ClassDeclaration")?.name;return _?"Python API handler with routes":g?`Python class: ${g}`:"Python module"},"Micro IR (Go/TS) ":(m,f)=>{let _=f.some(b=>b.kind==="TypeDeclaration"),g=f.filter(b=>b.kind==="FunctionDeclaration");return _&&g.length>0?`Go package: types and ${g.length} function(s)`:_?"Go package: type definitions":g.length>0?`Go package: ${g[0].name} and ${g.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(m,f)=>{let _=f.find(w=>w.kind==="TraitDeclaration")?.name,g=f.find(w=>w.kind==="StructDeclaration")?.name,b=f.filter(w=>w.kind==="FunctionDeclaration");return _?m.includes("Rust trait")?`Rust module: trait ${_}`:`Rust module: ${_}`:g?`Rust module: struct ${g}`:b.length>0?`Rust module: ${b.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return i?`Module: ${i}`:"Module with no exports";let l=n.filter(m=>m.kind==="FunctionDeclaration"),p=n.filter(m=>m.kind==="ClassDeclaration"),u=n.filter(m=>m.kind==="TsInterfaceDeclaration"||m.kind==="TsTypeAliasDeclaration"),d=[];if(p.length>0&&d.push(`Class: ${p[0].name}`),l.length>0){let m=l.slice(0,2).map(f=>f.name).join("");d.push(`Functions: ${m}`)}u.length>0&&d.push(`Types: ${u.length}`);let h=d.length>0?d.join(" | "):`Module with ${n.length} export(s)`;return o?`${h} \u2014 ${o}`:h}function io(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&oe(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&oe(n,e);for(let i in n){if(i==="span"||i==="comments"||i==="interpreter")continue;let r=n[i];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return s.forEach(n=>t(n)),Array.from(e)}function oe(s,e){if(s){if(s.type==="TsTypeAnnotation"){oe(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&so(s.typeName,e),s.typeParams&&oe(s.typeParams,e)),s.type==="TsArrayType"&&oe(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>oe(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>oe(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>oe(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>oe(t.typeAnnotation,e)),s.typeAnnotation&&oe(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&oe(t.constraint,e),t.default&&oe(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>oe(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&oe(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(oe(s.objectType,e),oe(s.indexType,e)),s.type==="TsConditionalType"&&(oe(s.checkType,e),oe(s.extendsType,e),oe(s.trueType,e),oe(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&oe(t.typeAnnotation,e)})}}function so(s,e){s.type==="TsQualifiedName"?(s.left&&so(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}import uo from"path";import us from"path";q();St();import oo from"path";import ql from"fs";import{fileURLToPath as Vl}from"url";import*as xt from"web-tree-sitter";var Rf=oo.dirname(Vl(import.meta.url)),ro=S.child({module:"parser:tree-sitter"}),ei=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=xt.Parser||xt;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=_e("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!ql.existsSync(t))return ro.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await xt.Language.load(t);return this.languages.set(e,n),n}catch(n){return ro.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
|
|
644
|
+
`}}function mo(s){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=s,i=tt.join(e,".git","hooks"),r=[],o=[],a=[];if(!se.existsSync(tt.join(e,".git")))return a.push("Not a git repository"),{installed:r,skipped:o,errors:a};se.existsSync(i)||se.mkdirSync(i,{recursive:!0});let c=ip();if(!c)return a.push(`Unable to resolve CLI entry at install time. Expected ${Le("dist/entry/cli/index.js")} to exist.`),{installed:r,skipped:o,errors:a};let l=rp(process.execPath,c),p=new Set;if(t&&(p.add("post-merge"),p.add("post-checkout")),n&&p.add("post-commit"),p.has("post-checkout")){let u=sp();u&&(a.push(u),Dt.warn({rotationError:u},"Post-checkout log rotation failed"))}for(let u of p){let d=tt.join(i,u),h=l[u];if(!h){a.push(`No template found for hook: ${u}`);continue}try{if(se.existsSync(d)){let m=se.readFileSync(d,"utf-8"),f=xs(m);if(f&&m===h){se.chmodSync(d,493),o.push(u),Dt.info({hookName:u},"Hook already installed, skipping");continue}if(!f){let S=`${d}.backup-${Date.now()}`;se.copyFileSync(d,S),Dt.info({hookName:u,backupPath:S},"Backed up existing hook")}}se.writeFileSync(d,h,{mode:493}),se.chmodSync(d,493),r.push(u),Dt.info({hookName:u},"Installed git hook")}catch(m){a.push(`Failed to install ${u}: ${m}`),Dt.error({hookName:u,err:m},"Failed to install hook")}}return{installed:r,skipped:o,errors:a}}function ho(s){let e=tt.join(s,".git","hooks"),t=[],n=[];if(!se.existsSync(e))return{removed:t,errors:n};for(let i of uo){let r=tt.join(e,i);try{if(se.existsSync(r)){let o=se.readFileSync(r,"utf-8");xs(o)&&(se.unlinkSync(r),t.push(i),Dt.info({hookName:i},"Removed git hook"))}}catch(o){n.push(`Failed to remove ${i}: ${o}`),Dt.error({hookName:i,err:o},"Failed to remove hook")}}return{removed:t,errors:n}}function op(s,e){let t=tt.join(s,".git","hooks"),n=tt.join(t,e);if(!se.existsSync(t)||!se.existsSync(n))return"missing";try{let i=se.readFileSync(n,"utf-8");return xs(i)?(se.statSync(n).mode&73)!==0?"installed":"disabled":"foreign"}catch{return"foreign"}}function Zt(s){let e=[],t=[],n=[],i=[],r={};for(let a of uo){let c=op(s,a);r[a]=c,c==="installed"&&e.push(a),c==="missing"&&t.push(a),c==="foreign"&&n.push(a),c==="disabled"&&i.push(a)}let o=[...t,...n,...i];return{installed:e,notInstalled:o,missing:t,foreign:n,disabled:i,statuses:r}}async function vs(s){let e=fo.resolve(s);try{await Q(async()=>{ge("Liquid Shadow Intelligence Dashboard");let t=N.getInstance(e),n=oi(),i=Zt(e),r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);if(ue("Operational Core",`${b.bold("State")}: ${pt(e)?b.green("IDENTIFIED (Stable)"):b.red("UNKNOWN (Needs Index)")}
|
|
645
|
+
${b.bold("Repository")}: ${b.cyan(fo.basename(e))}
|
|
646
|
+
${b.bold("Infrastructure")}: ${i.installed.length>0?b.green("Git-Hooked"):b.yellow("Standalone")}
|
|
647
|
+
${b.bold("Last Sync")}: ${a?b.yellow(new Date(a).toLocaleString()):b.red("Never")}`,"blue"),console.log(""),ue("Intelligence Density",`${b.bold("Files Target")}: ${b.cyan(r.toString())}
|
|
648
|
+
${b.bold("Symbols Mapped")}: ${b.cyan(o.toString())}
|
|
649
|
+
${b.bold("Graph Edges")}: ${b.cyan(t.imports.getCount().toString())}
|
|
650
|
+
${b.bold("Hotspots")}: ${b.yellow(c.length.toString())}`,"cyan"),n.query.count>0||n.index.runs>0){console.log("");let l=n.index.runs>0?(n.index.cacheHits/n.index.runs*100).toFixed(1):"0.0";ue("Reasoning Efficiency",`${b.bold("Query Count")}: ${b.cyan(n.query.count.toString())}
|
|
651
|
+
${b.bold("Avg Latency")}: ${b.yellow(`${n.query.avgLatencyMs?.toFixed(2)||0}ms`)}
|
|
652
|
+
${b.bold("Cache Hit Rate")}: ${b.green(`${l}%`)}`,"green")}c.length>0&&(console.log(""),console.log(` ${b.bold("Intelligence Landscape")}`),ii(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),35)),console.log(""),Ve("Liquid Shadow is observing.")})}finally{await ne(e)}}Y();ut();import ap from"path";async function go(s){let e=ap.resolve(s);try{await Q(async()=>{let t=N.getInstance(e),n=Zt(e),i=oi(),r=Math.floor(i.uptimeMs/1e3),o=Math.floor(r/60),a=Math.floor(o/60),c=a>0?`${a}h ${o%60}m`:o>0?`${o}m ${r%60}s`:`${r}s`,l=i.index.lastCompletedAt?new Date(i.index.lastCompletedAt).toLocaleString():"Never",p=i.index.lastDurationMs?`${(i.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",u=i.query.avgLatencyMs?`${i.query.avgLatencyMs.toFixed(2)}ms`:"N/A",d=i.query.lastLatencyMs?`${i.query.lastLatencyMs.toFixed(2)}ms`:"N/A",h=i.index.runs>0?(i.index.cacheHits/i.index.runs*100).toFixed(1):"0.0";ue("Performance Metrics",`${b.bold("Uptime")}: ${b.cyan(c)}
|
|
653
|
+
${b.bold("Indexed")}: ${pt(e)?b.green("Yes"):b.red("No")}
|
|
654
|
+
${b.bold("Files")}: ${b.cyan(t.files.getCount().toString())}
|
|
655
|
+
${b.bold("Exports")}: ${b.cyan(t.exports.getCount().toString())}
|
|
656
|
+
${b.bold("Imports")}: ${b.cyan(t.imports.getCount().toString())}
|
|
657
|
+
${b.bold("Last Indexed Commit")}: ${fn(e)?b.yellow(fn(e).substring(0,7)):b.red("None")}
|
|
658
|
+
${b.bold("Git Hooks")}: ${n.installed.length>0?b.green("Installed"):b.yellow("Not Installed")}`,"blue"),console.log(""),ue("Index Metrics",`${b.bold("Total Runs")}: ${b.cyan(i.index.runs.toString())}
|
|
659
|
+
${b.bold("Cache Hits")}: ${b.cyan(i.index.cacheHits.toString())}
|
|
660
|
+
${b.bold("Cache Hit Rate")}: ${b.cyan(`${h}%`)}
|
|
661
|
+
${b.bold("Last Duration")}: ${b.yellow(p)}
|
|
662
|
+
${b.bold("Last Completed")}: ${b.yellow(l)}`,"cyan"),i.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${b.bold("Last Index Run Phases:")}`),i.index.lastRunPhases.forEach(m=>{let f=`${(m.durationMs/1e3).toFixed(2)}s`;console.log(` ${b.gray(m.phase.padEnd(20))} ${b.cyan(f)}`)})),console.log(""),ue("Query Metrics",`${b.bold("Total Queries")}: ${b.cyan(i.query.count.toString())}
|
|
663
|
+
${b.bold("Avg Latency")}: ${b.yellow(u)}
|
|
664
|
+
${b.bold("Last Latency")}: ${b.yellow(d)}
|
|
665
|
+
${b.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?b.red(i.query.searchHistoryFailures.toString()):b.green("0")}`,"green")})}finally{await ne(e)}}import lu from"path";G();import La from"path";import cu from"ignore";import Ma from"fs";import ai from"path";var cp=50;function ci(s,e,t,n){let i={name:ai.basename(e)||e,type:"directory",path:e,children:[]};return s.forEach(r=>{let a=ai.relative(e,r.path).split(ai.sep),c=i;for(let l=0;l<a.length;l++){let p=a[l];if(n!==void 0&&l>=n)return;let u=l===a.length-1;if(n===1&&l===0&&u)return;let d=n!==void 0&&l===n-1&&!u,h=ai.join(e,...a.slice(0,l+1)),m=c.children?.find(f=>f.name===p);if(!m){if(c.children&&c.children.length>=cp){c.children.find(y=>y.type==="truncated")||c.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}m={name:p,type:u?"file":"directory",path:h,children:u||d?void 0:[],summary:u?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},m.summary&&(t==="structure"||t==="signatures")&&(delete m.summary.chunks,delete m.summary.imports),c.children?.push(m)}c=m}}),i}import lp from"fast-glob";import bo from"fs";import pp from"ignore";import _o from"path";var li=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],yo=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],Fe={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},ve={FILTERED_QUERY_LIMIT_MULTIPLIER:3,SCORE_BASE:1e3,EXACT_MATCH_BONUS:500,RECENT_FILE_BOOST:80,OLDER_FILE_BOOST:30,RECENT_FILE_THRESHOLD_DAYS:7,OLDER_FILE_THRESHOLD_DAYS:30,FUZZY_MATCH_LIMIT:30,ENABLE_LEXICAL_SCORING:process.env.ENABLE_LEXICAL_SCORING!=="false",LEXICAL_WEIGHT:parseFloat(process.env.LEXICAL_WEIGHT??String(.4)),GRAVITY_STRUCTURAL_WEIGHT:.5},Rs={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},pi={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function Eo(s,e=[]){let t=pp(),n=_o.join(s,".gitignore");return bo.existsSync(n)&&t.add(bo.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await lp(yo,{cwd:s,absolute:!0,ignore:li,stats:!0})).filter(o=>{let a=_o.relative(s,o.path);return!t.ignores(a)}).map(o=>({path:o.path,mtime:o.stats.mtimeMs}))}import Do from"fs";function So(s){let e=s.split(`
|
|
666
|
+
`),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function re(s,e){for(let t=0;t<e.length;t++)if(e[t+1]>s||t===e.length-1)return t+1;return 1}function ui(s,e){return e.slice(0,s).toString("utf8").length}function wo(s){if(s.toString("utf8").length===s.length)return n=>n;let t=new Map;return n=>{let i=t.get(n);return i===void 0&&(i=s.slice(0,n).toString("utf8").length,t.set(n,i)),i}}function xo(s,e,t){let n=s.start-e,i=s.end-e;return n<0||i>t.length?"":t.slice(n,i).toString("utf8")}function vo(s){let e=[],t=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=t.exec(s))!==null;)e.push({start:n.index,end:n.index+n[0].length,text:n[0]});return e}function nt(s,e,t){for(let n of e){if(n.start===s)return n.text;if(n.start>s&&n.start<s+50){let i=t.substring(s,n.start);if(/^\s*$/.test(i))return n.text}if(n.end<=s&&n.end>s-50){let i=t.substring(n.end,s);if(/^\s*$/.test(i))return n.text}}return""}function Ro(s){if(!s)return"";let t=s.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
|
|
667
|
+
`)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function di(s,e,t){let n=s.toLowerCase(),i=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||i.startsWith("use")?"Hook":n.includes("models/")||i.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||i.endsWith("service")||i.endsWith("controller")||i.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||i.endsWith("repository")||i.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function En(s){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(s)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(s)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(s)||/\.query\s*\(|\.execute\s*\(/i.test(s)&&/db|database|client|pool/i.test(s))&&e.push("Database"),(/\bfs\./i.test(s)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(s)||/import\s+.*\bfs\b/.test(s))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(s)||/\bdocument\.cookie\b/.test(s))&&e.push("Browser Storage"),e}function We(s,e){if(!s)return"";let t=s.trimStart();for(;/^\/\*[\s\S]*?\*\//.test(t);)t=t.replace(/^\/\*[\s\S]*?\*\/\s*/,"");for(;/^\/\/[^\n]*\n/.test(t);)t=t.replace(/^\/\/[^\n]*\n\s*/,"");if(t=t.replace(/^(?:import[^\n]*\n)+/,"").replace(/^(?:export\s+\{[^}]*\}\s+from\s+['"][^'"]+['"];?\s*\n?)+/,"").trim(),e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,i=0,r=t.length;for(let a=0;a<t.length;a++){let c=t[a];if(c==="(")n++;else if(c===")")n--;else if(c==="<")i++;else if(c===">")i--;else if(c==="{"){if(n===0&&i===0){r=a;break}}else if(c===";"&&n===0&&i===0){r=a;break}else if(c==="="&&t[a+1]===">"&&n===0&&i===0){r=a+2;break}}let o=t.substring(0,r).trim();return o.length>500?o.slice(0,497)+"...":o}function To(s){let e=[];for(let t of s)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join(", ")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function up(s,e){for(let t of s){if((t.type==="FunctionDeclaration"||t.type==="ClassDeclaration")&&(t.identifier?.value||t.id?.value)===e)return t.span;if(t.type==="VariableDeclaration"){for(let n of t.declarations)if(n.id?.type==="Identifier"&&n.id.value===e)return n.span||t.span}if((t.type==="TsTypeAliasDeclaration"||t.type==="TsInterfaceDeclaration"||t.type==="TsEnumDeclaration")&&(t.id?.value||t.identifier?.value)===e)return t.span;if(t.type==="ExportDeclaration"){let n=t.declaration;if(!n)continue;if((n.type==="FunctionDeclaration"||n.type==="ClassDeclaration")&&(n.identifier?.value||n.id?.value)===e)return n.span||t.span;if(n.type==="VariableDeclaration"){for(let i of n.declarations)if(i.id?.type==="Identifier"&&i.id.value===e)return i.span||n.span||t.span}}}return null}function ko(s,e,t,n,i,r,o,a,c){let l=c??(u=>ui(u,t)),p=[];for(let u of s){if(u.type==="ExportDeclaration"){let d=u.declaration,h=d.type,m="";h==="VariableDeclaration"?m=d.declarations.map(R=>R.id.value).join("",""):m=d.id?.value||d.identifier?.value||"anonymous";let f=l(u.span.start-e),S=l(u.span.end-e),y=nt(f,r,n),_=a(u.span),E=[];if(u.type==="ExportDeclaration"&&(h==="ClassDeclaration"||h==="ClassExpression")){let R=d.body||[];for(let T of R)if(T.type==="ClassMethod"||T.type==="ClassProperty"){let k=T.key.value;if(!k)continue;let F=l(T.span.start-e),B=l(T.span.end-e),M=a(T.span),v=nt(F,r,n);E.push({name:k,kind:T.type,signature:We(M,T.type),line:re(F,i),endLine:re(B,i),doc:v,classification:T.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(h==="FunctionDeclaration"&&d.body?.type==="BlockStatement")E=Ts(d.body.stmts,e,t,n,i,r,a,l);else if(h==="VariableDeclaration"){for(let R of d.declarations)if(R.init&&(R.init.type==="ArrowFunctionExpression"||R.init.type==="FunctionExpression")&&R.init.body?.type==="BlockStatement"){E=Ts(R.init.body.stmts,e,t,n,i,r,a,l);break}}p.push({name:m,kind:h,signature:We(_,h),line:re(f,i),endLine:re(S,i),doc:y,classification:di(o,m,h),capabilities:JSON.stringify(En(_)),members:E})}if(u.type==="ExportNamedDeclaration"){for(let d of u.specifiers)if(d.type==="ExportSpecifier"){let h=d.orig.value,m=d.exported?.value||h,S=up(s,h)||u.span,y=l(S.start-e),_=l(S.end-e),E=nt(y,r,n);p.push({name:m,kind:"ExportSpecifier",signature:`export { ${h} }`,line:re(y,i),endLine:re(_,i),doc:E,classification:"Export mapping",capabilities:"[]"})}}if(u.type==="ExportDefaultDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=nt(d,r,n),f=a(u.span),S=[];if(u.decl.type==="ClassExpression"||u.decl.type==="ClassDeclaration"){let y=u.decl.body||[];for(let _ of y)if(_.type==="ClassMethod"||_.type==="ClassProperty"){let E=_.key.value;if(!E)continue;let R=l(_.span.start-e),T=l(_.span.end-e),k=a(_.span),F=nt(R,r,n);S.push({name:E,kind:_.type,signature:We(k,_.type),line:re(R,i),endLine:re(T,i),doc:F,classification:_.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(u.decl.type==="FunctionExpression"||u.decl.type==="FunctionDeclaration"||u.decl.type==="ArrowFunctionExpression")&&u.decl.body?.type==="BlockStatement"&&(S=Ts(u.decl.body.stmts,e,t,n,i,r,a,l));p.push({name:"default",kind:"DefaultExport",signature:We(f,"DefaultExport"),line:re(d,i),endLine:re(h,i),doc:m,classification:"Default Export",capabilities:JSON.stringify(En(f)),members:S})}if(u.type==="ExportAllDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=u.source.value,f=nt(d,r,n);p.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${m}"`,line:re(d,i),endLine:re(h,i),doc:f,classification:"Re-export",capabilities:"[]"})}}return p}function Ts(s,e,t,n,i,r,o,a){let c=[];for(let l of s){if(l.type==="VariableDeclaration")for(let p of l.declarations){let u=[],d=m=>{if(m.type==="Identifier")u.push({name:m.value,span:m.span});else if(m.type==="ArrayPattern")for(let f of m.elements)f&&d(f);else if(m.type==="ObjectPattern")for(let f of m.properties)f.type==="AssignmentPatternProperty"?u.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&d(f.value)};d(p.id);let h=p.init&&(p.init.type==="ArrowFunctionExpression"||p.init.type==="FunctionExpression");for(let m of u){let f=h?p.init.span||p.span||m.span:p.span||m.span,S=h?p.init.type:"VariableDeclaration",y=h?"Internal Function":"Internal Variable",_=a(f.start-e),E=a(f.end-e),R=o(f),T=nt(_,r,n);c.push({name:m.name,kind:S,signature:We(R,S),line:re(_,i),endLine:re(E,i),doc:T,classification:y,capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let p=l.identifier?.value||l.ident?.value||"anonymous",u=a(l.span.start-e),d=a(l.span.end-e),h=o(l.span),m=nt(u,r,n);c.push({name:p,kind:"FunctionDeclaration",signature:We(h,"FunctionDeclaration"),line:re(u,i),endLine:re(d,i),doc:m,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let p of l.argument.properties){let u="",d=p.span||p.key?.span||p.ident?.span;if(p.type==="KeyValueProperty"){let h=p.key;u=h?.value||h?.raw||(h?.type==="Identifier"?h.value:"")}else p.type==="MethodProperty"?u=p.key?.value||p.key?.raw||"":p.type==="ShorthandProperty"?u=p.ident?.value||"":p.type==="Identifier"&&(u=p.value||"");if(u&&d){let h=a(d.start-e),m=a(d.end-e),f=o(d),S=nt(h,r,n);c.push({name:u,kind:"ReturnProperty",signature:We(f,"ReturnProperty"),line:re(h,i),endLine:re(m,i),doc:S,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let p=l.expression;if(p.callee.type==="MemberExpression"&&(p.callee.property?.value==="on"||p.callee.property?.value==="once")){let u=p.arguments[0]?.expression?.value,d=p.arguments[1]?.expression;if(u&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let h=a(d.span.start-e),m=a(d.span.end-e),f=o(d.span);c.push({name:`on:${u}`,kind:d.type,signature:We(f,d.type),line:re(h,i),endLine:re(m,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(p.callee.type==="Identifier"&&p.callee.value==="addRoute"&&p.arguments.length>=3){let u=p.arguments[2].expression;if(u.type==="StringLiteral"){let d=u.value,h=a(p.span.start-e),m=a(p.span.end-e),f=o(p.span);c.push({name:d,kind:"HTTP Route",signature:We(f,"HTTP Route"),line:re(h,i),endLine:re(m,i),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:d})})}}}}return c}function Co(s,e,t,n,i,r){let o=r??(l=>ui(l,t)),a=[];function c(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let p=dp(l);if(p){let u=o(l.span.start-e);a.push({...p,line:re(u,n),snippet:i(l.span)})}}for(let p of Object.keys(l)){if(p==="span")continue;let u=l[p];Array.isArray(u)?u.forEach(c):typeof u=="object"&&c(u)}}}return s.forEach(c),a}function dp(s){let{callee:e,arguments:t}=s;if(!t||t.length===0)return null;if(e.type==="Identifier"&&e.value,e.type==="Identifier"&&e.value==="addRoute"&&t.length>=3){let n=t[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value,o=e.object.type==="Identifier"?e.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(o))return{type:"api_route",name:r,direction:"produce"};if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function Sn(s){let{classification:e,capabilities:t,exports:n,fileName:i}=s,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(m=>r[m]).filter(Boolean).join(" and "),c={Component:(m,f)=>{let S=f.find(_=>_.kind==="FunctionDeclaration"||_.kind==="ClassDeclaration")?.name,y=S?`React component: ${S}`:"React UI component";return m?`${y} with ${m}`:y},Hook:(m,f)=>{let S=f.find(_=>_.name.startsWith("use"))?.name,y=S?`Custom React hook: ${S}`:"Custom React hook";return m?`${y} for ${m}`:y},Service:(m,f)=>{let y=`Service layer: ${f[0]?.name||"Service"}`;return m?`${y} handling ${m}`:y},Repository:(m,f)=>`Data repository: ${f[0]?.name||"Repository"} for ${m||"data access"}`,"Type Definition":(m,f)=>`Type definitions: ${f.slice(0,3).map(y=>y.name).join("")}${f.length>3?"...":""}`,Model:(m,f)=>`Data model: ${f[0]?.name||"Model"}`,"HTTP Route":(m,f)=>{let S=f.filter(y=>y.classification==="Service Boundary");return S.length>0?`API endpoints: ${S.slice(0,3).map(y=>y.name).join("")}`:"API route handler"},"Micro IR (PHP)":(m,f)=>{let S=f.some(_=>_.classification==="Service Boundary"),y=f.find(_=>_.kind==="ClassDeclaration")?.name;return S?"PHP controller with API routes":y?`PHP class: ${y}`:"PHP module"},"Micro IR (Python)":(m,f)=>{let S=f.some(_=>_.classification==="Service Boundary"),y=f.find(_=>_.kind==="ClassDeclaration")?.name;return S?"Python API handler with routes":y?`Python class: ${y}`:"Python module"},"Micro IR (Go/TS) ":(m,f)=>{let S=f.some(_=>_.kind==="TypeDeclaration"),y=f.filter(_=>_.kind==="FunctionDeclaration");return S&&y.length>0?`Go package: types and ${y.length} function(s)`:S?"Go package: type definitions":y.length>0?`Go package: ${y[0].name} and ${y.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(m,f)=>{let S=f.find(E=>E.kind==="TraitDeclaration")?.name,y=f.find(E=>E.kind==="StructDeclaration")?.name,_=f.filter(E=>E.kind==="FunctionDeclaration");return S?m.includes("Rust trait")?`Rust module: trait ${S}`:`Rust module: ${S}`:y?`Rust module: struct ${y}`:_.length>0?`Rust module: ${_.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return i?`Module: ${i}`:"Module with no exports";let l=n.filter(m=>m.kind==="FunctionDeclaration"),p=n.filter(m=>m.kind==="ClassDeclaration"),u=n.filter(m=>m.kind==="TsInterfaceDeclaration"||m.kind==="TsTypeAliasDeclaration"),d=[];if(p.length>0&&d.push(`Class: ${p[0].name}`),l.length>0){let m=l.slice(0,2).map(f=>f.name).join("");d.push(`Functions: ${m}`)}u.length>0&&d.push(`Types: ${u.length}`);let h=d.length>0?d.join(" | "):`Module with ${n.length} export(s)`;return o?`${h} \u2014 ${o}`:h}function Io(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&de(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&de(n,e);for(let i in n){if(i==="span"||i==="comments"||i==="interpreter")continue;let r=n[i];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return s.forEach(n=>t(n)),Array.from(e)}function de(s,e){if(s){if(s.type==="TsTypeAnnotation"){de(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&Lo(s.typeName,e),s.typeParams&&de(s.typeParams,e)),s.type==="TsArrayType"&&de(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>de(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>de(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>de(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>de(t.typeAnnotation,e)),s.typeAnnotation&&de(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&de(t.constraint,e),t.default&&de(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>de(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&de(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(de(s.objectType,e),de(s.indexType,e)),s.type==="TsConditionalType"&&(de(s.checkType,e),de(s.extendsType,e),de(s.trueType,e),de(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&de(t.typeAnnotation,e)})}}function Lo(s,e){s.type==="TsQualifiedName"?(s.left&&Lo(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}import Oo from"path";import ks from"path";G();Nt();import Ao from"path";import mp from"fs";import{fileURLToPath as hp}from"url";import*as Ot from"web-tree-sitter";var Vf=Ao.dirname(hp(import.meta.url)),Mo=w.child({module:"parser:tree-sitter"}),mi=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=Ot.Parser||Ot;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=Le("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!mp.existsSync(t))return Mo.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await Ot.Language.load(t);return this.languages.set(e,n),n}catch(n){return Mo.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
|
|
615
668
|
(function_definition name: (name) @name) @func
|
|
616
669
|
(class_declaration name: (name) @name) @class
|
|
617
670
|
(interface_declaration name: (name) @name) @interface
|
|
@@ -635,55 +688,57 @@ ${y.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?y.red(i.
|
|
|
635
688
|
(trait_item name: (_type_identifier) @name) @trait
|
|
636
689
|
(type_item name: (_type_identifier) @name) @type
|
|
637
690
|
(use_declaration argument: (_) @name) @import
|
|
638
|
-
`;default:return""}}mapKind(e,t){if(e==="import")return"ImportDeclaration";if(t===".php"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration";if(e==="interface")return"InterfaceDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="method")return"MethodDeclaration"}if(t===".py"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration"}if(t===".go"){if(e==="func")return"FunctionDeclaration";if(e==="type")return"TypeDeclaration"}if(t===".rs"){if(e==="func")return"FunctionDeclaration";if(e==="struct")return"StructDeclaration";if(e==="enum")return"EnumDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(e){return e==="import"?"Dependency":e==="func"||e==="method"?"Function":e==="class"||e==="interface"||e==="trait"||e==="struct"||e==="enum"||e==="type"?"Class":"Other"}async parse(e,t){await this.ensureInitialized();let n=
|
|
639
|
-
`),a=this.getQueries(n);if(!a)return[];let l=new
|
|
640
|
-
`),o="",a="",c=0,l=0,p=-1,u=-1,d=[],h=[],m=!1,f=t?"api":"",
|
|
641
|
-
`).trim(),capabilities:JSON.stringify(
|
|
642
|
-
`).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let
|
|
643
|
-
`).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let
|
|
644
|
-
`).trim()
|
|
645
|
-
`)
|
|
646
|
-
`).trim()),
|
|
691
|
+
`;default:return""}}mapKind(e,t){if(e==="import")return"ImportDeclaration";if(t===".php"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration";if(e==="interface")return"InterfaceDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="method")return"MethodDeclaration"}if(t===".py"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration"}if(t===".go"){if(e==="func")return"FunctionDeclaration";if(e==="type")return"TypeDeclaration"}if(t===".rs"){if(e==="func")return"FunctionDeclaration";if(e==="struct")return"StructDeclaration";if(e==="enum")return"EnumDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(e){return e==="import"?"Dependency":e==="func"||e==="method"?"Function":e==="class"||e==="interface"||e==="trait"||e==="struct"||e==="enum"||e==="type"?"Class":"Other"}async parse(e,t){await this.ensureInitialized();let n=Ao.extname(e).toLowerCase(),i=await this.getLanguage(n);if(!i||!this.parser)return[];this.parser.setLanguage(i);let r=this.parser.parse(t),o=t.split(`
|
|
692
|
+
`),a=this.getQueries(n);if(!a)return[];let l=new Ot.Query(i,a).matches(r.rootNode),p=[];for(let u of l){let d=u.captures.find(f=>f.name==="name")?.node,h=u.captures[0].node,m=u.captures[0].name;if(d){let f=h.startPosition.row+1,S=h.endPosition.row+1,y=o[h.startPosition.row].trim();p.push({name:d.text,kind:this.mapKind(m,n),classification:this.mapClassification(m),signature:y,line:f,endLine:S,doc:"",capabilities:"{}"})}}return p}};var hi=class{parse(e,t=!1){let n=[],i=[],r=e.split(`
|
|
693
|
+
`),o="",a="",c=0,l=0,p=-1,u=-1,d=[],h=[],m=!1,f=t?"api":"",S="",y=/^namespace\s+([a-zA-Z0-9_\\]+);/,_=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,E=/^interface\s+([a-zA-Z0-9_]+)/,R=/^trait\s+([a-zA-Z0-9_]+)/,T=/^enum\s+([a-zA-Z0-9_]+)(?:\s*:\s*(string|int))?\s*/,k=/^((?:(?:public|protected|private|static)\s+)*)function\s+([a-zA-Z0-9_]+)\s*\(/,F=/^(public|protected|private)\s+(static\s+)?(readonly\s+)?(?:(\?\s*)?([a-zA-Z0-9_\\|]+)\s+)?\$([a-zA-Z0-9_]+)/,B=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,M=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,v=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,I=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/,$=/\$this->(hasMany|hasOne|belongsTo|belongsToMany|morphTo|morphMany|morphOne|morphToMany|morphedByMany)\s*\(\s*([a-zA-Z0-9_\\]+)(?:::class)?/,P=/^->(hasMany|hasOne|belongsTo|belongsToMany|morphTo|morphMany|morphOne|morphToMany|morphedByMany)\s*\(\s*([a-zA-Z0-9_\\]+)(?:::class)?/,U=/(public|protected|private)\s+(readonly\s+)?(?:(\?\s*)?([a-zA-Z0-9_\\|]+)\s+)?\$([a-zA-Z0-9_]+)/g,A=/(?:protected|public)\s+\$(fillable|casts|guarded|hidden|appends|with)\s*=/;function H(g){try{let x=JSON.parse(g||"{}");if(x&&typeof x=="object"&&!Array.isArray(x))return x}catch{}return{}}function L(g,x){let O=[],C=g,W=0,j=0;for(;C<r.length;){let Z=r[C].trim();O.push(Z),W+=(Z.match(/\[/g)||[]).length-(Z.match(/]/g)||[]).length,j+=(Z.match(/\(/g)||[]).length-(Z.match(/\)/g)||[]).length;let he=Z.includes(x),Ce=W<=0&&j<=0;if(he&&Ce)break;C+=1}return{text:O.join(" "),endIndex:C}}function D(g,x){let O=x.replace(/^[^=]+=\s*/,"").replace(/;$/,"").trim();if(g==="casts"){let Z={},he=/['"]([^'"]+)['"]\s*=>\s*['"]([^'"]+)['"]/g,Ce=null;for(;Ce=he.exec(O);)Z[Ce[1]]=Ce[2];return Z}let C=[],W=/['"]([^'"]+)['"]/g,j=null;for(;j=W.exec(O);)C.push(j[1]);return C}function J(g,x){for(let O=x;O>=0;O-=1){let C=g[O]?.trim()||"";if(C)return C}return""}function z(g,x,O,C){if(!o)return;let W=x.split("\\").pop()||x;i.push({type:"eloquent_relation",name:W,direction:"produce",line:O,snippet:C,method:g,url:`${o}->${W}`})}for(let g=0;g<r.length;g++){let x=r[g].trim();if(!x)continue;let O=(x.match(/{/g)||[]).length,C=(x.match(/}/g)||[]).length,W=l;if(l+=O-C,a&&l<=u){let V=n.find(q=>q.name===a&&q.line===c);V&&(V.endLine=g+1),a="",u=-1}if(o&&l<=p){let V=n.find(q=>q.name===o&&(q.kind==="ClassDeclaration"||q.kind==="TraitDeclaration"||q.kind==="InterfaceDeclaration"||q.kind==="EnumDeclaration"));V&&(V.endLine=g+1),o="",p=-1}let j=x.match(I);if(j&&(f=j[1]),x.includes("});")&&(f=""),x.startsWith("/**")){m=!0,h=[];continue}if(m){x.endsWith("*/")?m=!1:h.push(x.replace(/^\*\s?/,""));continue}let Z=x.match(M);if(Z){d.push(Z[1]);continue}let he=x.match(y);if(he){S=he[1]||"",d=[],h=[];continue}let Ce=x.match(_);if(Ce){o=Ce[1],p=l-O;let V={attributes:d};S&&(V.namespace=S),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:g+1,endLine:g+1,doc:h.join(`
|
|
694
|
+
`).trim(),capabilities:JSON.stringify(V),members:[]}),d=[],h=[];continue}let Ie=x.match(E);if(Ie){let V=Ie[1];o=V,p=l-O,n.push({name:V,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${V}`,line:g+1,endLine:g+1,doc:h.join(`
|
|
695
|
+
`).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let gt=x.match(R);if(gt){let V=gt[1];o=V,p=l-O,n.push({name:V,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${V}`,line:g+1,endLine:g+1,doc:h.join(`
|
|
696
|
+
`).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let fe=x.match(T);if(fe){let V=fe[1],q=fe[2]||null;o=V,p=l-O;let X={attributes:d,backedType:q};S&&(X.namespace=S),n.push({name:V,kind:"EnumDeclaration",classification:"Enum",signature:q?`enum ${V}: ${q}`:`enum ${V}`,line:g+1,endLine:g+1,doc:h.join(`
|
|
697
|
+
`).trim(),capabilities:JSON.stringify(X),members:[]}),d=[],h=[];continue}let $e=x.match(k);if($e){let V=($e[1]||"").trim(),q=$e[2],X=!!o,xe=/\bprivate\b/.test(V)?"private":/\bprotected\b/.test(V)?"protected":"public",ce=/\bstatic\b/.test(V),je=L(g,")"),at=je.text.match(/\)\s*:\s*([?a-zA-Z0-9_\\|]+)/),Pn=at?at[1]:null,nl=O>0&&C>=O;a=q,c=g+1,u=l-O;let gr=!1,ss={};for(let Ne of d)Ne.toLowerCase().includes("route")&&(gr=!0,ss={type:"route",method:"GET",path:"/"});let yr=h.join(`
|
|
698
|
+
`).trim();if(gr){let Ne=ss.path||"/";n.push({name:Ne,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${q}`,line:g+1,endLine:g+1,doc:yr,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${q}`:q,...ss})}),i.push({type:"api_route",name:Ne,direction:"consume",line:g+1,snippet:x})}let br={name:q,kind:X?"MethodDeclaration":"FunctionDeclaration",classification:X?"Method":"Function",signature:`${X?o+":: ":""}${q}`,line:g+1,endLine:g+1,doc:yr,capabilities:JSON.stringify(X?{attributes:d,visibility:xe,static:ce,returnType:Pn}:{attributes:d,returnType:Pn})};n.push(br);let rs=X?x.match($):null;if(rs&&z(rs[1],rs[2],g+1,x),X&&q==="__construct"){let Ne=null;for(;Ne=U.exec(je.text);){let _r=Ne[1],Er=!!Ne[2],os=Ne[4]?`${Ne[3]?"?":""}${Ne[4]}`:null,Sr=Ne[5],il=`${_r} ${Er?"readonly ":""}${os?`${os} `:""}$${Sr}`.trim();n.push({name:Sr,kind:"PropertyDeclaration",classification:"Property",signature:il,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({visibility:_r,static:!1,readonly:Er,type:os}),members:[]})}U.lastIndex=0}nl&&(br.endLine=g+1,a="",u=-1),d=[],h=[];continue}let Pe=!1,Ee=!1,K=g,ae=o&&!a?x.match(F):null;if(ae){Pe=!0;let V=ae[1],q=!!ae[2],X=!!ae[3],xe=ae[5]?`${ae[4]?"?":""}${ae[5]}`:null,ce=ae[6],je=`${V} ${q?"static ":""}${X?"readonly ":""}${xe?`${xe} `:""}$${ce}`.trim();n.push({name:ce,kind:"PropertyDeclaration",classification:"Property",signature:je,line:g+1,endLine:g+1,doc:h.join(`
|
|
699
|
+
`).trim(),capabilities:JSON.stringify({visibility:V,static:q,readonly:X,type:xe}),members:[]})}let ot=o&&!a?x.match(A):null;if(ot){Ee=!0;let V=ot[1],q=L(g,";");K=q.endIndex;let X=D(V,q.text),xe=[...n].reverse().find(ce=>ce.name===o&&ce.kind==="ClassDeclaration");if(xe){let ce=H(xe.capabilities);(!ce.modelConfig||typeof ce.modelConfig!="object"||Array.isArray(ce.modelConfig))&&(ce.modelConfig={}),ce.modelConfig[V]=X,xe.capabilities=JSON.stringify(ce)}}if(Pe||Ee){Ee&&K>g&&(g=K),d=[],h=[];continue}let yt=x.match(B);if(yt){let V=yt[1]||"",q=yt[2]||V.split("\\").pop()||"";n.push({name:q,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${V}`,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:V})}),d=[],h=[];continue}let Be=x.match(v);if(Be){let V=Be[1].toUpperCase(),q=Be[2];if(x.includes("Route::")||x.includes("router->")||x.includes("action")||x.includes(",")&&!x.includes("view(")){if(f){let at=f.startsWith("/")?f:`/${f}`,Pn=q.startsWith("/")?q:`/${q}`;q=(at+Pn).replace(/\/+/g,"/")}let xe=null,ce=x.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(ce)xe=`${ce[1]}@${ce[2]}`;else if(x.includes("::class")){let at=x.match(/([a-zA-Z0-9_]+)::class/);at&&(xe=at[1])}let je=x;!x.endsWith(");")&&g+1<r.length&&(je+=" "+r[g+1].trim(),!je.endsWith(");")&&g+2<r.length&&(je+=" "+r[g+2].trim())),n.push({name:q,kind:"HTTP Route",classification:"Service Boundary",signature:je,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"route",method:V,path:q,handler:xe})}),i.push({type:"api_route",name:q,direction:"consume",line:g+1,snippet:je,method:V,url:q}),h=[];continue}}let Ue=o&&a?x.match($):null,$t=o&&a?x.match(P):null;if(Ue)z(Ue[1],Ue[2],g+1,x);else if($t){let V=J(r,g-1);/\$this\b/.test(V)&&z($t[1],$t[2],g+1,x)}let fr=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,we=x.match(fr);if(we){let V=(we[1]||we[3]).toUpperCase(),q=(we[2]||we[4]).trim();(q.startsWith("'")&&q.endsWith("'")||q.startsWith('"')&&q.endsWith('"'))&&(q=q.substring(1,q.length-1)),i.push({type:"api_route",name:q,direction:"produce",line:g+1,snippet:x,method:V,url:q})}!x.startsWith("#[")&&!x.startsWith("//")&&!x.startsWith("*")&&!m&&(d=[],h=[])}return{nodes:n,events:i}}};var fi=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],i=e.split(`
|
|
700
|
+
`),r=[{indent:-1,name:"root",type:"root"}],o=[],a=/^class\s+([a-zA-Z0-9_]+)/,c=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,l=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,p=/^@(.*)/;function u(E){return E.trim().split(/[.(]/)[0]?.trim()||E}function d(E){let R=E.decorators.map(k=>u(k.raw)),T={decorators:E.decorators,decoratorNames:R};return E.async===!0&&(T.async=!0),E.accessor&&(T.accessor=E.accessor),E.contextmanager===!0&&(T.contextmanager=!0),JSON.stringify(T)}function h(E,R){return(E.match(new RegExp(`\\${R}`,"g"))||[]).length}function m(E){let R=[],T=E,k=0,F=0,B=0,M=!1;do{let v=i[T].trim();if(R.push(v),k+=h(v,"(")-h(v,")"),F+=h(v,"[")-h(v,"]"),B+=h(v,"{")-h(v,"}"),M=v.endsWith("\\"),T+1>=i.length||k<=0&&F<=0&&B<=0&&!M)break;T+=1}while(!0);return{text:R.join(" "),endIndex:T}}let f=!1,S="",y=[],_=[];for(let E=0;E<i.length;E++){let R=i[E],T=R.trim();if(!T||T.startsWith("#"))continue;let k=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,F=T.match(k);if(F&&(this.currentRoutePrefix=F[2]),f){if(T.endsWith(S)||T.includes(S)){f=!1;let C=T.replace(S,"").trim();C&&y.push(C);let W=r[r.length-1];W.node&&(W.node.doc=y.join(`
|
|
701
|
+
`).trim()),y=[]}else y.push(T);continue}let B=R.search(/\S/),M=R.trim(),v=M.match(/^(['"]{3})/);if(v){let C=v[1],W=r[r.length-1];if(W.node&&!W.node.doc){if(M.substring(3).includes(C)){let j=M.replace(new RegExp(C,"g"),"").trim();W.node.doc=j}else{f=!0,S=C;let j=M.substring(3).trim();j&&y.push(j)}continue}}for(;r.length>1&&r[r.length-1].indent>=B;)r.pop();let I=r[r.length-1],$=I.type==="root"&&B===0;if($&&/^__all__\s*=/.test(M)){let C=m(E),W=[],j=/['"]([^'"]+)['"]/g,Z=null;for(;Z=j.exec(C.text);)W.push(Z[1]);let he={name:"__all__",kind:"ModuleExports",classification:"ExportList",signature:"__all__ = [...]",line:E+1,endLine:C.endIndex+1,doc:"",capabilities:JSON.stringify({exports:W}),members:[]};_.push(he),t.push(he),E=C.endIndex,o=[];continue}let U=/^([A-Z][A-Z0-9_]*)(?:\s*:\s*[^=]+)?\s*=/,A=$?M.match(U):null;if(A){let C=m(E),W=C.text.length>120?`${C.text.slice(0,117)}...`:C.text,j={name:A[1],kind:"VariableDeclaration",classification:"Constant",signature:W,line:E+1,endLine:C.endIndex+1,doc:"",capabilities:"{}",members:[]};_.push(j),t.push(j),E=C.endIndex,o=[];continue}let H=M.match(p);if(H){o.push({raw:H[1].trim(),line:E+1});continue}let L=M.match(a);if(L){let C=L[1],W={name:C,kind:"ClassDeclaration",classification:"Class",signature:`class ${C}`,line:E+1,endLine:E+1,doc:"",capabilities:d({decorators:o}),members:[]};_.push(W),I.node?(I.node.members||(I.node.members=[]),I.node.members.push(W)):t.push(W),r.push({indent:B,name:C,type:"class",node:W}),o=[];continue}let D=M.match(c);if(D){let C=!!D[1],W=D[1]||D[2],j=I.type==="class",Z=o.some(K=>/(?:^|\.)contextmanager$/.test(K.raw.trim())),he;o.some(K=>K.raw.trim()==="property")&&(he="getter");for(let K of o){let ae=K.raw.trim().match(/^[a-zA-Z_][a-zA-Z0-9_]*\.(setter|deleter)$/);if(ae){he=ae[1];break}}let Ce=!1,Ie={};for(let K of o)if(K.raw.match(/(?:app|router)\.(get|post|put|delete|patch|websocket)/)){Ce=!0;let ot=["get","post","put","delete","patch","websocket"].find(Ue=>K.raw.toLowerCase().includes(`.${Ue}`))?.toUpperCase()||"GET",yt=K.raw.match(/['"]([^'"]+)['"]/),Be=yt?yt[1]:"/";if(this.currentRoutePrefix){let Ue=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,$t=Be.startsWith("/")?Be:`/${Be}`;Be=Ue+$t}Ie={type:"route",method:ot,path:Be}}if(Ce){let K=Ie.path||"",ae=Ie.method==="WEBSOCKET",ot={name:K||W,kind:ae?"WebSocket Route":"HTTP Route",classification:"Service Boundary",signature:`Function: ${W}`,line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({handler:j?`${I.name}.${W}`:W,async:C,...Ie})};_.push(ot),t.push(ot),n.push({type:ae?"websocket_route":"api_route",name:K,direction:"consume",line:E+1,snippet:M})}for(let K of o){let ae=K.raw.match(/(?:^|\.)receiver\s*\(\s*([a-zA-Z0-9_\.]+)/);ae&&n.push({type:"signal",name:ae[1].split(".").pop()||ae[1],direction:"consume",line:K.line,snippet:`@${K.raw}`})}let gt=o.some(K=>K.raw==="staticmethod"),fe=o.some(K=>K.raw==="classmethod"),$e=`${C?"async ":""}${j?(gt?"@staticmethod ":fe?"@classmethod ":"")+I.name+".":""}${W}`,Pe=!!he,Ee={name:W,kind:Pe?"PropertyDeclaration":C&&j?"AsyncMethodDeclaration":C?"AsyncFunctionDeclaration":j?"MethodDeclaration":"FunctionDeclaration",classification:Pe?"Property":j?gt||fe?"Static Method":"Method":"Function",signature:$e,line:E+1,endLine:E+1,doc:"",capabilities:d({decorators:o,async:C,accessor:he,contextmanager:Z}),members:[]};_.push(Ee),I.node?(I.node.members||(I.node.members=[]),I.node.members.push(Ee)):t.push(Ee),r.push({indent:B,name:W,type:"function",node:Ee}),o=[];continue}let J=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,z=M.match(J);if(z){let C=z[1].replace(/^\^/,""),W={name:C,kind:"HTTP Route",classification:"Service Boundary",signature:M.trim(),line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:C})};_.push(W),t.push(W),n.push({type:"api_route",name:C,direction:"consume",line:E+1,snippet:M});continue}let g=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,x=M.match(g);if(x){let C=x[1].toUpperCase(),W=x[2].trim();(W.startsWith("'")&&W.endsWith("'")||W.startsWith('"')&&W.endsWith('"'))&&(W=W.substring(1,W.length-1)),n.push({type:"api_route",name:W,direction:"produce",line:E+1,snippet:M,method:C,url:W})}let O=M.match(l);if(O){let C=O[1]||O[2],W={name:C,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${C}`,line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({type:"import",module:C})};_.push(W),t.push(W),o=[];continue}o=[],I.node&&(I.node.endLine=E+1)}return{nodes:_,events:n}}};function fp(s,e){let t=0,n=!1;for(let i=e;i<s.length;i++){let r=s[i];for(let o of r)if(o==="{")t++,n=!0;else if(o==="}"&&(t--,n&&t<=0))return i+1;if(!n&&i>e&&/[;}]$/.test(r.trim()))return i+1}return Math.min(s.length,e+41)}var $o=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function",signature:s[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:s=>({name:s[1],kind:"MethodDeclaration",classification:"Method",signature:s[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:s=>({name:s[1],kind:"ImportSpecifier",classification:"Dependency",signature:s[0],meta:{type:"import",path:s[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function",signature:s[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"StructDeclaration",classification:"Class",signature:s[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"EnumDeclaration",classification:"Class",signature:s[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"TraitDeclaration",classification:"Class",signature:s[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:s=>({name:s[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:s[0],meta:{type:"import",path:s[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:s=>({name:s[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:s=>({name:s[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:s[1]}})}]}];function gp(s,e){let t=[];if(s===".go"&&e.some(n=>n.kind==="TypeDeclaration")&&t.push("Go type"),s===".rs"&&(e.some(n=>n.kind==="TraitDeclaration")&&t.push("Rust trait"),e.some(n=>n.kind==="StructDeclaration")&&t.push("Rust struct"),e.some(n=>n.kind==="EnumDeclaration")&&t.push("Rust enum")),s===".py"){for(let n of e)if(n.capabilities)try{if(JSON.parse(n.capabilities).decoratorNames?.length){t.push("Python decorators");break}}catch{}e.some(n=>n.kind==="AsyncFunctionDeclaration"||n.kind==="AsyncMethodDeclaration")&&t.push("Async")}return t}var gi=class{phpParser=new hi;pythonParser=new fi;treeSitterParser=new mi;supports(e){return $o.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=ks.extname(e).toLowerCase(),i=[],r=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let l=this.pythonParser.parse(t);i=l.nodes,r=l.events}else if(n===".php"){let l=e.toLowerCase().endsWith("api.php"),p=this.phpParser.parse(t,l);i=p.nodes,r=p.events}else try{i=await this.treeSitterParser.parse(e,t)}catch{}if(i.length>0){let l=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",p=i.filter(m=>m.classification!=="Dependency"),u=i.filter(m=>m.classification==="Dependency"),d=gp(n,i),h=Sn({classification:l,capabilities:d,exports:p.map(m=>({name:m.name,kind:m.kind,classification:m.classification})),fileName:ks.basename(e)});return{exports:p,imports:u.map(m=>({module:m.name,name:m.name,kind:m.kind,classification:m.classification})),events:r,classification:l,summary:h||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=$o.find(l=>l.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};let a=t.split(`
|
|
647
702
|
`);for(let l of o.rules){l.regex.lastIndex=0;let p;for(;(p=l.regex.exec(t))!==null;){let u=l.onMatch(p),d=t.substring(0,p.index).split(`
|
|
648
|
-
`).length,h=
|
|
649
|
-
`);for(let n of t){let i=n.trim();if(i.startsWith("FROM "))e.push({key:"base_image",value:i.substring(5).trim(),kind:"Image"});else if(i.startsWith("EXPOSE "))e.push({key:"port",value:i.substring(7).trim(),kind:"Port"});else if(i.startsWith("ENV ")){let r=i.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],a=r.slice(1).join("= ").trim()||"undefined",c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:a,kind:c})}}}}function
|
|
650
|
-
`);for(let n of t){let i=n.trim();if(i&&!i.startsWith("#")){let r=i.split("=");if(r[0]){let o=r[0].trim(),a=r.slice(1).join("=");a=a.trim().replace(/^['"](.*)['"]$/,"$1");let c="Env",l=a.includes("://");(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&l&&(c="Service"),e.push({key:o,value:a,kind:c})}}}}function
|
|
651
|
-
`):[]}catch{return[]}}function
|
|
652
|
-
`).some(r=>r&&
|
|
653
|
-
`).some(i=>i?
|
|
654
|
-
`).map(p=>p.trim().replace(/^\* /,"")).filter(p=>p&&p!==i)}catch{}if(c.length>0){let l=this.missions.findMergedMissions(i,c);for(let p of l)this.missions.updateStatus(p.id,"completed"),
|
|
655
|
-
`).filter(Boolean);for(let i of n){let[r,o,a,c]=i.split("|"),l=this.analyzeCommitImpact(r);if(l.significant){let p=Array.from(l.layers).join(", "),u=`Heritage: ${c} (by ${a}). Touched ${l.fileCount} files across [${p}].`;this.repos.intentLogs.importHeritage(u,r,parseInt(o,10),.7),
|
|
656
|
-
`).filter(Boolean);n=r.length;for(let c of r){let l=this.classifyPathOnly(c);l!=="Unknown"&&t.add(l)}let o=t.has("Entry")||t.has("Data")||t.has("Infrastructure"),a=t.size>=2||n>5;return{significant:o||a,layers:t,fileCount:n}}catch{return{significant:!1,layers:t,fileCount:0}}}classifyPathOnly(e){let t=e.startsWith("/")?e:"/"+e;return
|
|
657
|
-
`).length:0,t=ia(s?.exports),n=0,i=0,r=0,o=0;for(let a of t){let c=ta(a?.line??a?.start_line),l=ta(a?.endLine??a?.end_line??c);if(!c||!l||l<c||e>0&&l>e){i++;continue}n++,l>c&&o++,e>0&&c===e&&l===e&&r++}return{total:t.length,valid:n,invalid:i,eofCollapsed:r,multiLine:o,lineCount:e}}function Hp(s){let e=sa(s);if(e.total===0||e.lineCount===0)return!1;if(e.invalid>0)return!0;let t=e.eofCollapsed/e.total;return e.eofCollapsed>=3&&t>=.5||e.total>=2&&e.eofCollapsed===e.total}function na(s){let e=sa(s);return e.valid*2+e.multiLine*2-e.eofCollapsed*3-e.invalid*4}async function X(s,e=Wp,t=!1,n=!0,i){let r=O.getInstance(s),o=r.files.database,a=Ke(s),c=a.concurrency??e;if(Or(),!t&&Xe(s)){let g=nn(s),b=De(s);if(g&&!xo(s,g))return os(),S.debug({repoPath:s,commit:b},"Index is current, skipping re-index (fast-path)"),o}ri(s);let l=r.files.findAll(),p=new Map(l.map(g=>[g.path,{mtime:g.mtime,hash:g.content_hash}])),u=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let d=await Jr(s,a.ignore),h=new Map(d.map(g=>[g.path,g.mtime])),m=l.filter(g=>!h.has(g.path)).map(g=>g.path),f=l.length===0,_=[];if(t||f)_.push(...d);else{let g=d.filter(R=>{let k=p.get(R.path);return!k||k.mtime!==R.mtime}),b=xs(c*4),w=g.map(R=>b(async()=>{let k=p.get(R.path);if(!k||!k.hash)return R;try{let D=await Dp.promises.readFile(R.path,"utf8");return sr(D,k.hash)?R:(r.files.updateMtime(R.path,R.mtime),null)}catch{return null}})),x=await Promise.all(w);_.push(...x.filter(R=>R!==null))}if(m.length===0&&_.length===0){os();let g=De(s);return Yi(s,g||void 0),o}if(f?S.info({totalFiles:d.length},"Starting initial repository indexing..."):S.info({toDelete:m.length,toProcess:_.length},"Syncing repository updates..."),m.length>0&&r.files.deletePaths(m),_.length>0){Wr(),n?(Pn(!0),Ot().initialize().catch(()=>{})):Pn(!1);let g=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,b=[],w=[];for(let $ of _)g.test(vs.basename($.path))?b.push($):w.push($);let x=0,R=_.length,k=!1,D=Ro();try{await D.initialize(),k=!0,S.info({workers:D.workerCount},"Parser worker pool active")}catch($){S.warn({err:$},"Parser worker pool failed to initialize, falling back to main-thread parsing"),k=!1}let U=async($,W)=>{let L=W;if(k&&Hp(W))try{let F=await pn($.path);na(F)>na(W)&&(S.warn({filePath:$.path},"Detected suspicious worker parse ranges; using main-thread parse output"),L=F)}catch(F){S.warn({filePath:$.path,err:F instanceof Error?F.message:String(F)},"Main-thread parse retry failed after suspicious worker parse")}let A=L.imports?.map(F=>({...F,resolved_path:Tt(F.module,$.path,s)})),H=L.content?Nt(L.content):null;return x++,(x%50===0||x===R)&&S.info({completed:x,total:R},"Parsing files..."),i?.({phase:"parse",current:x,total:R,message:`Parsing ${vs.basename($.path)}`}),{meta:$,...L,imports:A,embedding:null,kind:"code",contentHash:H}},P;if(k)P=b.map($=>D.parseFile($.path).then(W=>U($,W),W=>(x++,S.error({path:$.path,error:W},"Worker parse failed"),{meta:$,exports:[],imports:[],content:"",kind:"error"})));else{let $=f?Math.max(c,Math.min(Fp-1,16)):c,W=xs($);P=b.map(L=>W(async()=>{try{let A=await pn(L.path);return U(L,A)}catch(A){return x++,S.error({path:L.path,error:A},"Failed to parse file"),{meta:L,exports:[],imports:[],content:"",kind:"error"}}}))}let E=xs(c),T=w.map($=>E(async()=>{try{let W=bo($.path),L=W.content?Nt(W.content):null;return x++,(x%50===0||x===R)&&S.info({completed:x,total:R},"Parsing configs..."),i?.({phase:"parse",current:x,total:R,message:`Parsing config ${vs.basename($.path)}`}),{meta:$,...W,embedding:null,kind:"config",contentHash:L}}catch(W){return x++,S.error({path:$.path,error:W},"Failed to parse config"),{meta:$,exports:[],imports:[],content:"",kind:"error"}}}));S.info({total:R,codeFiles:b.length,configFiles:w.length,useParserPool:k},"Phase 1: Parsing all files...");let I=Date.now(),M=(await Promise.all([...P,...T])).filter(Boolean),N=Date.now()-I;if(an("parse",N),S.info({count:M.length,time:`${(N/1e3).toFixed(1)}s`},"Phase 1 complete"),k&&ko().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let $=[];M.forEach((C,B)=>{"summary"in C&&C.summary&&$.push({fileIdx:B,text:C.summary})}),S.info("Phase 2+3: Generating file-summary embeddings + persisting in parallel..."),i?.({phase:"embed",current:0,total:M.length,message:"Generating embeddings..."});let W=Date.now(),L=(async()=>{let C=[];return $.length>0&&(S.info({count:$.length}," \u2192 Generating file summary embeddings..."),C=await ns($.map(B=>B.text),256),S.info({count:$.length}," \u2713 File summaries complete")),C})();i?.({phase:"persist",current:0,total:M.length,message:"Saving to database..."});let A=Date.now();r.files.batchSaveIndexResults(M,s,Nt,Tt);let H=Date.now()-A;an("persist",H),S.info({time:`${(H/1e3).toFixed(1)}s`},"Structural persist complete");let F=await L,v=Date.now()-W;if(an("embed",v),S.info({time:`${(v/1e3).toFixed(1)}s`},"File-summary embeddings complete"),F.length>0){let C=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),B=o.transaction(J=>{for(let z of J)C.run(z.embedding?JSON.stringify(z.embedding):null,z.path)}),j=$.map((J,z)=>({path:M[J.fileIdx].meta.path,embedding:F[z]}));B(j),S.info({count:j.length},"File embedding column updated")}}else{i?.({phase:"persist",current:0,total:M.length,message:"Saving to database..."});let $=Date.now();r.files.batchSaveIndexResults(M,s,Nt,Tt),an("persist",Date.now()-$)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(f||_.length>0){let g=De(s);Yi(s,g||void 0)}if(n&&!Zo(s)&&ea(s),(_.length>0||m.length>0)&&new qe(s).detectAndRepairShifts(),f||n)try{new gi(s).analyzeHeritage(50)}catch(g){S.warn({err:g.message},"Heritage sync deferred")}return Fr(Date.now()-u),i?.({phase:"complete",current:_.length,total:_.length,message:"Indexing complete"}),o}V();async function bi(s,e=Qn.DEFAULT_CONCURRENCY,t="detailed",n,i){S.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await X(s,e);let{files:r,exports:o,imports:a}=O.getInstance(s),c=n?r.findInSubPath(s,n):r.findAll(),l=Ke(s),p=zp(),u=ra.join(s,".gitignore");if(oa.existsSync(u)&&p.add(oa.readFileSync(u,"utf8")),l.ignore&&l.ignore.length>0&&p.add(l.ignore),p.add(Kn),c=c.filter(b=>{let w=ra.relative(s,b.path);return!p.ignores(w)}),S.info({count:c.length},"Fetching data from DB..."),t==="lite"){let b=c.map(w=>({path:w.path,mtime:w.mtime}));return Yn(b,s,t,i)}if(t==="summaries"){let b=c.map(w=>({path:w.path,mtime:w.mtime,classification:w.classification||void 0,summary:w.summary||void 0}));return Yn(b,s,t,i)}let d=c.map(b=>b.path),h=o.findByFiles(d),m=t==="detailed"?a.findByFiles(d):[],f=new Map;for(let b of h){let w=f.get(b.file_path)||[];w.push(b),f.set(b.file_path,w)}let _=new Map;for(let b of m){let w=_.get(b.file_path)||[];w.push(b),_.set(b.file_path,w)}let g=c.map(b=>{let x=(f.get(b.path)||[]).map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.start_line}));t==="structure"?x=x.map(k=>({name:k.name,kind:k.kind,line:k.line})):t==="signatures"&&(x=x.map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.line})));let R=[];return t==="detailed"&&(R=(_.get(b.path)||[]).map(D=>({module:D.module_specifier,resolved_path:D.resolved_path}))),{path:b.path,mtime:b.mtime,classification:b.classification||void 0,summary:b.summary||void 0,exports:x,imports:R.length>0?R:void 0,chunks:[]}});return S.info({count:g.length},"Building hierarchical project tree..."),Yn(g,s,t,i)}async function aa(s,e){let t=Up.resolve(s);try{await Y(async()=>{pe("\u{1F311} Liquid Shadow: Topological Mapping");let n=parseInt(e.depth,10),i=await bi(t,n,"detailed",e.subPath);console.log(` ${y.bold("Root")}: ${y.cyan(t)}`),e.subPath&&console.log(` ${y.bold("Subpath")}: ${y.yellow(e.subPath)}`),console.log("");let r=o=>({name:o.name,info:o.type==="directory"?`${o.children?.length||0} items`:o.size,color:o.type==="directory"?"blue":"white",children:o.children?.map(r)});ss([r(i)]),console.log(""),Pe("Mapping concluded.")})}finally{await Q(t)}}import la from"path";import jp from"fs";q();import ce from"path";import Ts from"fs";var _i=S.child({module:"path-resolver"}),hn=class{repoPath;constructor(e){this.repoPath=ce.isAbsolute(e)?ce.normalize(e):ce.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw _i.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(ce.isAbsolute(e)?t=ce.normalize(e):t=ce.join(this.repoPath,e),t=ce.normalize(t),!this.isWithinRoot(t))throw _i.warn({inputPath:e,resolved:t},"Path traversal attempt blocked"),new Error(`Access denied: path '${e}' is outside the repository root`);return t}resolveAndValidate(e){try{let t=this.resolve(e);return Ts.existsSync(t)?t:(_i.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return _i.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=ce.resolve(e),n=ce.resolve(this.repoPath),i=ce.relative(n,t);if(i.startsWith("..")||ce.isAbsolute(i))return!1;if(Ts.existsSync(t)){let o=Ts.realpathSync(t),a=ce.relative(n,o);if(a.startsWith("..")||ce.isAbsolute(a))return!1}return!0}catch{return!1}}getRelative(e){let t=ce.normalize(e);return ce.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return ce.normalize(e)}static isPathWithinRoot(e,t){let n=ce.resolve(e),i=ce.resolve(t),r=ce.relative(n,i);return r===""||!r.startsWith("..")&&!ce.isAbsolute(r)}};function ca(s){return new hn(s)}async function pa(s,e){let t=la.resolve(s);await Y(async()=>{if(pe("\u{1F311} Liquid Shadow: Intelligence Deployment"),console.log(` ${y.bold("Target")}: ${y.cyan(t)}`),console.log(` ${y.bold("Objective")}: ${e.output?y.magenta("Data Extraction"):y.green("Semantic Mapping")}`),console.log(""),!e.output){let i=Re();i.start("Engaging intelligence engines...");let r="",o=a=>{if(a.phase!==r){r=a.phase;let c={scan:"\u{1F4E1} Scanning topography",parse:"\u{1F9E9} Parsing symbols",embed:"\u{1F9E0} Generating vectors",persist:"\u{1F4BE} Hardening index",complete:"\u{1F3C1} Mapping complete"}[a.phase]||a.phase;i.message(`${c}...`)}if(a.total>0&&a.current>0){let c=Math.round(a.current/a.total*100);i.message(`${r==="parse"?"Parsing":"Processing"}: ${a.current}/${a.total} (${c}%)`)}};try{await X(t,void 0,e.force,e.deep??!0,o),i.message("\u{1FA79} Running Nano-Repair healing...");let c=new qe(t).detectAndRepairShifts();i.stop("Intelligence mapping successfully concluded."),console.log(""),console.log(` ${y.bold("Next Steps:")}`),console.log(` ${y.dim("view your repo stats")} -> ${y.bold(y.cyan("liquid-shadow dashboard"))}`),console.log(` ${y.dim("start a chat search")} -> ${y.bold(y.cyan('liquid-shadow search-concept "your query"'))}`),console.log(""),Pe("Liquid Shadow is online.")}catch(a){throw i.stop(`Operation failed: ${a.message}`),a}finally{await Q(t)}return}let n=Re();n.start("Engaging intelligence engines...");try{let i=await bi(t,5,e.level,e.subPath),r=la.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!hn.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");jp.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Data extraction saved: ${y.bold(y.cyan(r))}`),Pe("Extraction complete.")}catch(i){throw n.stop(`Extraction failed: ${i.message}`),i}finally{await Q(t)}})}import{performance as ua}from"perf_hooks";import Bp from"path";V();async function da(s){let e=Bp.resolve(s);await Y(async()=>{console.log(`
|
|
658
|
-
${
|
|
659
|
-
`);let t=
|
|
660
|
-
${
|
|
661
|
-
${
|
|
662
|
-
${
|
|
703
|
+
`).length,h=fp(a,d-1);i.push({name:u.name||"anonymous",kind:u.kind||"Unknown",classification:u.classification||"Other",signature:u.signature||p[0],line:d,endLine:h,doc:"",capabilities:JSON.stringify(u.meta||{})})}}let c=Sn({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:i.map(l=>({name:l.name,kind:l.kind,classification:l.classification})),fileName:ks.basename(e)});return{exports:i,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:c||"Module",parseStatus:i.length>0?"success":"partial"}}};G();import*as Cs from"@swc/core";function Po(s){if(!s||typeof s!="object")return!1;let e=s;return typeof e.parse=="function"&&typeof e.parseSync=="function"}function yp(){if(Po(Cs))return Cs;let s=Cs;if(Po(s.default))return s.default;throw new Error("SWC runtime unavailable: couldn't resolve parse/parseSync from @swc/core exports")}var No=yp();function Is(s,e,t){return No.parse(s,e,t)}function yi(s,e,t){return No.parseSync(s,e,t)}var Ls=new gi;async function wn(s){let e=Oo.extname(s);if(Ls.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=await Do.promises.readFile(s,"utf-8");return{...await Ls.parse(s,r),content:r}}catch(r){return w.error({filePath:s,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:r.message}}let t;try{t=await Do.promises.readFile(s)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),i=So(n);try{let r=s.endsWith(".tsx"),o=s.endsWith(".d.ts")||s.endsWith(".d.tsx"),a,c={syntax:"typescript",tsx:r,decorators:!0,comments:!0};if(o)try{a=yi(n,c)}catch{a=yi(n,{...c,isModule:!1})}else a=yi(n,c);let l=a.span.start,p=wo(t),u=vo(n),d=T=>xo(T,l,t),h=To(a.body),m=Io(a.body);m.length>0&&w.debug({filePath:s,count:m.length},"Extracted type references"),m.forEach(T=>{h.push({module:"__type_reference__",name:T})});let f=ko(a.body,l,t,n,i,u,s,d,p),S=Co(a.body,l,t,i,d,p),y=di(s,"","Module"),E=u.length>0&&n.slice(0,u[0].start).trim().length===0?u[0].text:f.find(T=>T.doc)?.doc||"",R=Ro(E);if(!R&&f.length>0){let T=En(n);R=Sn({classification:y,capabilities:T,exports:f.map(k=>({name:k.name,kind:k.kind,classification:k.classification})),fileName:Oo.basename(s)})}return{exports:f,imports:h,events:S,classification:y,summary:R,content:n,parseStatus:"success"}}catch(r){w.warn({filePath:s,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=await Ls.parse(s,n);return{...o,content:n,classification:o.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return w.error({filePath:s,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}G();import Ws from"p-limit";ut();import zs from"path";import iu from"fs";import su from"os";import Ye from"path";import en from"fs";import{loadConfig as Ep,createMatchPath as Sp}from"tsconfig-paths";import xt from"path";import xn from"fs";var vt=class extends Error{constructor(t,n,i){super(n);this.code=t;this.cause=i;this.name="FileSystemError"}};function Fo(s){let e;try{e=xn.statSync(s).isDirectory()?s:xt.dirname(s)}catch(t){throw t.code==="ENOENT"?new vt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new vt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new vt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==xt.dirname(e);){let t=xt.join(e,"tsconfig.json");if(xn.existsSync(t))return e;e=xt.dirname(e)}return null}function Wo(s){let e;try{e=xn.statSync(s).isDirectory()?s:xt.dirname(s)}catch(t){throw t.code==="ENOENT"?new vt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new vt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new vt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==xt.dirname(e);){let t=xt.join(e,"package.json");if(xn.existsSync(t))try{if(JSON.parse(xn.readFileSync(t,"utf8")).workspaces)return e}catch{}e=xt.dirname(e)}return null}import Xt from"path";import Ft from"fs";function zo(s,e){let t=new Map,n=e.workspaces||[];for(let i of n){let r=i.replace("/*",""),o=Xt.join(s,r);if(!Ft.existsSync(o))continue;let a=Ft.readdirSync(o);for(let c of a){let l=Xt.join(o,c,"package.json");if(Ft.existsSync(l))try{let p=JSON.parse(Ft.readFileSync(l,"utf8"));p.name&&t.set(p.name,{name:p.name,path:Xt.dirname(l),main:p.main||"dist/index.js"})}catch{}}}return t}function Ho(s){let e=new Map;try{let t=JSON.parse(Ft.readFileSync(s,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[i,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),a=Xt.dirname(s),c=Xt.resolve(a,o),l=Xt.join(c,"package.json");if(Ft.existsSync(l))try{let p=JSON.parse(Ft.readFileSync(l,"utf8"));e.set(i,{name:i,path:c,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import Bo from"path";import Je from"fs";var bp=[".ts",".tsx",".d.ts",".js",".jsx"];function Rt(s){let e=Bo.extname(s);if(e===".js"||e===".jsx"){let t=s.slice(0,-e.length),n=e===".jsx"?[".tsx",".ts"]:[".ts",".tsx"];for(let i of n){let r=t+i;if(Je.existsSync(r)&&Je.statSync(r).isFile())return r}if(Je.existsSync(s)&&Je.statSync(s).isFile())return s}if(Je.existsSync(s)&&Je.statSync(s).isFile())return s;for(let t of bp){let n=s+t;if(Je.existsSync(n)&&Je.statSync(n).isFile())return n}if(Je.existsSync(s)&&Je.statSync(s).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=Bo.join(s,"index"+t);if(Je.existsSync(n))return n}return""}import{builtinModules as _p,createRequire as kg}from"node:module";var Lg=new Set(_p.map(s=>s.replace(/^node:/,"")));var _i=new Map;function bi(s){let e=Fo(s);if(!e)return null;if(_i.has(e))return _i.get(e)||null;let t=Ep(e);if(t.resultType==="failed")return _i.set(e,null),null;let n=t,i=n.absoluteBaseUrl;!i&&n.paths&&Object.keys(n.paths).length>0&&(i=n.configFileAbsolutePath?Ye.dirname(n.configFileAbsolutePath):e);let r=Sp(i,n.paths,n.mainFields,n.addMatchAll),o=Wo(e),a=new Map;if(o){let u=Ye.join(o,"package.json");if(en.existsSync(u))try{let d=JSON.parse(en.readFileSync(u,"utf8"));a=zo(o,d)}catch{}}let c=Ye.join(e,"package.json");en.existsSync(c)&&Ho(c).forEach((d,h)=>a.set(h,d));let l={baseUrl:i||"",paths:n.paths,matchPath:r,workspacePackages:a,imports:new Map},p=Ye.join(e,"package.json");if(en.existsSync(p))try{let u=JSON.parse(en.readFileSync(p,"utf8"));if(u.imports){for(let[d,h]of Object.entries(u.imports))if(typeof h=="string"||typeof h=="object"&&h!==null){let m=h;Array.isArray(h)&&(m=h[0]),typeof m=="object"&&(m=m.default||m.node),typeof m=="string"&&l.imports.set(d,m)}}}catch{}return _i.set(e,l),l}function Wt(s,e,t){if(!s)return"";if(s.includes(".")&&!s.startsWith(".")&&!s.startsWith("/")&&!s.endsWith(".js")&&!s.endsWith(".ts")&&!s.endsWith(".json")){let i=s.split(".")[0];if(i&&i!==s){let r=Wt(i,e,t);if(r)return r}}if(s.startsWith(".")){let i=Ye.dirname(e),r=Ye.resolve(i,s);return Rt(r)}let n=bi(e);if(n){let i=n.matchPath(s);if(i)return Rt(i);if(!s.startsWith("@")||s.startsWith("@/")){let o=Ye.resolve(n.baseUrl,s),a=Rt(o);if(a)return a}for(let[o,a]of n.imports.entries())if(o.includes("*")){let c="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",l=new RegExp(c),p=s.match(l);if(p){let u=p[1],d=a.replace("*",u),h=Ye.resolve(n.baseUrl,d);return Rt(h)}}else if(o===s){let c=Ye.resolve(n.baseUrl,a);return Rt(c)}let r=n.workspacePackages.get(s);if(r){let o=Ye.join(r.path,"src/index.ts");if(en.existsSync(o))return o;let a=Ye.join(r.path,r.main),c=Rt(a);if(c)return c}}return""}import wp from"fs";import xp from"path";import jo from"js-yaml";function Uo(s){let e=xp.basename(s),t=wp.readFileSync(s,"utf8"),n=[];if(e.endsWith(".prisma"))return{...kp(t,s),content:t};if(e.endsWith(".graphql")||e.endsWith(".gql"))return{...Cp(t,s),content:t};let i="Configuration";return e==="lerna.json"?{...Lp(t,s),content:t}:e==="turbo.json"?{...Mp(t,s),content:t}:e==="pnpm-workspace.yaml"?{...Ap(t,s),content:t}:(e.includes("Dockerfile")?(i="Infrastructure (Docker) ",vp(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(i="Infrastructure (YAML) ",Rp(t,n)):e.startsWith(".env")?(i="Configuration (Env) ",Tp(t,n)):e==="package.json"&&(i="Project Manifest",Ip(t,n)),{configs:n,classification:i,content:t})}function vp(s,e){let t=s.split(`
|
|
704
|
+
`);for(let n of t){let i=n.trim();if(i.startsWith("FROM "))e.push({key:"base_image",value:i.substring(5).trim(),kind:"Image"});else if(i.startsWith("EXPOSE "))e.push({key:"port",value:i.substring(7).trim(),kind:"Port"});else if(i.startsWith("ENV ")){let r=i.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],a=r.slice(1).join("= ").trim()||"undefined",c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:a,kind:c})}}}}function Rp(s,e){try{let t=jo.load(s);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[i,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${i}`,value:i,kind:"Service"}),o.image&&e.push({key:`service:${i}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(a=>{e.push({key:`service:${i}:port`,value:String(a),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(a=>{let[c,...l]=a.split("= ");c&&l.length>0&&e.push({key:`service:${i}:env:${c}`,value:l.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[a,c]of Object.entries(o.environment))e.push({key:`service:${i}:env:${a}`,value:String(c),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(a=>{e.push({key:`service:${i}:depends_on`,value:a,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let a of Object.keys(o.depends_on))e.push({key:`service:${i}:depends_on`,value:a,kind:"Dependency"})}let n=(i,r="")=>{if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,a]of Object.entries(i)){let c=r?`${r}.${o}`:o;if(t.services&&(c.startsWith("services.")||c==="services")){a&&typeof a=="object"&&!Array.isArray(a)&&n(a,c);continue}if(a&&typeof a=="object"&&!Array.isArray(a))n(a,c);else if(a!=null){let l=String(a);if(l==="[object Object]"||l.includes("[object Object]"))continue;let p="Env",u=/^[a-z0-9_-]+$/i.test(l),d=l.includes("://");o.toLowerCase().includes("service")&&(u||d)&&(p="Service"),o.toLowerCase().includes("image")&&(p="Image"),o.toLowerCase().includes("port")&&(p="Port"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&d&&(p="Service"),e.push({key:c,value:l.length>200?l.substring(0,197)+"...":l,kind:p})}}};n(t)}catch{let n=s.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(i=>{let r=i.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function Tp(s,e){let t=s.split(`
|
|
705
|
+
`);for(let n of t){let i=n.trim();if(i&&!i.startsWith("#")){let r=i.split("=");if(r[0]){let o=r[0].trim(),a=r.slice(1).join("=");a=a.trim().replace(/^['"](.*)['"]$/,"$1");let c="Env",l=a.includes("://");(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&l&&(c="Service"),e.push({key:o,value:a,kind:c})}}}}function kp(s,e){let t=[],n="Contract (Prisma) ",i=/^model\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(s))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let a=/provider\s*=\s*"([^"]+)"/,c=s.match(a);return c&&t.push({key:"datasource_provider",value:c[1],kind:"Database Config"}),{classification:n,configs:t,content:s}}function Cp(s,e){let t=[],n="Contract (GraphQL) ",i=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;){let o=r[0],a="GraphQL Type";o.startsWith("input")&&(a="GraphQL Input"),o.startsWith("interface")&&(a="GraphQL Interface"),o.startsWith("enum")&&(a="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:a})}return{classification:n,configs:t,content:s}}function Ip(s,e){try{let t=JSON.parse(s);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"Env"}),t.workspaces){let r=Array.isArray(t.workspaces)?t.workspaces.join("",""):JSON.stringify(t.workspaces);e.push({key:"workspaces",value:r,kind:"Env"})}if(t.scripts){let r=["start","dev","build","test","docker"];for(let o of Object.keys(t.scripts))r.some(a=>o.includes(a))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},i=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(i.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Dependency"})}}catch{}}function Lp(s,e){let t=[],n="Monorepo (Lerna) ";try{let i=JSON.parse(s);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),i.version&&t.push({key:"lerna_version",value:i.version,kind:"Monorepo"}),i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),i.npmClient&&t.push({key:"npm_client",value:i.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:s}}function Mp(s,e){let t=[],n="Monorepo (Turborepo) ";try{let i=JSON.parse(s);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),i.pipeline)for(let r of Object.keys(i.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=i.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(i.tasks)for(let r of Object.keys(i.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:s}}function Ap(s,e){let t=[],n="Monorepo (pnpm) ";try{let i=jo.load(s);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),i&&i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n,content:s}}Y();qe();import{execSync as zt}from"child_process";import vn from"path";import Ms from"fs";function be(s){try{if(!Ms.existsSync(vn.join(s,".git")))return null;let e=zt("git rev-parse --abbrev-ref HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return e==="HEAD"?zt("git rev-parse --short HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():e.replace(/[\/\\:*"<>|?]/g,"-")}catch{return null}}function Ke(s){try{return Ms.existsSync(vn.join(s,".git"))?zt("git rev-parse HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function qo(s,e=50){try{let t=zt(`git rev-list --max-count=${e} HEAD`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return t?t.split(`
|
|
706
|
+
`):[]}catch{return[]}}function Vo(s,e,t){try{return zt(`git merge-tree --write-tree ${e} ${t}`,{cwd:s,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}var $p=new Set([".ts",".tsx",".yaml",".yml",".php",".py",".go",".prisma",".graphql",".gql"]),Pp=new Set(["package.json","lerna.json","turbo.json","pnpm-workspace.yaml"]),Np=new Set(["node_modules",".git","dist","build","vendor",".next",".cache","coverage"]);function Go(s){let e=s.split("/");for(let i of e)if(Np.has(i))return!1;if(s.endsWith(".min.js"))return!1;let t=vn.basename(s);if(t.startsWith("Dockerfile")||t.startsWith(".env")||Pp.has(t))return!0;let n=vn.extname(t).toLowerCase();return $p.has(n)}function Dp(s){let e=s.trim(),t=e.indexOf(" -> ");if(t!==-1)return e.substring(t+4);let n=e.split(/\s+/);return n.length>=2?n[n.length-1]:e}function Jo(s,e){try{if(!Ms.existsSync(vn.join(s,".git")))return!0;let t=Ke(s);if(!t)return!0;if(e&&e!==t){let i=zt(`git diff --name-only ${e} ${t}`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(i&&i.split(`
|
|
707
|
+
`).some(r=>r&&Go(r)))return!0}let n=zt("git status --porcelain",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return n?n.split(`
|
|
708
|
+
`).some(i=>i?Go(Dp(i)):!1):!1}catch{return!0}}Y();G();import{execSync as Yo}from"child_process";var Ht=w.child({module:"nano-repair"}),it=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:i}=N.getInstance(e);this.intentLogs=t,this.exports=n,this.missions=i,this.repoPath=e}detectAndRepairShifts(){let e=this.intentLogs.findRepairableOrphans();if(e.length===0)return{repaired:0,failed:0};Ht.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let i of e){let r=this.exports.findByNameAndFile(i.symbol_name,i.file_path);if(r.length>0){let a=r.find(c=>c.signature===i.signature)||r[0];this.intentLogs.update(i.id,{symbol_id:a.id}),Ht.info({logId:i.id,symbol:i.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(i.symbol_name);if(o.length>0){let a=o.filter(c=>c.file_path!==i.file_path);if(a.length>0){let c=a.find(l=>l.signature===i.signature)||a[0];this.intentLogs.update(i.id,{symbol_id:c.id,file_path:c.file_path}),Ht.info({logId:i.id,symbol:i.symbol_name,oldPath:i.file_path,newPath:c.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&Ht.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(e={}){let t=e.enableContextPivot===!0,n=e.enableMergeSentinel===!0,i="HEAD";try{i=Yo("git rev-parse --abbrev-ref HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return{suspended:0,resumed:0,completed:0,contextPivotEnabled:t,mergeSentinelEnabled:n}}if(!i)return{suspended:0,resumed:0,completed:0,contextPivotEnabled:t,mergeSentinelEnabled:n};let r=0,o=0;if(t){let c=this.missions.findActive();for(let l of c)l.git_branch&&l.git_branch!==i&&(this.missions.updateStatus(l.id,"suspended"),Ht.info({missionId:l.id,branch:l.git_branch,current:i},"Context Pivot: Suspended mission"),r++);o=this.missions.resumeByBranch(i)}let a=0;if(n){let c=[];try{c=Yo(`git branch --merged "${i}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
709
|
+
`).map(p=>p.trim().replace(/^\* /,"")).filter(p=>p&&p!==i)}catch{}if(c.length>0){let l=this.missions.findMergedMissions(i,c);for(let p of l)this.missions.updateStatus(p.id,"completed"),Ht.info({missionId:p.id,branch:p.git_branch},"Merge Sentinel: Auto-completed mission"),a++}}return(r>0||o>0||a>0)&&Ht.info({suspended:r,resumed:o,completed:a},"Git-Native Lifecycle Sync complete"),{suspended:r,resumed:o,completed:a,contextPivotEnabled:t,mergeSentinelEnabled:n}}};G();Nt();import{Worker as Op}from"node:worker_threads";import{cpus as Fp}from"node:os";import{fileURLToPath as Wp}from"node:url";import{dirname as zp,join as Hp}from"node:path";import{existsSync as Bp}from"node:fs";var Ko=Wp(import.meta.url),Up=zp(Ko),jp=Ko.endsWith(".ts");function Gp(){if(jp)return null;let s=Hp(Up,"worker.js");return Bp(s)?s:Le("dist/logic/parser/worker.js")}var As=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(4,Fp().length-1)),this.initTimeout=e.initTimeout??3e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{w.info({numWorkers:this.numWorkers},"Initializing parser worker pool");let t=new Promise((n,i)=>{e=setTimeout(()=>i(new Error(`Parser pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0;return}this.initialized=!0,w.info({numWorkers:this.workers.length},"Parser worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=Gp();if(!e)throw new Error("Parser worker pool not available in development mode (tsx). Use main-thread fallback.");w.debug({workerPath:e},"Resolved parser worker path");let t=[];for(let n=0;n<this.numWorkers;n++)t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Parser worker ${t} initialization timed out`))},this.initTimeout),o=new Op(e,{execArgv:process.execArgv}),a={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){o.terminate().catch(()=>{}),n();return}this.workers.push(a),w.debug({workerIndex:t},"Parser worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(a,c.id,c.result):c.type==="error"&&c.id&&this.handleTaskError(a,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),w.error({err:c,workerIndex:t},"Parser worker error"),a.currentTaskId&&this.handleTaskError(a,a.currentTaskId,c),!this.initialized){i(c);return}let l=this.workers.indexOf(a);l!==-1&&this.workers.splice(l,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{w.error({err:p},"Failed to replace crashed parser worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&w.warn({workerIndex:t,code:c},"Parser worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"parse",id:t.id,filePath:t.filePath}))}async parseFile(e){return this.initialized||await this.initialize(),new Promise((t,n)=>{let r={id:`parse_${++this.taskIdCounter}`,filePath:e,resolve:t,reject:n};this.taskQueue.push(r),this.processQueue()})}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}w.info({numWorkers:this.workers.length},"Shutting down parser worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,this.initPromise=void 0,w.info("Parser worker pool shutdown complete")}},tn=null;function Qo(s){return tn||(tn=new As(s)),tn}async function Zo(){tn&&(await tn.shutdown(),tn=null)}Y();G();Ut();$s();Ps();Ns();import{execSync as Ea}from"child_process";var Ci=w.child({module:"heritage-analyzer"}),Ii=class{repos;repoPath;constructor(e){this.repos=N.getInstance(e),this.repoPath=e}analyzeHeritage(e=20){try{Ci.info({limit:e},"Analyzing repository heritage...");let t=Ea(`git log -n ${e} --pretty=format:"%H|%at|%an|%s"`,{cwd:this.repoPath,encoding:"utf-8"});if(!t)return;let n=t.split(`
|
|
710
|
+
`).filter(Boolean);for(let i of n){let[r,o,a,c]=i.split("|"),l=this.analyzeCommitImpact(r);if(l.significant){let p=Array.from(l.layers).join(", "),u=`Heritage: ${c} (by ${a}). Touched ${l.fileCount} files across [${p}].`;this.repos.intentLogs.importHeritage(u,r,parseInt(o,10),.7),Ci.debug({sha:r,subject:c},"Logged heritage move")}}Ci.info("Heritage analysis complete.")}catch(t){Ci.warn({err:t.message},"Failed to run heritage analysis")}}analyzeCommitImpact(e){let t=new Set,n=0;try{let r=Ea(`git diff-tree --no-commit-id --name-only -r ${e}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
|
|
711
|
+
`).filter(Boolean);n=r.length;for(let c of r){let l=this.classifyPathOnly(c);l!=="Unknown"&&t.add(l)}let o=t.has("Entry")||t.has("Data")||t.has("Infrastructure"),a=t.size>=2||n>5;return{significant:o||a,layers:t,fileCount:n}}catch{return{significant:!1,layers:t,fileCount:0}}}classifyPathOnly(e){let t=e.startsWith("/")?e:"/"+e;return Ds.some(n=>n.test(t))?"Test":Si.some(n=>n.test(t))||Ei.some(n=>n.test(t))?"Entry":Rn.some(n=>n.test(t))?"Data":xi.some(n=>n.test(t))?"Utility":vi.some(n=>n.test(t))?"Entry":Ri.some(n=>n.test(t))?"Data":Ti.some(n=>n.test(t))?"Entry":ki.some(n=>n.test(t))?"Data":Os.some(n=>n.test(t))?"Infrastructure":/\.(service|logic|usecase|interactor|manager)\.(ts|js|php|py)$/i.test(t)||wi.some(n=>n.test(t))?"Logic":"Unknown"}};ut();Nt();import{spawn as Yp}from"node:child_process";import Fs from"node:os";import{resolve as Kp}from"node:path";import{existsSync as Sa}from"node:fs";import{fileURLToPath as Qp}from"node:url";import{dirname as Zp}from"node:path";var wa=Qp(import.meta.url),Xp=Zp(wa),eu=Fs.constants.priority.PRIORITY_LOWEST??Fs.constants.priority.PRIORITY_LOW;function tu(){if(wa.endsWith(".ts"))return null;let s=Kp(Xp,"../../entry/ember/index.js");if(Sa(s))return s;let e=Le("dist/entry/ember/index.js");return Sa(e)?e:null}function xa(s){try{let t=De(s).prepare("SELECT key, value FROM ember_state WHERE key IN ('status','progress','pid')").all(),n=new Map(t.map(i=>[i.key,i.value??""]));return{status:n.get("status")??"idle",progress:n.get("progress")??"0/0",pid:n.get("pid")??null}}catch{return{status:"idle",progress:"0/0",pid:null}}}function nu(s,e){let t=De(s);t.transaction(()=>{let n=t.prepare("INSERT OR REPLACE INTO ember_state (key, value, updated_at) VALUES (?, ?, unixepoch())");n.run("pid",String(e)),n.run("status","running"),n.run("repo_path",s)})()}function va(s){let{pid:e}=xa(s);if(!e)return!1;let t=parseInt(e,10);if(!Number.isFinite(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function Ra(s){let e=tu();if(!e)return;let t=Yp(process.execPath,[e,s],{detached:!0,stdio:"ignore",env:{...process.env,EMBER_MODE:"1"}});if(t.pid!=null){try{Fs.setPriority(t.pid,eu)}catch{}t.unref(),nu(s,t.pid)}}function Li(s){let{status:e,progress:t}=xa(s);return{status:e,progress:t}}var ru=su.cpus().length||4,ou=pi.DEFAULT_CONCURRENCY;function Ca(s,e=[]){if(!Array.isArray(s))return e;for(let t of s)!t||typeof t!="object"||(e.push(t),Array.isArray(t.members)&&t.members.length>0&&Ca(t.members,e));return e}function Ta(s){if(typeof s!="number"||!Number.isFinite(s))return null;let e=Math.trunc(s);return e>0?e:null}function Ia(s){let e=typeof s?.content=="string"&&s.content.length>0?s.content.split(`
|
|
712
|
+
`).length:0,t=Ca(s?.exports),n=0,i=0,r=0,o=0;for(let a of t){let c=Ta(a?.line??a?.start_line),l=Ta(a?.endLine??a?.end_line??c);if(!c||!l||l<c||e>0&&l>e){i++;continue}n++,l>c&&o++,e>0&&c===e&&l===e&&r++}return{total:t.length,valid:n,invalid:i,eofCollapsed:r,multiLine:o,lineCount:e}}function au(s){let e=Ia(s);if(e.total===0||e.lineCount===0)return!1;if(e.invalid>0)return!0;let t=e.eofCollapsed/e.total;return e.eofCollapsed>=3&&t>=.5||e.total>=2&&e.eofCollapsed===e.total}function ka(s){let e=Ia(s);return e.valid*2+e.multiLine*2-e.eofCollapsed*3-e.invalid*4}async function ie(s,e=ou,t=!1,n=!0,i){let r=N.getInstance(s),o=r.files.database,a=ct(s),c=a.concurrency??e;if(co(),!t&&pt(s)){let y=fn(s),_=Ke(s);if(y&&!Jo(s,y))return ws(),w.debug({repoPath:s,commit:_},"Index is current, skipping re-index (fast-path)"),o}bi(s);let l=r.files.findAll(),p=new Map(l.map(y=>[y.path,{mtime:y.mtime,hash:y.content_hash}])),u=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let d=await Eo(s,a.ignore),h=new Map(d.map(y=>[y.path,y.mtime])),m=l.filter(y=>!h.has(y.path)).map(y=>y.path),f=l.length===0,S=[];if(t||f)S.push(...d);else{let y=d.filter(T=>{let k=p.get(T.path);return!k||k.mtime!==T.mtime}),_=Ws(c*4),E=y.map(T=>_(async()=>{let k=p.get(T.path);if(!k||!k.hash)return T;try{let F=await iu.promises.readFile(T.path,"utf8");return Cr(F,k.hash)?T:(r.files.updateMtime(T.path,T.mtime),null)}catch{return null}})),R=await Promise.all(E);S.push(...R.filter(T=>T!==null))}if(m.length===0&&S.length===0){ws();let y=Ke(s);return us(s,y||void 0),o}if(f?w.info({totalFiles:d.length},"Starting initial repository indexing..."):w.info({toDelete:m.length,toProcess:S.length},"Syncing repository updates..."),m.length>0&&r.files.deletePaths(m),S.length>0){po(),n?(Gn(!0),Kt().initialize().catch(()=>{})):Gn(!1);let y=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,_=[],E=[];for(let A of S)y.test(zs.basename(A.path))?_.push(A):E.push(A);let R=0,T=S.length,k=!1,F=Qo();try{await F.initialize(),k=!0,w.info({workers:F.workerCount},"Parser worker pool active")}catch(A){w.warn({err:A},"Parser worker pool failed to initialize, falling back to main-thread parsing"),k=!1}let B=async(A,H)=>{let L=H;if(k&&au(H))try{let z=await wn(A.path);ka(z)>ka(H)&&(w.warn({filePath:A.path},"Detected suspicious worker parse ranges; using main-thread parse output"),L=z)}catch(z){w.warn({filePath:A.path,err:z instanceof Error?z.message:String(z)},"Main-thread parse retry failed after suspicious worker parse")}let D=L.imports?.map(z=>({...z,resolved_path:Wt(z.module,A.path,s)})),J=L.content?Jt(L.content):null;return R++,(R%50===0||R===T)&&w.info({completed:R,total:T},"Parsing files..."),i?.({phase:"parse",current:R,total:T,message:`Parsing ${zs.basename(A.path)}`}),{meta:A,...L,imports:D,embedding:null,kind:"code",contentHash:J}},M;if(k)M=_.map(A=>F.parseFile(A.path).then(H=>B(A,H),H=>(R++,w.error({path:A.path,error:H},"Worker parse failed"),{meta:A,exports:[],imports:[],content:"",kind:"error"})));else{let A=f?Math.max(c,Math.min(ru-1,16)):c,H=Ws(A);M=_.map(L=>H(async()=>{try{let D=await wn(L.path);return B(L,D)}catch(D){return R++,w.error({path:L.path,error:D},"Failed to parse file"),{meta:L,exports:[],imports:[],content:"",kind:"error"}}}))}let v=Ws(c),I=E.map(A=>v(async()=>{try{let H=Uo(A.path),L=H.content?Jt(H.content):null;return R++,(R%50===0||R===T)&&w.info({completed:R,total:T},"Parsing configs..."),i?.({phase:"parse",current:R,total:T,message:`Parsing config ${zs.basename(A.path)}`}),{meta:A,...H,embedding:null,kind:"config",contentHash:L}}catch(H){return R++,w.error({path:A.path,error:H},"Failed to parse config"),{meta:A,exports:[],imports:[],content:"",kind:"error"}}}));w.info({total:T,codeFiles:_.length,configFiles:E.length,useParserPool:k},"Phase 1: Parsing all files...");let $=Date.now(),P=(await Promise.all([...M,...I])).filter(Boolean),U=Date.now()-$;if(_n("parse",U),w.info({count:P.length,time:`${(U/1e3).toFixed(1)}s`},"Phase 1 complete"),k&&Zo().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let A=[];P.forEach((x,O)=>{"summary"in x&&x.summary&&A.push({fileIdx:O,text:x.summary})}),w.info("Phase 2+3: Generating file-summary embeddings + persisting in parallel..."),i?.({phase:"embed",current:0,total:P.length,message:"Generating embeddings..."});let H=Date.now(),L=(async()=>{let x=[];return A.length>0&&(w.info({count:A.length}," \u2192 Generating file summary embeddings..."),x=await bs(A.map(O=>O.text),256),w.info({count:A.length}," \u2713 File summaries complete")),x})();i?.({phase:"persist",current:0,total:P.length,message:"Saving to database..."});let D=Date.now();r.files.batchSaveIndexResults(P,s,Jt,Wt);let J=Date.now()-D;_n("persist",J),w.info({time:`${(J/1e3).toFixed(1)}s`},"Structural persist complete");let z=await L,g=Date.now()-H;if(_n("embed",g),w.info({time:`${(g/1e3).toFixed(1)}s`},"File-summary embeddings complete"),z.length>0){let x=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),O=o.transaction(W=>{for(let j of W)x.run(j.embedding?JSON.stringify(j.embedding):null,j.path)}),C=A.map((W,j)=>({path:P[W.fileIdx].meta.path,embedding:z[j]}));O(C),w.info({count:C.length},"File embedding column updated")}}else{i?.({phase:"persist",current:0,total:P.length,message:"Saving to database..."});let A=Date.now();r.files.batchSaveIndexResults(P,s,Jt,Wt),_n("persist",Date.now()-A)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(f||S.length>0){let y=Ke(s);us(s,y||void 0)}if(n&&!va(s)&&Ra(s),(S.length>0||m.length>0)&&new it(s).detectAndRepairShifts(),f||n)try{new Ii(s).analyzeHeritage(50)}catch(y){w.warn({err:y.message},"Heritage sync deferred")}return lo(Date.now()-u),i?.({phase:"complete",current:S.length,total:S.length,message:"Indexing complete"}),o}Y();async function Mi(s,e=pi.DEFAULT_CONCURRENCY,t="detailed",n,i){w.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await ie(s,e);let{files:r,exports:o,imports:a}=N.getInstance(s),c=n?r.findInSubPath(s,n):r.findAll(),l=ct(s),p=cu(),u=La.join(s,".gitignore");if(Ma.existsSync(u)&&p.add(Ma.readFileSync(u,"utf8")),l.ignore&&l.ignore.length>0&&p.add(l.ignore),p.add(li),c=c.filter(_=>{let E=La.relative(s,_.path);return!p.ignores(E)}),w.info({count:c.length},"Fetching data from DB..."),t==="lite"){let _=c.map(E=>({path:E.path,mtime:E.mtime}));return ci(_,s,t,i)}if(t==="summaries"){let _=c.map(E=>({path:E.path,mtime:E.mtime,classification:E.classification||void 0,summary:E.summary||void 0}));return ci(_,s,t,i)}let d=c.map(_=>_.path),h=o.findByFiles(d),m=t==="detailed"?a.findByFiles(d):[],f=new Map;for(let _ of h){let E=f.get(_.file_path)||[];E.push(_),f.set(_.file_path,E)}let S=new Map;for(let _ of m){let E=S.get(_.file_path)||[];E.push(_),S.set(_.file_path,E)}let y=c.map(_=>{let R=(f.get(_.path)||[]).map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.start_line}));t==="structure"?R=R.map(k=>({name:k.name,kind:k.kind,line:k.line})):t==="signatures"&&(R=R.map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.line})));let T=[];return t==="detailed"&&(T=(S.get(_.path)||[]).map(F=>({module:F.module_specifier,resolved_path:F.resolved_path}))),{path:_.path,mtime:_.mtime,classification:_.classification||void 0,summary:_.summary||void 0,exports:R,imports:T.length>0?T:void 0,chunks:[]}});return w.info({count:y.length},"Building hierarchical project tree..."),ci(y,s,t,i)}async function Aa(s,e){let t=lu.resolve(s);try{await Q(async()=>{ge("\u{1F311} Liquid Shadow: Topological Mapping");let n=parseInt(e.depth,10),i=await Mi(t,n,"detailed",e.subPath);console.log(` ${b.bold("Root")}: ${b.cyan(t)}`),e.subPath&&console.log(` ${b.bold("Subpath")}: ${b.yellow(e.subPath)}`),console.log("");let r=o=>({name:o.name,info:o.type==="directory"?`${o.children?.length||0} items`:o.size,color:o.type==="directory"?"blue":"white",children:o.children?.map(r)});Es([r(i)]),console.log(""),Ve("Mapping concluded.")})}finally{await ne(t)}}import Pa from"path";import pu from"fs";G();import me from"path";import Hs from"fs";var Ai=w.child({module:"path-resolver"}),Tn=class{repoPath;constructor(e){this.repoPath=me.isAbsolute(e)?me.normalize(e):me.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw Ai.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(me.isAbsolute(e)?t=me.normalize(e):t=me.join(this.repoPath,e),t=me.normalize(t),!this.isWithinRoot(t))throw Ai.warn({inputPath:e,resolved:t},"Path traversal attempt blocked"),new Error(`Access denied: path '${e}' is outside the repository root`);return t}resolveAndValidate(e){try{let t=this.resolve(e);return Hs.existsSync(t)?t:(Ai.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return Ai.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=me.resolve(e),n=me.resolve(this.repoPath),i=me.relative(n,t);if(i.startsWith("..")||me.isAbsolute(i))return!1;if(Hs.existsSync(t)){let o=Hs.realpathSync(t),a=me.relative(n,o);if(a.startsWith("..")||me.isAbsolute(a))return!1}return!0}catch{return!1}}getRelative(e){let t=me.normalize(e);return me.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return me.normalize(e)}static isPathWithinRoot(e,t){let n=me.resolve(e),i=me.resolve(t),r=me.relative(n,i);return r===""||!r.startsWith("..")&&!me.isAbsolute(r)}};function $a(s){return new Tn(s)}async function Na(s,e){let t=Pa.resolve(s);await Q(async()=>{if(ge("\u{1F311} Liquid Shadow: Intelligence Deployment"),console.log(` ${b.bold("Target")}: ${b.cyan(t)}`),console.log(` ${b.bold("Objective")}: ${e.output?b.magenta("Data Extraction"):b.green("Semantic Mapping")}`),console.log(""),!e.output){let i=Oe();i.start("Engaging intelligence engines...");let r="",o=a=>{if(a.phase!==r){r=a.phase;let c={scan:"\u{1F4E1} Scanning topography",parse:"\u{1F9E9} Parsing symbols",embed:"\u{1F9E0} Generating vectors",persist:"\u{1F4BE} Hardening index",complete:"\u{1F3C1} Mapping complete"}[a.phase]||a.phase;i.message(`${c}...`)}if(a.total>0&&a.current>0){let c=Math.round(a.current/a.total*100);i.message(`${r==="parse"?"Parsing":"Processing"}: ${a.current}/${a.total} (${c}%)`)}};try{await ie(t,void 0,e.force,e.deep??!0,o),i.message("\u{1FA79} Running Nano-Repair healing...");let c=new it(t).detectAndRepairShifts();i.stop("Intelligence mapping successfully concluded."),console.log(""),console.log(` ${b.bold("Next Steps:")}`),console.log(` ${b.dim("view your repo stats")} -> ${b.bold(b.cyan("liquid-shadow dashboard"))}`),console.log(` ${b.dim("start a chat search")} -> ${b.bold(b.cyan('liquid-shadow search-concept "your query"'))}`),console.log(""),Ve("Liquid Shadow is online.")}catch(a){throw i.stop(`Operation failed: ${a.message}`),a}finally{await ne(t)}return}let n=Oe();n.start("Engaging intelligence engines...");try{let i=await Mi(t,5,e.level,e.subPath),r=Pa.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!Tn.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");pu.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Data extraction saved: ${b.bold(b.cyan(r))}`),Ve("Extraction complete.")}catch(i){throw n.stop(`Extraction failed: ${i.message}`),i}finally{await ne(t)}})}import{performance as Da}from"perf_hooks";import uu from"path";Y();async function Oa(s){let e=uu.resolve(s);await Q(async()=>{console.log(`
|
|
713
|
+
${b.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${b.gray("Repository: ")} ${e}`),console.log(` ${b.yellow("Starting fresh index (DB deleted)...")}
|
|
714
|
+
`);let t=Da.now();try{await ie(e,10,!0);let n=Da.now()-t,i=N.getInstance(e),r=i.files.getCount(),o=i.exports.getCount(),a=i.exports.getWithEmbeddingsCount();ue("Benchmark Results",`${b.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
|
|
715
|
+
${b.bold("Files Processed")}: ${b.cyan(r.toString())}
|
|
716
|
+
${b.bold("Symbols Extracted")}: ${b.cyan(o.toString())}
|
|
717
|
+
${b.bold("Symbols Embedded")}: ${b.cyan(a.toString())} (${(a/o*100).toFixed(1)}%)
|
|
663
718
|
`+"\u2500".repeat(40)+`
|
|
664
|
-
${
|
|
665
|
-
${
|
|
666
|
-
${
|
|
667
|
-
Benchmark failed during execution:`,n),n}finally{await Q(e)}})}import xi from"path";import Ee from"path";import ks from"fs";var Gp=/[\x00-\x1f\x7f]/g,qp=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Rs(s){if(typeof s!="string")throw new Error("Invalid path: expected string");if(s.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(s.replace(Gp,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function Ei(s,e=4096){if(typeof s!="string")return"";let t=s.replace(qp,"").trim();return t.length>e?t.slice(0,e):t}Ze();function Vp(s){let e=Ee.isAbsolute(s)?Ee.normalize(s):Ee.resolve(process.cwd(),s),t=Ee.parse(e).root;for(;e!==t;){if(ks.existsSync(Ee.join(e,".liquid-shadow.db"))||ks.existsSync(Ee.join(e,".git"))||ks.existsSync(Ee.join(e,"package.json")))return e;let n=Ee.dirname(e);if(n===e)break;e=n}return null}function Ve(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=Rs(e)),t&&(t=Rs(t));let n;if(e)Ee.isAbsolute(e)||(e=Ee.resolve(process.cwd(),e)),n=e;else if(t){let o=Ee.resolve(process.cwd(),t);n=Vp(Ee.dirname(o))||process.cwd()}else n=process.cwd();n=Ee.normalize(n);let i=ca(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}V();q();import $t from"fs";import fe from"path";import{Visitor as Jp}from"@swc/core/Visitor.js";var Si=class extends Jp{calls=new Set;apiCalls=[];imports=new Map;axiosInstances=new Map([["axios",""],["http",""],["appApi",""],["restApi",""],["adminApi",""]]);visitImportDeclaration(e){let t=e.source.value;for(let n of e.specifiers)(n.type==="ImportDefaultSpecifier"||n.type==="ImportSpecifier")&&this.imports.set(n.local.value,t);return super.visitImportDeclaration(e)}visitCallExpression(e){if(e.callee.type==="Identifier"){let t=e.callee.value;this.calls.add(t),(t==="axios"||t==="http")&&e.arguments.length>0&&this.extractApiCallFromConfig(e.arguments[0].expression)}else if(e.callee.type==="MemberExpression"){let t=e.callee.property.value,n=r=>{if(!r)return"?";if(r.type==="Identifier")return r.value;if(r.type==="ThisExpression")return"this";if(r.type==="MemberExpression"){let o=n(r.object),a=r.property.value||"?";return`${o}.${a}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},i=n(e.callee.object);if(i!=="?"&&t){if(this.calls.add(`${i}.${t}`),i==="axios"||i==="http"||this.axiosInstances.has(i)){let r=this.axiosInstances.get(i)||"";this.extractApiCall(t,e.arguments,r)}if((i.toLowerCase().includes("pubsub")||i==="pubSubClient"||i.endsWith(".pubSubClient"))&&t!=="subscribe"){let r=t;if((t==="publish"||t==="publishMessage"||t==="publishTaskByNameAndPayload")&&e.arguments.length>0)for(let o of e.arguments){let a=o.expression;if(a.type==="ObjectExpression"){let c=a.properties.find(l=>l.key?.type==="Identifier"&&(l.key.value==="action"||l.key.value==="type")||l.key?.type==="StringLiteral"&&(l.key.value==="action"||l.key.value==="type"));if(c&&c.value?.type==="StringLiteral"){r=c.value.value;break}}if(a.type==="CallExpression"&&a.callee.type==="MemberExpression"&&a.callee.object.value==="JSON"&&a.callee.property.value==="stringify"&&a.arguments.length>0){let c=a.arguments[0].expression;if(c.type==="ObjectExpression"){let l=c.properties.find(p=>p.key?.type==="Identifier"&&(p.key.value==="action"||p.key.value==="type")||p.key?.type==="StringLiteral"&&(p.key.value==="action"||p.key.value==="type"));if(l&&l.value?.type==="StringLiteral"){r=l.value.value;break}}}}this.apiCalls.push({method:"PUBSUB",url:r})}}}return e.callee.type==="Identifier"&&e.callee.value==="fetch"&&this.extractApiCall("GET",e.arguments),super.visitCallExpression(e)}visitNewExpression(e){return e.callee.type==="Identifier"&&this.calls.add(e.callee.value),super.visitNewExpression(e)}visitVariableDeclarator(e){if(e.init&&e.init.type==="CallExpression"){let t=e.init.callee;if(t.type==="MemberExpression"&&t.property.value==="create"&&t.object.value==="axios"){let i=e.init.arguments[0]?.expression;if(i&&i.type==="ObjectExpression"){let r=i.properties.find(o=>o.key.value==="baseURL");if(r){let o="?";r.value.type==="StringLiteral"?o=r.value.value:r.value.type==="Identifier"&&(o=`\${${r.value.value}}`),e.id.type==="Identifier"&&this.axiosInstances.set(e.id.value,o)}}}}return super.visitVariableDeclarator(e)}extractApiCallFromConfig(e){if(e&&e.type==="ObjectExpression"){let t=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="url"||i.key.type==="StringLiteral"&&i.key.value==="url"),n=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="method"||i.key.type==="StringLiteral"&&i.key.value==="method");if(t&&t.value){let i=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:i.toUpperCase(),url:r})}}}resolveUrlValue(e){return e.type==="StringLiteral"?e.value:e.type==="TemplateLiteral"?e.quasis.map(t=>t.cooked).join("*"):"?"}visitTsType(e){return e}extractApiCall(e,t,n=""){if(t.length>0){let i=t[0].expression,r=this.resolveUrlValue(i);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},jt=class{calls=new Set;apiCalls=[];imports=new Map;visit(e,t){if(t===".php"){let n=/(?:([a-zA-Z0-9_$->:\(\)]*)?(?:->|::))?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&!["$this","self","parent"].includes(r)&&this.calls.add(`${r}${r.includes("::")?"::":"->"}${o}`),["save","delete","update","create","first","all","where","get","find"].includes(o)&&r&&!["Log","Route","Cache","Config","Http"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}->${o}()`}),o==="publish"&&r&&(r.includes("topic")||r.includes("pubSub"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="Http"||r==="client"||r.endsWith("request")||r.includes("Client")||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if(t===".py"){let n=/(?:([a-zA-Z0-9_\.]+)\.)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&r!=="self"&&r!=="cls"&&this.calls.add(`${r}.${o}`),["save","delete","update","create","first","all","filter","get"].includes(o)&&r&&!["logger","os","sys"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}.${o}()`}),o==="publish"&&r&&(r.includes("publisher")||r.includes("client"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="requests"||r==="httpx"||r==="client"||r==="http"||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if([".ts",".tsx",".js",".jsx"].includes(t)){let n=/import\s+[\s\S]*?from\s+['"](.*?)['"];?/g,i;for(;(i=n.exec(e))!==null;)this.imports.set("*",i[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=o[2];a?(this.calls.add(`${a}.${c}`),(a.toLowerCase().includes("pubsub")||a==="pubSubClient")&&c!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:c})):this.calls.add(c)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,i;for(;(i=n.exec(e))!==null;)this.calls.add(i[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,i;for(;(i=n.exec(e))!==null;){let r=i[1],o=r.split("\\"),a=i[2]||o[o.length-1];this.imports.set(a,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,i;for(;(i=n.exec(e))!==null;){let a=i[1];i[2].split(",").map(l=>l.trim()).forEach(l=>{this.imports.set(l,a)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=a.split("."),l=c[c.length-1];this.imports.set(l,a)}}}};var Yp=new Set(["api","v1","v2","v3","http","https","localhost","admin","internal","public","private","app","src","get","post","put","delete","patch","user","users","id","search","list","create","update","data"]),Kp=new Set(["GET","POST","PUT","DELETE","PATCH"]),Qp=[/\bRoute::(?:get|post|put|delete|patch)\b/i,/\brouter\.(?:get|post|put|delete|patch)\s*\(/i,/\bapp\.(?:get|post|put|delete|patch)\s*\(/i,/\bfastify\.(?:get|post|put|delete|patch)\s*\(/i,/\baddRoute\s*\(/i,/\bHTTPMethods\.(?:GET|POST|PUT|DELETE|PATCH)\b/i,/\bpath\s*\(/i,/\bre_path\s*\(/i,/@(?:GET|POST|PUT|DELETE|PATCH|Route)\b/i,/@(?:Get|Post|Put|Delete|Patch|RequestMapping)\b/];function Xp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fn(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Cs(s){let e=fn(s).replace(/:[^/]+/g,"__SEG__").replace(/\{[^}]+\}/g,"__SEG__").replace(/\$[^/]+/g,"__SEG__").replace(/\*/g,"__SEG__"),t=Xp(e).replace(/__SEG__/g,"[^/]+");return new RegExp(`^${t}$`)}function ma(s){let e=[/(HTTPMethods\.)?(GET|POST|PUT|DELETE|PATCH)\b/i,/Route::(get|post|put|delete|patch)\b/i,/@(GET|POST|PUT|DELETE|PATCH)\b/i],t;for(let n of e){let i=s.match(n);if(i?.[2]){t=i[2].toUpperCase();break}if(i?.[1]){t=i[1].toUpperCase();break}}return t&&Kp.has(t)?t:null}function Zp(s){return s.replace(/<[^>]+>/g," ")}function eu(s){return Qp.some(e=>e.test(s))}function tu(s){let e=[],t=/['"`]([^'"`]*\/[^'"`]*)['"`]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();i&&e.push(i)}return e}function nu(s){let e=s.replace(/^\^/,"").replace(/\$$/,"");if(e.includes("://"))try{e=new URL(e).pathname}catch{}if(!e.startsWith("/")){let t=e.indexOf("/");if(t===-1)return null;e=e.slice(t)}return fn(e)}function iu(s,e){let t=tu(s);for(let n of t){let i=nu(n);if(!i)continue;let r=Cs(i),o=e.replace(/\*/g,"test-val");if(r.test(o)||!/[:{*$]/.test(i)&&o.startsWith(`${i}/`))return!0}return!1}function su(s,e){if(e)try{let i=JSON.parse(e);if(typeof i.path=="string"&&i.path.startsWith("/"))return fn(i.path)}catch{}let t=/['"]([^'"]+)['"]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();if(i){if(i=i.replace(/^\^/,"").replace(/\$$/,""),!i.startsWith("/")){if(!i.includes("/")&&!i.includes(":"))continue;i=`/${i}`}return fn(i)}}return null}function ru(s,e){let t=s.toLowerCase();return e.reduce((n,i)=>n+(t.includes(i.toLowerCase())?20:0),0)}function ha(s,e,t){let n=e,i=e.match(/\$\{([^}]+)\}/g);if(i)for(let h of i){let m=h.substring(2,h.length-1),f=s.configs.findEnvValue(m);f&&(n=n.replace(h,f))}let r=n.split("?")[0].split("#")[0];try{r.includes("://")&&(r=new URL(r).pathname)}catch{}r=fn(r);let o=t?.toUpperCase(),a=[],c=!1,l=r.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),p=s.files.findSynapses({type:"api_route",name:l.includes("%")?l:r,direction:"consume",limit:10});for(let h of p)Cs(h.name).test(r.replace(/\*/g,"test-val"))&&(a.push({file_path:h.file_path,start_line:h.line_number||0,signature:`[Synapse] ${h.name}`,score:1e3}),c=!0);let u=r.split(/[^a-zA-Z0-9-_]/).filter(h=>h.length>=3&&!Yp.has(h.toLowerCase())&&!/^\d+$/.test(h));if(u.length>0){let f=[...u].sort((g,b)=>b.length-g.length).slice(0,2).flatMap(g=>s.exports.findRoutesByToken(g,20)),_=new Set;for(let g of f){let b=`${g.file_path}:${g.start_line}:${g.name}`;if(_.has(b))continue;_.add(b);let w=g.signature||g.name||"",x=ma(w);if(o&&x&&o!==x)continue;let R=su(w,g.capabilities);if(o&&!x&&!R)continue;let k=40;if(R){if(!Cs(R).test(r.replace(/\*/g,"test-val")))continue;k+=280,c=!0}o&&x&&o===x&&(k+=120,c=!0),k+=ru(`${w} ${R||""}`,u),a.push({file_path:g.file_path,start_line:g.start_line,signature:`[Boundary] ${w}`,capabilities:g.capabilities||void 0,score:k})}}if(a.length<3&&!c){let h=u.map(m=>m.replace(/[^a-zA-Z0-9_]/g,"")).filter(m=>m.length>0).join(" AND ");if(h.length>0){let m=s.content.search(h);for(let f of m){let _=Zp(f.snippet);if(!eu(_)||!iu(_,r))continue;let g=ma(_);if(o&&g&&g!==o)continue;let b=0,w=f.file_path.toLowerCase(),x=_.toLowerCase();(w.includes("route")||w.includes("controller"))&&(b+=10),(w.includes("src/api")||w.includes("services/api"))&&(b+=5),(x.includes("addroute")||x.includes("@get"))&&(b+=15),(x.includes("axios.")||x.includes("fetch("))&&(b-=10),(w.includes(".spec.")||w.includes(".test."))&&(b-=20),o&&x.includes(o.toLowerCase())&&(b+=20),b>0&&a.push({file_path:f.file_path,start_line:0,signature:`[FTS Match] ${_.replace(/\n/g," ")}`,score:b})}}}let d=new Map;return a.sort((h,m)=>m.score-h.score).forEach(h=>{d.has(h.file_path)||d.set(h.file_path,h)}),Array.from(d.values()).slice(0,c?2:3)}var Is=7,Lt=80,ou=2,au=4,cu=6,lu=3,pu=24,uu=new Set(["publish","publishmessage","publishtaskbynameandpayload"]),du=new Set(["Error","TypeError","RangeError","ReferenceError","SyntaxError","Promise","Map","Set","WeakMap","WeakSet","Date","Array","Object","String","Number","Boolean","RegExp","URL","URLSearchParams"]),mu=new Set(["error","errors","request","response","result","results","value","values","item","data","payload","message","messages","text","description","name","id","type","status","code"]),ga=new Set(["req","res","request","response","error","err","event","item","row","data","value","obj","window","document","console","json","math"]),hu=new Set(["length","size","value","values","name","id","type","status"]),ya=new Set(["push","pop","shift","unshift","slice","splice","map","filter","reduce","reduceRight","forEach","find","findIndex","includes","indexOf","lastIndexOf","every","some","flat","flatMap","fill","copyWithin","entries","keys","values","join","concat","sort","reverse","at","with","toSorted","toReversed","toSpliced","toString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","charAt","charCodeAt","codePointAt","split","substring","substr","trim","trimStart","trimEnd","padStart","padEnd","repeat","replace","replaceAll","match","matchAll","search","toLowerCase","toUpperCase","localeCompare","normalize","startsWith","endsWith","then","catch","finally","get","set","has","delete","clear","size","length","call","apply","bind"]);function fu(s,e){return fe.resolve(s)===fe.resolve(e)}function gu(s){if(du.has(s))return!0;let e=s.trim().toLowerCase();if(!e||e.length<2||/\[|\]|\s/.test(s)||mu.has(e))return!0;let t=s.split(/(?:\.|->|::)+/).filter(Boolean),n=(t.length>0?t[t.length-1]:e).replace(/^\$+/,"");if(hu.has(n.toLowerCase())||ya.has(n))return!0;if(t.length>1){let i=t[0].replace(/^\$+/,"").toLowerCase();if(ga.has(i))return!0}return!1}function $s(s,e){if(e.has(s))return e.get(s)??null;try{let t=$t.readFileSync(s,"utf8");return e.set(s,t),t}catch{return null}}function yu(s){return s<20?Is:s<45?Is-1:Math.max(4,Is-2)}function bu(s,e){let t=s<=2?1:s<=4?.7:.4,n=e<25?1:e<55?.8:.55,i=Math.floor(pu*t*n);return Math.max(lu,i)}function _u(s,e){let t=s.split(`
|
|
668
|
-
`),n=new Map,i=new Map,r=[],o=new Set;for(let a=0;a<t.length;a++){let c=t[a],l=e+a+1,p=c.match(/\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/),u=c.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*[^=]/),d=p?.[1]||u?.[1];if(d){n.set(d,l);continue}for(let[h,m]of n.entries()){if(l<=m||!new RegExp(`\\b${
|
|
669
|
-
`),o=
|
|
719
|
+
${b.bold("Files/sec")}: ${b.green((r/(n/1e3)).toFixed(2))}
|
|
720
|
+
${b.bold("Symbols/sec")}: ${b.green((o/(n/1e3)).toFixed(2))}
|
|
721
|
+
${b.bold("ms per file")}: ${b.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
|
|
722
|
+
Benchmark failed during execution:`,n),n}finally{await ne(e)}})}import Di from"path";import Me from"path";import Us from"fs";var du=/[\x00-\x1f\x7f]/g,mu=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Bs(s){if(typeof s!="string")throw new Error("Invalid path: expected string");if(s.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(s.replace(du,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function $i(s,e=4096){if(typeof s!="string")return"";let t=s.replace(mu,"").trim();return t.length>e?t.slice(0,e):t}ut();function hu(s){let e=Me.isAbsolute(s)?Me.normalize(s):Me.resolve(process.cwd(),s),t=Me.parse(e).root;for(;e!==t;){if(Us.existsSync(Me.join(e,".liquid-shadow.db"))||Us.existsSync(Me.join(e,".git"))||Us.existsSync(Me.join(e,"package.json")))return e;let n=Me.dirname(e);if(n===e)break;e=n}return null}function st(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=Bs(e)),t&&(t=Bs(t));let n;if(e)Me.isAbsolute(e)||(e=Me.resolve(process.cwd(),e)),n=e;else if(t){let o=Me.resolve(process.cwd(),t);n=hu(Me.dirname(o))||process.cwd()}else n=process.cwd();n=Me.normalize(n);let i=$a(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}Y();G();import Gt from"fs";import Se from"path";import{Visitor as fu}from"@swc/core/Visitor.js";var Pi=class extends fu{calls=new Set;apiCalls=[];imports=new Map;axiosInstances=new Map([["axios",""],["http",""],["appApi",""],["restApi",""],["adminApi",""]]);visitImportDeclaration(e){let t=e.source.value;for(let n of e.specifiers)(n.type==="ImportDefaultSpecifier"||n.type==="ImportSpecifier")&&this.imports.set(n.local.value,t);return super.visitImportDeclaration(e)}visitCallExpression(e){if(e.callee.type==="Identifier"){let t=e.callee.value;this.calls.add(t),(t==="axios"||t==="http")&&e.arguments.length>0&&this.extractApiCallFromConfig(e.arguments[0].expression)}else if(e.callee.type==="MemberExpression"){let t=e.callee.property.value,n=r=>{if(!r)return"?";if(r.type==="Identifier")return r.value;if(r.type==="ThisExpression")return"this";if(r.type==="MemberExpression"){let o=n(r.object),a=r.property.value||"?";return`${o}.${a}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},i=n(e.callee.object);if(i!=="?"&&t){if(this.calls.add(`${i}.${t}`),i==="axios"||i==="http"||this.axiosInstances.has(i)){let r=this.axiosInstances.get(i)||"";this.extractApiCall(t,e.arguments,r)}if((i.toLowerCase().includes("pubsub")||i==="pubSubClient"||i.endsWith(".pubSubClient"))&&t!=="subscribe"){let r=t;if((t==="publish"||t==="publishMessage"||t==="publishTaskByNameAndPayload")&&e.arguments.length>0)for(let o of e.arguments){let a=o.expression;if(a.type==="ObjectExpression"){let c=a.properties.find(l=>l.key?.type==="Identifier"&&(l.key.value==="action"||l.key.value==="type")||l.key?.type==="StringLiteral"&&(l.key.value==="action"||l.key.value==="type"));if(c&&c.value?.type==="StringLiteral"){r=c.value.value;break}}if(a.type==="CallExpression"&&a.callee.type==="MemberExpression"&&a.callee.object.value==="JSON"&&a.callee.property.value==="stringify"&&a.arguments.length>0){let c=a.arguments[0].expression;if(c.type==="ObjectExpression"){let l=c.properties.find(p=>p.key?.type==="Identifier"&&(p.key.value==="action"||p.key.value==="type")||p.key?.type==="StringLiteral"&&(p.key.value==="action"||p.key.value==="type"));if(l&&l.value?.type==="StringLiteral"){r=l.value.value;break}}}}this.apiCalls.push({method:"PUBSUB",url:r})}}}return e.callee.type==="Identifier"&&e.callee.value==="fetch"&&this.extractApiCall("GET",e.arguments),super.visitCallExpression(e)}visitNewExpression(e){return e.callee.type==="Identifier"&&this.calls.add(e.callee.value),super.visitNewExpression(e)}visitVariableDeclarator(e){if(e.init&&e.init.type==="CallExpression"){let t=e.init.callee;if(t.type==="MemberExpression"&&t.property.value==="create"&&t.object.value==="axios"){let i=e.init.arguments[0]?.expression;if(i&&i.type==="ObjectExpression"){let r=i.properties.find(o=>o.key.value==="baseURL");if(r){let o="?";r.value.type==="StringLiteral"?o=r.value.value:r.value.type==="Identifier"&&(o=`\${${r.value.value}}`),e.id.type==="Identifier"&&this.axiosInstances.set(e.id.value,o)}}}}return super.visitVariableDeclarator(e)}extractApiCallFromConfig(e){if(e&&e.type==="ObjectExpression"){let t=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="url"||i.key.type==="StringLiteral"&&i.key.value==="url"),n=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="method"||i.key.type==="StringLiteral"&&i.key.value==="method");if(t&&t.value){let i=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:i.toUpperCase(),url:r})}}}resolveUrlValue(e){return e.type==="StringLiteral"?e.value:e.type==="TemplateLiteral"?e.quasis.map(t=>t.cooked).join("*"):"?"}visitTsType(e){return e}extractApiCall(e,t,n=""){if(t.length>0){let i=t[0].expression,r=this.resolveUrlValue(i);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},nn=class{calls=new Set;apiCalls=[];imports=new Map;visit(e,t){if(t===".php"){let n=/(?:([a-zA-Z0-9_$->:\(\)]*)?(?:->|::))?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&!["$this","self","parent"].includes(r)&&this.calls.add(`${r}${r.includes("::")?"::":"->"}${o}`),["save","delete","update","create","first","all","where","get","find"].includes(o)&&r&&!["Log","Route","Cache","Config","Http"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}->${o}()`}),o==="publish"&&r&&(r.includes("topic")||r.includes("pubSub"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="Http"||r==="client"||r.endsWith("request")||r.includes("Client")||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if(t===".py"){let n=/(?:([a-zA-Z0-9_\.]+)\.)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&r!=="self"&&r!=="cls"&&this.calls.add(`${r}.${o}`),["save","delete","update","create","first","all","filter","get"].includes(o)&&r&&!["logger","os","sys"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}.${o}()`}),o==="publish"&&r&&(r.includes("publisher")||r.includes("client"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="requests"||r==="httpx"||r==="client"||r==="http"||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if([".ts",".tsx",".js",".jsx"].includes(t)){let n=/import\s+[\s\S]*?from\s+['"](.*?)['"];?/g,i;for(;(i=n.exec(e))!==null;)this.imports.set("*",i[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=o[2];a?(this.calls.add(`${a}.${c}`),(a.toLowerCase().includes("pubsub")||a==="pubSubClient")&&c!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:c})):this.calls.add(c)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,i;for(;(i=n.exec(e))!==null;)this.calls.add(i[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,i;for(;(i=n.exec(e))!==null;){let r=i[1],o=r.split("\\"),a=i[2]||o[o.length-1];this.imports.set(a,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,i;for(;(i=n.exec(e))!==null;){let a=i[1];i[2].split(",").map(l=>l.trim()).forEach(l=>{this.imports.set(l,a)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=a.split("."),l=c[c.length-1];this.imports.set(l,a)}}}};var gu=new Set(["api","v1","v2","v3","http","https","localhost","admin","internal","public","private","app","src","get","post","put","delete","patch","user","users","id","search","list","create","update","data"]),yu=new Set(["GET","POST","PUT","DELETE","PATCH"]),bu=[/\bRoute::(?:get|post|put|delete|patch)\b/i,/\brouter\.(?:get|post|put|delete|patch)\s*\(/i,/\bapp\.(?:get|post|put|delete|patch)\s*\(/i,/\bfastify\.(?:get|post|put|delete|patch)\s*\(/i,/\baddRoute\s*\(/i,/\bHTTPMethods\.(?:GET|POST|PUT|DELETE|PATCH)\b/i,/\bpath\s*\(/i,/\bre_path\s*\(/i,/@(?:GET|POST|PUT|DELETE|PATCH|Route)\b/i,/@(?:Get|Post|Put|Delete|Patch|RequestMapping)\b/];function _u(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kn(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function js(s){let e=kn(s).replace(/:[^/]+/g,"__SEG__").replace(/\{[^}]+\}/g,"__SEG__").replace(/\$[^/]+/g,"__SEG__").replace(/\*/g,"__SEG__"),t=_u(e).replace(/__SEG__/g,"[^/]+");return new RegExp(`^${t}$`)}function Fa(s){let e=[/(HTTPMethods\.)?(GET|POST|PUT|DELETE|PATCH)\b/i,/Route::(get|post|put|delete|patch)\b/i,/@(GET|POST|PUT|DELETE|PATCH)\b/i],t;for(let n of e){let i=s.match(n);if(i?.[2]){t=i[2].toUpperCase();break}if(i?.[1]){t=i[1].toUpperCase();break}}return t&&yu.has(t)?t:null}function Eu(s){return s.replace(/<[^>]+>/g," ")}function Su(s){return bu.some(e=>e.test(s))}function wu(s){let e=[],t=/['"`]([^'"`]*\/[^'"`]*)['"`]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();i&&e.push(i)}return e}function xu(s){let e=s.replace(/^\^/,"").replace(/\$$/,"");if(e.includes("://"))try{e=new URL(e).pathname}catch{}if(!e.startsWith("/")){let t=e.indexOf("/");if(t===-1)return null;e=e.slice(t)}return kn(e)}function vu(s,e){let t=wu(s);for(let n of t){let i=xu(n);if(!i)continue;let r=js(i),o=e.replace(/\*/g,"test-val");if(r.test(o)||!/[:{*$]/.test(i)&&o.startsWith(`${i}/`))return!0}return!1}function Ru(s,e){if(e)try{let i=JSON.parse(e);if(typeof i.path=="string"&&i.path.startsWith("/"))return kn(i.path)}catch{}let t=/['"]([^'"]+)['"]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();if(i){if(i=i.replace(/^\^/,"").replace(/\$$/,""),!i.startsWith("/")){if(!i.includes("/")&&!i.includes(":"))continue;i=`/${i}`}return kn(i)}}return null}function Tu(s,e){let t=s.toLowerCase();return e.reduce((n,i)=>n+(t.includes(i.toLowerCase())?20:0),0)}function Wa(s,e,t){let n=e,i=e.match(/\$\{([^}]+)\}/g);if(i)for(let h of i){let m=h.substring(2,h.length-1),f=s.configs.findEnvValue(m);f&&(n=n.replace(h,f))}let r=n.split("?")[0].split("#")[0];try{r.includes("://")&&(r=new URL(r).pathname)}catch{}r=kn(r);let o=t?.toUpperCase(),a=[],c=!1,l=r.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),p=s.files.findSynapses({type:"api_route",name:l.includes("%")?l:r,direction:"consume",limit:10});for(let h of p)js(h.name).test(r.replace(/\*/g,"test-val"))&&(a.push({file_path:h.file_path,start_line:h.line_number||0,signature:`[Synapse] ${h.name}`,score:1e3}),c=!0);let u=r.split(/[^a-zA-Z0-9-_]/).filter(h=>h.length>=3&&!gu.has(h.toLowerCase())&&!/^\d+$/.test(h));if(u.length>0){let f=[...u].sort((y,_)=>_.length-y.length).slice(0,2).flatMap(y=>s.exports.findRoutesByToken(y,20)),S=new Set;for(let y of f){let _=`${y.file_path}:${y.start_line}:${y.name}`;if(S.has(_))continue;S.add(_);let E=y.signature||y.name||"",R=Fa(E);if(o&&R&&o!==R)continue;let T=Ru(E,y.capabilities);if(o&&!R&&!T)continue;let k=40;if(T){if(!js(T).test(r.replace(/\*/g,"test-val")))continue;k+=280,c=!0}o&&R&&o===R&&(k+=120,c=!0),k+=Tu(`${E} ${T||""}`,u),a.push({file_path:y.file_path,start_line:y.start_line,signature:`[Boundary] ${E}`,capabilities:y.capabilities||void 0,score:k})}}if(a.length<3&&!c){let h=u.map(m=>m.replace(/[^a-zA-Z0-9_]/g,"")).filter(m=>m.length>0).join(" AND ");if(h.length>0){let m=s.content.search(h);for(let f of m){let S=Eu(f.snippet);if(!Su(S)||!vu(S,r))continue;let y=Fa(S);if(o&&y&&y!==o)continue;let _=0,E=f.file_path.toLowerCase(),R=S.toLowerCase();(E.includes("route")||E.includes("controller"))&&(_+=10),(E.includes("src/api")||E.includes("services/api"))&&(_+=5),(R.includes("addroute")||R.includes("@get"))&&(_+=15),(R.includes("axios.")||R.includes("fetch("))&&(_-=10),(E.includes(".spec.")||E.includes(".test."))&&(_-=20),o&&R.includes(o.toLowerCase())&&(_+=20),_>0&&a.push({file_path:f.file_path,start_line:0,signature:`[FTS Match] ${S.replace(/\n/g," ")}`,score:_})}}}let d=new Map;return a.sort((h,m)=>m.score-h.score).forEach(h=>{d.has(h.file_path)||d.set(h.file_path,h)}),Array.from(d.values()).slice(0,c?2:3)}var Gs=7,jt=80,ku=2,Cu=4,Iu=6,Lu=3,Mu=24,Au=new Set(["publish","publishmessage","publishtaskbynameandpayload"]),$u=new Set(["Error","TypeError","RangeError","ReferenceError","SyntaxError","Promise","Map","Set","WeakMap","WeakSet","Date","Array","Object","String","Number","Boolean","RegExp","URL","URLSearchParams"]),Pu=new Set(["error","errors","request","response","result","results","value","values","item","data","payload","message","messages","text","description","name","id","type","status","code"]),Ha=new Set(["req","res","request","response","error","err","event","item","row","data","value","obj","window","document","console","json","math"]),Nu=new Set(["length","size","value","values","name","id","type","status"]),Ba=new Set(["push","pop","shift","unshift","slice","splice","map","filter","reduce","reduceRight","forEach","find","findIndex","includes","indexOf","lastIndexOf","every","some","flat","flatMap","fill","copyWithin","entries","keys","values","join","concat","sort","reverse","at","with","toSorted","toReversed","toSpliced","toString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","charAt","charCodeAt","codePointAt","split","substring","substr","trim","trimStart","trimEnd","padStart","padEnd","repeat","replace","replaceAll","match","matchAll","search","toLowerCase","toUpperCase","localeCompare","normalize","startsWith","endsWith","then","catch","finally","get","set","has","delete","clear","size","length","call","apply","bind"]);function Du(s,e){return Se.resolve(s)===Se.resolve(e)}function Ou(s){if($u.has(s))return!0;let e=s.trim().toLowerCase();if(!e||e.length<2||/\[|\]|\s/.test(s)||Pu.has(e))return!0;let t=s.split(/(?:\.|->|::)+/).filter(Boolean),n=(t.length>0?t[t.length-1]:e).replace(/^\$+/,"");if(Nu.has(n.toLowerCase())||Ba.has(n))return!0;if(t.length>1){let i=t[0].replace(/^\$+/,"").toLowerCase();if(Ha.has(i))return!0}return!1}function Vs(s,e){if(e.has(s))return e.get(s)??null;try{let t=Gt.readFileSync(s,"utf8");return e.set(s,t),t}catch{return null}}function Fu(s){return s<20?Gs:s<45?Gs-1:Math.max(4,Gs-2)}function Wu(s,e){let t=s<=2?1:s<=4?.7:.4,n=e<25?1:e<55?.8:.55,i=Math.floor(Mu*t*n);return Math.max(Lu,i)}function zu(s,e){let t=s.split(`
|
|
723
|
+
`),n=new Map,i=new Map,r=[],o=new Set;for(let a=0;a<t.length;a++){let c=t[a],l=e+a+1,p=c.match(/\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/),u=c.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*[^=]/),d=p?.[1]||u?.[1];if(d){n.set(d,l);continue}for(let[h,m]of n.entries()){if(l<=m||!new RegExp(`\\b${Ua(h)}\\b`).test(c))continue;let f=i.get(h)||0;if(f>=2)continue;let S=`${h}:${m}->${l}`;o.has(S)||(r.push({symbol:h,fromLine:m,toLine:l}),o.add(S),i.set(h,f+1))}}return r}function za(s){let e=s.trim();if(!e)return"";let t=e.indexOf("/"),n=t>=0?e.slice(t):e;return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function Ua(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Js(s){let e=s.split(/(?:\.|::|->)+/).filter(Boolean);return e.length>0?e[e.length-1]:s.trim()}function Hu(s,e){let t=0,n=!1;for(let i=e;i<s.length;i++){let r=s[i];for(let a of r)if(a==="{")t++,n=!0;else if(a==="}"&&(t--,n&&t<=0))return{start:e+1,end:i+1};let o=r.trim();if(!n&&/[;}]$/.test(o))return{start:e+1,end:i+1}}return{start:e+1,end:Math.min(s.length,e+40)}}function qs(s,e,t){let n=Js(e);if(!n)return null;try{let i=t?Vs(s,t):Gt.readFileSync(s,"utf8");if(!i)return null;let r=i.split(`
|
|
724
|
+
`),o=Ua(n),a=[new RegExp(`^\\s*(?:export\\s+)?(?:async\\s+)?function\\s+${o}\\b`),new RegExp(`^\\s*(?:(?:public|private|protected|static|readonly|async|abstract|get|set)\\s+)*${o}\\s*(?:<[^>]*>)?\\s*\\(`),new RegExp(`^\\s*(?:(?:public|private|protected|static|readonly|async|abstract)\\s+)*${o}\\s*[:=]\\s*(?:async\\s*)?(?:\\([^)]*\\)\\s*=>|function\\b)`),new RegExp(`^\\s*(?:export\\s+)?class\\s+${o}\\b`)];for(let c=0;c<r.length;c++){let l=r[c];if(l.includes(n)&&a.some(p=>p.test(l)))return Hu(r,c)}}catch{return null}return null}function ja(s,e,t,n){try{let i=n?Vs(s,n):Gt.readFileSync(s,"utf8");if(!i)return!0;let r=i.split(`
|
|
670
725
|
`);if(e.start<1||e.end<e.start||e.start>r.length||e.end>r.length||!r.slice(e.start-1,e.end).join(`
|
|
671
|
-
`).trim())return!0;if(e.start===e.end){let a=r[e.start-1]?.trim()||"",c=a.replace(/\s+/g,"");if(!c||/^[{}()[\];,]+$/.test(c))return!0;let l=
|
|
672
|
-
File: ${
|
|
673
|
-
`+(
|
|
726
|
+
`).trim())return!0;if(e.start===e.end){let a=r[e.start-1]?.trim()||"",c=a.replace(/\s+/g,"");if(!c||/^[{}()[\];,]+$/.test(c))return!0;let l=Js(t);if(l&&!a.includes(l))return!0}return!1}catch{return!0}}function Ni(s,e,t,n){if(e){if(!t)return e;if(ja(s,e,t,n)){let i=qs(s,t,n);if(i)return i}return e}}function Bu(s,e,t){let n=s.exports.findByNameAndFile(t,e);if(n.length>0)return n[0];let i=s.exports.findByFile(e);if(i.length===0)return null;if(t.includes("/")){let a=za(t),c=i.find(l=>!l?.name||typeof l.name!="string"?!1:za(l.name)===a);if(c)return c}let r=t.split(/(?:\.|::|->)+/).filter(Boolean);if(r.length>1){let a=r[r.length-1],c=s.exports.findByNameAndFile(a,e);if(c.length===1)return c[0]}return i.find(a=>typeof a?.name=="string"&&(a.name===t||a.name.includes(t)))||null}async function Ga(s){let{repoPath:e,filePath:t,symbolName:n}=st(s);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let i=t;await ie(e);let r=N.getInstance(e);if(!Gt.existsSync(i))return{isError:!0,content:[{type:"text",text:`File not found: ${i}`}]};let o=new Map,a,c=Se.basename(i),l;if(n){let h=Js(n),m=Bu(r,i,n);if(m){let f=m;a={start:f.start_line,end:f.end_line},c=f.name,l=f.start_line}else{let f=qs(i,n,o);if(f)a=f,l=f.start,c=h||n;else{let S=r.exports.findByFile(i).map(y=>y.name).filter(y=>!!y).slice(0,10);return{isError:!0,content:[{type:"text",text:`Symbol not found in file: "${n}"
|
|
727
|
+
File: ${Se.relative(e,i)}
|
|
728
|
+
`+(S.length>0?`Top symbols in file: ${S.join(", ")}`:"No indexed symbols found for this file.")}]}}}if(a&&ja(i,a,n,o)){let f=qs(i,n,o);f&&(w.warn({filePath:i,symbolName:n,start:a.start,end:a.end},"Indexed symbol range appears degenerate; using source-inferred range for flow"),a=f,l=f.start,c===Se.basename(i)&&(c=h||n))}}let p={type:a?"function":"file",name:c,path:Se.relative(e,i),line:l,children:[]},u=new Set;u.add(i+(n?`:${n}`:""));let d={count:0,truncated:!1,pruned:!1};return await sn(i,p,e,r,u,1,d,o,a),(d.truncated||d.pruned)&&p.children.push({type:"function",name:"\u26A0\uFE0F Trace Pruned",details:`Adaptive trace limits applied (depth/node budget). Current cap: ${jt} nodes.`,children:[]}),{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}async function sn(s,e,t,n,i,r,o,a,c){let l=Fu(o.count);if(r>l){o.pruned=!0;return}if(o.count>=jt){o.truncated=!0;return}try{let p=Vs(s,a);if(!p)throw new Error(`Unable to read source: ${s}`);let u=p,d=Se.extname(s).toLowerCase(),m=(u.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
|
|
674
729
|
`);c&&(u=u.split(`
|
|
675
730
|
`).slice(c.start-1,c.end).join(`
|
|
676
|
-
`));let f;if(d===".ts"||d===".tsx"||d===".js"||d===".jsx"){f=new
|
|
677
|
-
${u}`:u,
|
|
731
|
+
`));let f;if(d===".ts"||d===".tsx"||d===".js"||d===".jsx"){f=new Pi;let M={syntax:"typescript",tsx:s.endsWith(".tsx"),target:"es2020"};try{let v=c?`${m}
|
|
732
|
+
${u}`:u,I=await Is(v,M);f.visitModule(I)}catch{if(c)try{let I=`${m}
|
|
678
733
|
class TraceContext {
|
|
679
734
|
${u}
|
|
680
|
-
}
|
|
681
|
-
`).filter(o=>o.trim()!=="");if(r.length===0)return;
|
|
682
|
-
`);for(let i of n){let[r,o]=i.split(" ");if(o){let a=this.getNote(o);a&&e.set(o,a)}}}catch{}return e}removeNote(e){try{
|
|
735
|
+
}`,$=await Is(I,M);f.visitModule($)}catch{let $=new nn,P=d;$.visit(u,P),f.calls=$.calls,f.apiCalls=$.apiCalls,f.imports=$.imports}else{let I=new nn;I.visit(u,d),f.calls=I.calls,f.apiCalls=I.apiCalls,f.imports=I.imports}}}else f=new nn,f.visit(u,d);w.info({file:Se.basename(s),calls:f.calls.size,apiCalls:f.apiCalls.length,depth:r},"Analyzed file");let S=Math.max(0,jt-o.count),y=Math.max(2,Math.min(10,Math.floor(S/(r<=2?3:5)))),_=f.apiCalls.slice(0,y);f.apiCalls.length>y&&(o.pruned=!0);for(let M of _){if(o.count>=jt)break;if(o.count++,M.method==="PUBSUB"){let P={type:"event_trigger",name:`PubSub Event: ${M.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(P);let U=M.url.toLowerCase();if(Au.has(U)){P.children.push({type:"subscriber",name:"PubSub fan-out omitted",details:"Generic publish call without concrete event/action; skipping global subscriber expansion to avoid false links.",children:[]});continue}let A=n.exports.findByNameGlobal(M.url).concat(n.exports.findByMethodName(M.url));if(M.url.length>10){let L=M.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(L!==M.url){let D=n.exports.findByNameGlobal(L).concat(n.exports.findByMethodName(L));A.push(...D)}}let H=new Set;for(let L of A.slice(0,Cu)){if(H.has(L.file_path)||L.file_path===s)continue;if(H.add(L.file_path),o.count>=jt)break;o.count++;let D={type:"subscriber",name:`${L.name} (${Se.basename(L.file_path)})`,path:Se.relative(t,L.file_path),line:L.start_line,details:"Potential Subscriber / Handler",children:[]};P.children.push(D),Gt.existsSync(L.file_path)&&!i.has(L.file_path)&&(i.add(L.file_path),await sn(L.file_path,D,t,n,i,r+1,o,a))}continue}let v={type:"api_call",name:`${M.method} ${M.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(v);let $=Wa(n,M.url,M.method).slice(0,ku);for(let P of $){if(Du(P.file_path,s))continue;if(o.count>=jt)break;o.count++;let U={type:"route",name:P.signature||"Route Handler",path:P.file_path,line:P.start_line,children:[]};if(v.children.push(U),Gt.existsSync(P.file_path)&&!i.has(P.file_path)&&(i.add(P.file_path),await sn(P.file_path,U,t,n,i,r+1,o,a)),P.capabilities)try{let A=JSON.parse(P.capabilities);if(A.handler){let[H,L]=A.handler.split("@");if(H){let J=H.split("\\").pop();if(J){let z=n.exports.findClassByName(J);if(z){let g=n.exports.findByNameAndFile(L||"",z.file_path),x,O=z.start_line;g.length>0&&(x=Ni(z.file_path,{start:g[0].start_line,end:g[0].end_line},L||"",a),x||(x={start:g[0].start_line,end:g[0].end_line}),O=x.start);let C={type:"component",name:`${J}${L?" :: "+L:""}`,path:Se.relative(t,z.file_path),line:O,details:"Controller Logic (Macro IR)",children:[]};U.children.push(C),i.has(z.file_path+(L?`:${L}`:""))||(i.add(z.file_path+(L?`:${L}`:"")),await sn(z.file_path,C,t,n,i,r+1,o,a,x))}}}}}catch{}}}let E=c?c.start-1:0,R=zu(u,E).slice(0,Iu);for(let M of R){if(o.count>=jt)break;o.count++,e.children.push({type:"data_flow",name:`${M.symbol} handoff`,line:M.toLine,details:`assigned @L${M.fromLine} \u2192 used @L${M.toLine}`,children:[]})}let T=f.calls,k=Array.from(T).sort(),F=Wu(r,o.count),B=k.slice(0,F);k.length>F&&(o.pruned=!0);for(let M of B)if(f.imports.has(M)){let v=f.imports.get(M);if(!v.startsWith(".")){if(["react","react-dom"].includes(v))continue;e.children.push({type:"function",name:M,details:`External: ${v}`,children:[]});continue}let I=Wt(v,s,t);if(I&&Gt.existsSync(I)){let $=n.exports.findByNameAndFile(M,I),P=$.length>0?$[0]:null,U=P?`${I}:${P.name}`:I;if(i.has(U))e.children.push({type:"function",name:M,details:"Circular / Already Visited",path:Se.relative(t,I),line:P?.start_line,children:[]});else{i.add(U);let A={type:P?"component":"file",name:M,details:P?`Imported symbol from ${Se.basename(I)}`:`Imported from ${Se.basename(I)}`,path:Se.relative(t,I),line:P?.start_line,children:[]};e.children.push(A);let H=P?Ni(I,{start:P.start_line,end:P.end_line},M,a):void 0;await sn(I,A,t,n,i,r+1,o,a,H)}}}else if(!["log","info","error","warn","print"].includes(M)&&!Ou(M)){let v=n.exports.findByNameGlobal(M);if(v.length===0){let I=M.split(/(?:\.|->|::)+/);if(I.length>1){let $=I[0]?.replace(/^\$+/,"").toLowerCase(),P=I[I.length-1];!Ba.has(P)&&!($&&Ha.has($))&&(v=n.exports.findByMethodName(P))}}if(v.length>0){let I=v.find(P=>P.file_path===s),$=I||(v.length===1?v[0]:null);if($){let P=`${$.file_path}:${$.name}`;if(!i.has(P)){i.add(P);let U={type:"component",name:M,details:`Resolved via global index${I?" (local)":""}`,path:Se.relative(t,$.file_path),line:Ni($.file_path,{start:$.start_line,end:$.end_line},M,a)?.start,children:[]};e.children.push(U);let A=Ni($.file_path,{start:$.start_line,end:$.end_line},M,a)||{start:$.start_line,end:$.end_line};await sn($.file_path,U,t,n,i,r+1,o,a,A)}}}}}catch(p){w.error({filePath:s,error:p.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:p.message,children:[]})}}async function qa(s,e){let t=Di.resolve(e.dir),n=Di.isAbsolute(s)?s:Di.resolve(t,s);await Q(async()=>{ge("Execution Trace");let i=Oe();i.start(`Tracing ${b.cyan(e.symbolName||Di.basename(n))}...`);try{let r=await Ga({repoPath:t,filePath:n,symbolName:e.symbolName});i.stop("Trace complete."),r.isError?console.error(b.red(r.content[0].text)):ue("Flow Results",r.content[0].text,"magenta")}catch(r){throw i.stop(`Trace failed: ${r.message}`),r}finally{await ne(t)}})}import Gu from"path";Y();rn();G();import{execSync as Ja}from"child_process";import ju from"path";var Oi=w.child({module:"shadow-trace"}),on=class{intentLogs;exports;repoPath;hologramService;constructor(e){let{intentLogs:t,exports:n}=N.getInstance(e);this.intentLogs=t,this.exports=n,this.repoPath=e,this.hologramService=new Ae(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=Ja(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
|
|
736
|
+
`).filter(o=>o.trim()!=="");if(r.length===0)return;Oi.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let a=ju.join(this.repoPath,o),l=Ja(`git diff -U0 ${t} -- ${o}`,{cwd:this.repoPath,encoding:"utf-8"}).matchAll(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/g);for(let p of l){let u=parseInt(p[2],10),d=this.exports.findAtLine(a,u);d&&(this.intentLogs.create({mission_id:0,file_path:a,symbol_id:d.id,type:"discovery",content:`Shadow Trace: Modified externally in ${t}`,confidence:.8,symbol_name:d.name,signature:d.signature,commit_sha:null}),Oi.debug({symbol:d.name},"Logged ghost change"),n.push({from:"external",to:`${o}:${d.name}`,pattern:"git-delta",confidence:.8}))}}n.length>0&&this.hologramService.updateGhostBridges(n),Oi.info("Shadow Trace complete.")}catch(i){Oi.warn({err:i.message},"Shadow Trace failed: git diff error.")}}};Y();import{execSync as an}from"child_process";var Fi=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{an(`git notes --ref ${this.ref} add -f -m '${t.replace(/'/g,"'\\''")}' ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch(n){throw new Error(`Failed to add git note to ${e}: ${n.message}`)}}getNote(e){try{return an(`git notes --ref ${this.ref} show ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}listNotes(){let e=new Map;try{let t=an(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
|
|
737
|
+
`);for(let i of n){let[r,o]=i.split(" ");if(o){let a=this.getNote(o);a&&e.set(o,a)}}}catch{}return e}removeNote(e){try{an(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{an(`git push ${e} ${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch(t){throw new Error(`Failed to push git notes to ${e}: ${t.message}`)}}fetch(e="origin"){try{an(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};G();Cn();var cn=w.child({module:"persistence-service"}),Ze=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new Fi(e)}async syncMissionToGitNotes(e){let{missions:t,intentLogs:n}=N.getInstance(this.repoPath),i=t.findById(e);if(!i)throw new Error(`Mission ${e} not found`);if(!i.commit_sha){cn.info({missionId:e},"Skipping Git Notes sync because mission has no commit_sha yet");return}cn.info({missionId:e,commitSha:i.commit_sha},"Syncing mission to Git Notes");let r=t.getArtifacts(e),o=n.findByMission(e,1e3),a=o.find(p=>p.type==="adr"),c=o.filter(p=>p.type==="decision").map(p=>({content:p.content,symbol_name:p.symbol_name,created_at:p.created_at})),l={version:"1.0",mission:{name:i.name,goal:i.goal,status:i.status,strategy_graph:i.strategy_graph,git_branch:i.git_branch,commit_sha:i.commit_sha,parent_id:i.parent_id,verification_context:i.verification_context,outcome_contract:i.outcome_contract,created_at:i.created_at,updated_at:i.updated_at},artifacts:r,adr:a?a.content:null,decisions:c};this.gitNotes.addNote(i.commit_sha,JSON.stringify(l,null,2))}async syncAllToGitNotes(){let{missions:e}=N.getInstance(this.repoPath),t=e.findActive(),n=e.findRecentCompleted(10),i=[...t,...n];for(let r of i)try{await this.syncMissionToGitNotes(r.id)}catch(o){cn.error({missionId:r.id,...Re(o)},"Failed to sync mission")}}async recoverFromGitNotes(){let e=this.gitNotes.listNotes(),{missions:t,intentLogs:n}=N.getInstance(this.repoPath),i=0,r=0;for(let[o,a]of e.entries())try{let c=JSON.parse(a);if(c.version!=="1.0")continue;if(t.findByCommitShas([o]).some(d=>d.name===c.mission.name)){cn.debug({commitSha:o,missionName:c.mission.name},"Mission already exists, skipping recovery");continue}let u=t.create({name:c.mission.name,goal:c.mission.goal,status:c.mission.status,strategy_graph:c.mission.strategy_graph,git_branch:c.mission.git_branch,commit_sha:o,parent_id:c.mission.parent_id,verification_context:c.mission.verification_context,outcome_contract:c.mission.outcome_contract});if(i++,c.adr&&(n.create({mission_id:Number(u),symbol_id:null,file_path:null,type:"adr",content:c.adr,confidence:1,symbol_name:null,signature:null,commit_sha:o}),r++),c.decisions&&c.decisions.length>0)for(let d of c.decisions)n.create({mission_id:Number(u),symbol_id:null,file_path:null,type:"decision",content:d.content,confidence:1,symbol_name:d.symbol_name,signature:null,commit_sha:o}),r++;cn.info({commitSha:o,missionName:c.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(c){cn.error({commitSha:o,...Re(c)},"Failed to parse Git Note for recovery")}return{missionsRecovered:i,logsRecovered:r}}};Y();Ut();async function Ya(s){let{repoPath:e,enableContextPivot:t,enableMergeSentinel:n}=s;try{await ie(e),new on(e).analyzeGhostChanges();let r=new it(e),o=r.detectAndRepairShifts(),a=r.syncLifecycle({enableContextPivot:t,enableMergeSentinel:n}),l=await new Ze(e).recoverFromGitNotes(),{HologramService:p}=await Promise.resolve().then(()=>(rn(),Va)),u=new p(e),d=kt(N.getInstance(e),e);u.updateTopography(d);let h=u.computeGravityZones();u.updateGravityZones(h);let m="Shadow Sync complete. Code changes indexed and intent logs updated.";return m+=`
|
|
683
738
|
\u269B\uFE0F Hologram: Refreshed architectural map (${h.length} hotspots).`,o.repaired>0&&(m+=`
|
|
684
739
|
\u2728 Nano-Repair: Fixed ${o.repaired} links.`),m+=`
|
|
685
740
|
\u{1F9ED} Lifecycle: contextPivot=${a.contextPivotEnabled?"on":"off"}, mergeSentinel=${a.mergeSentinelEnabled?"on":"off"}, suspended=${a.suspended}, resumed=${a.resumed}, completed=${a.completed}.`,l.missionsRecovered>0&&(m+=`
|
|
686
|
-
\u{1F9EC} Re-hydration: Recovered ${l.missionsRecovered} missions.`),{content:[{type:"text",text:m}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}async function
|
|
741
|
+
\u{1F9EC} Re-hydration: Recovered ${l.missionsRecovered} missions.`),{content:[{type:"text",text:m}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}async function Ka(s,e){let t=Gu.resolve(s);await Q(async()=>{ge("Shadow Sync");let n=Oe();n.start("Synchronizing intelligence lifecycle...");try{let i=await Ya({repoPath:t,enableContextPivot:e.contextPivot===!0,enableMergeSentinel:e.mergeSentinel===!0});n.stop("Sync complete."),i.isError?console.error(b.red(i.content[0].text)):(console.log(""),console.log(i.content[0].text),console.log(""))}catch(i){throw n.stop(`Sync failed: ${i.message}`),i}finally{await ne(t)}})}Ut();Y();G();rn();import Za from"path";Y();Ut();rn();import dt from"path";async function Qa(s){let{repoPath:e}=s;await ie(e);let t=N.getInstance(e),n=kt(t,e),r=new Ae(e).getSnapshot(),o=[],a=[],c=Object.values(n.layers.Entry.topFiles).map(d=>d.path),l=new Set(Object.values(n.layers.Data.topFiles).map(d=>d.path));for(let d of c){let h=dt.isAbsolute(d)?d:dt.join(e,d),m=t.imports.findByFile(h);for(let f of m)f.resolved_path&&l.has(dt.relative(e,f.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${dt.relative(e,d)}\` directly imports Data layer \`${dt.relative(e,f.resolved_path)}\`. Should go through Logic.`)}let p=r.gravity?.hotspots||[];for(let d of p){let h=Bt(d.filePath,t);(h.layer==="Utility"||h.layer==="Unknown")&&d.gravity>50&&a.push(`\u{1F6A8} GRAVITY ANOMALY: \`${dt.relative(e,d.filePath)}\` has high gravity (${d.gravity.toFixed(0)}) but is classified as ${h.layer}. Consider promoting to Core Logic.`)}for(let d of c){let h=dt.isAbsolute(d)?d:dt.join(e,d),m=t.exports.findByFile(h);m.length>10&&a.push(`\u{1F388} ENTRY BLOAT: \`${dt.relative(e,d)}\` exports ${m.length} symbols. Entry handlers should be thin interfaces.`)}let u=`# \u{1F575}\uFE0F Architectural Scout Report
|
|
687
742
|
|
|
688
743
|
`;return o.length===0&&a.length===0?u+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
|
|
689
744
|
`:(o.length>0&&(u+=`## \u274C Structural Violations
|
|
@@ -692,128 +747,128 @@ ${u}
|
|
|
692
747
|
`),a.length>0&&(u+=`## \u26A0\uFE0F Architectural Warnings
|
|
693
748
|
`,a.forEach(d=>u+=`- ${d}
|
|
694
749
|
`),u+=`
|
|
695
|
-
`)),{content:[{type:"text",text:u}]}}async function
|
|
696
|
-
\u{1F3D7}\uFE0F Architecture Summary for ${
|
|
750
|
+
`)),{content:[{type:"text",text:u}]}}async function Xa(s,e,t){let n=e?Za.resolve(process.cwd(),e):process.cwd();if(s==="init"){w.info('Running full initialization (same as "index --force")...'),await ie(n,void 0,!0,!0);return}if(s==="tree"){w.info('For tree view, please use the "tree" command.');return}if(s==="topography"){await ie(n);let i=N.getInstance(n),r=kt(i,n);console.log(`
|
|
751
|
+
\u{1F3D7}\uFE0F Architecture Summary for ${Za.basename(n)}
|
|
697
752
|
`),console.log(`Detected Pattern: **${r.pattern}** (Confidence: ${r.patternConfidence.toFixed(0)}%)`),r.insights.length>0&&(console.log(`
|
|
698
753
|
Insights:`),r.insights.forEach(l=>console.log(`- ${l}`))),console.log(`
|
|
699
754
|
Layer Distribution:`);let o=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],a=Object.values(r.layers).reduce((l,p)=>l+p.count,0),c=l=>{switch(l){case"Entry":return"\u{1F6AA}";case"Logic":return"\u2699\uFE0F";case"Data":return"\u{1F4BE}";case"Utility":return"\u{1F527}";case"Infrastructure":return"\u{1F3D7}\uFE0F";case"Test":return"\u{1F9EA}";case"Types":return"\u{1F4DD}";default:return"\u2753"}};o.forEach(l=>{let p=r.layers[l],u=a>0?(p.count/a*100).toFixed(1):"0.0";console.log(`${c(l)} ${l.padEnd(14)} | ${p.count.toString().padStart(5)} files | ${u}%`)}),console.log(`
|
|
700
755
|
Top Files by Layer:`),o.forEach(l=>{let p=r.layers[l];p.count!==0&&(console.log(`
|
|
701
|
-
${c(l)} ${l}`),p.topFiles.forEach(u=>{console.log(` - ${u.path} (${u.confidence}% conf)`),u.signals.length>0&&console.log(` \u2514\u2500 ${u.signals.slice(0,1).join(", ")}`)}))});return}if(s==="scout"){let i=await
|
|
702
|
-
`),o=new Array(r.length).fill(0);for(let d=0;d<r.length;d++){let h=r[d].toLowerCase(),m=0,f=0;for(let
|
|
756
|
+
${c(l)} ${l}`),p.topFiles.forEach(u=>{console.log(` - ${u.path} (${u.confidence}% conf)`),u.signals.length>0&&console.log(` \u2514\u2500 ${u.signals.slice(0,1).join(", ")}`)}))});return}if(s==="scout"){let i=await Qa({repoPath:n});console.log(i.content[0].text);return}if(s==="hologram"){let i=new Ae(n);console.log(JSON.stringify(i.getSnapshot(),null,2));return}w.error(`Unknown recon mode: ${s}. Available: init, topography, scout, hologram`)}import Mn from"path";Y();var Ct=class s{static extractKeywords(e){if(!e)return[];let t=new Set(["the","and","for","with","from","this","that","into","onto","http","https","www","com","org","net","api"]),i=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>2&&!t.has(r));return Array.from(new Set(i))}static calculateKeywordCoverageFromKeywords(e,t){if(!e||!t||t.length===0)return 0;let n=e.toLowerCase();return t.filter(r=>n.includes(r)).length/t.length}static calculateKeywordCoverage(e,t){return s.calculateKeywordCoverageFromKeywords(e,s.extractKeywords(t))}static extractSnippet(e,t,n=300){if(!e||!t)return"";let i=s.extractKeywords(t);if(i.length===0)return e.slice(0,n)+"...";let r=e.split(`
|
|
757
|
+
`),o=new Array(r.length).fill(0);for(let d=0;d<r.length;d++){let h=r[d].toLowerCase(),m=0,f=0;for(let S of i)h.includes(S)&&(m++,f++);(h.includes("export ")||h.includes("class ")||h.includes("function ")||h.includes("interface "))&&(m+=1),o[d]=f*10+m}let a=0,c=-1,l=5;for(let d=0;d<=r.length-l;d++){let h=0;for(let m=0;m<l;m++)h+=o[d+m];h>c&&(c=h,a=d)}if(c<=0)return e.slice(0,n).trim()+"...";let u=r.slice(a,a+l).join(`
|
|
703
758
|
`).trim();return a>0&&(u=`...
|
|
704
759
|
`+u),a+l<r.length&&(u=u+`
|
|
705
|
-
...`),u.length>n?u.slice(0,n)+"...":u}static calculateLexicalScore(e,t){if(!e||!t)return 0;let n=s.extractKeywords(t);if(n.length===0)return 0;let i=0,r=e.toLowerCase();for(let o of n)if(r.includes(o)){i+=1;let a=new RegExp(`\\b${o}`,"gi"),c=r.match(a);c&&(i+=Math.min(c.length*.2,2)),new RegExp(`(class|function|export|interface|enum|type)\\s+${o}`,"i").test(e)&&(i+=1.5)}return i/n.length}};
|
|
760
|
+
...`),u.length>n?u.slice(0,n)+"...":u}static calculateLexicalScore(e,t){if(!e||!t)return 0;let n=s.extractKeywords(t);if(n.length===0)return 0;let i=0,r=e.toLowerCase();for(let o of n)if(r.includes(o)){i+=1;let a=new RegExp(`\\b${o}`,"gi"),c=r.match(a);c&&(i+=Math.min(c.length*.2,2)),new RegExp(`(class|function|export|interface|enum|type)\\s+${o}`,"i").test(e)&&(i+=1.5)}return i/n.length}};qe();Y();G();var It=w.child({module:"clean-sweep"}),Ys=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=N.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){It.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();It.info({orphanCount:n.length},"Found orphaned logs");for(let o of n)o.file_path&&this.files.exists(o.file_path)?(this.intentLogs.markAsLapsed(o.id),t++,It.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,It.debug({logId:o.id},"Deleted orphaned log"));let i=this.intentLogs.findLogsForMissingFiles();for(let o of i)this.intentLogs.delete(o.id),e++;let r=this.intentLogs.findRecentDecisionActivity(1e3).length;return It.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},Ks=class{lambda;constructor(e=.01){this.lambda=e}calculateScore(e,t){let i=(Math.floor(Date.now()/1e3)-t)/(3600*24),r=Math.exp(-this.lambda*i);return e*r}scoreResults(e){return e.map(t=>({...t,decayed_score:this.calculateScore(t.score,t.created_at)}))}},Qs=class{missions;constructor(e){let{missions:t}=N.getInstance(e);this.missions=t}findColdMissions(){let e=Math.floor(Date.now()/1e3)-604800,t=this.missions.findColdMissions(e,10);return It.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},Wi=class{pruner;scorer;compactor;constructor(e){this.pruner=new Ys(e),this.scorer=new Ks,this.compactor=new Qs(e)}runMaintenance(){It.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return It.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};Y();G();var ec=w.child({module:"lineage-service"}),In=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=qo(this.repoPath,e);if(t.length===0)return[];let{missions:n}=N.getInstance(this.repoPath),r=n.findByCommitShas(t).map(o=>o.id);return r.length>0&&ec.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return ec.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var qu={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},Xe=class{static classify(e,t){let n=e.toLowerCase();if(t?.content){let i=t.content;if(i.includes("describe(")||i.includes("test(")||i.includes("it(")||i.includes("expect(")||i.includes('from "@jest/globals"')||i.includes('from "vitest"'))return"Virtual"}return t?.exports&&(t.exports.some(r=>r.kind==="ClassDeclaration"||r.kind==="Class")||t.exports.length>5),n.includes("/dist/")||n.includes("/build/")||n.includes("/.generated/")||n.includes("/node_modules/")||n.endsWith(".map")||n.endsWith(".log")?"Phantom":n.includes("/test/")||n.includes("/tests/")||n.includes("/__tests__/")||n.includes("/__mocks__/")||n.includes(".spec.")||n.includes(".test.")||n.includes("/e2e/")||n.includes("/test-utils/")?"Virtual":n.includes("/examples/")||n.includes("/fixtures/")||n.includes("/mocks/")||n.includes("/stories/")||n.includes("/samples/")||n.includes("/docs/")?"Intel":n.includes("/src/")||n.includes("/lib/")||n.includes("/app/")||n.includes("/core/")||n.includes("/logic/")||n.includes("/domain/")||n.includes("/services/")||n.includes("/controllers/")||n.includes("/handlers/")||n.includes("/repositories/")||n.includes("/models/")||n.includes("/packages/")&&!n.includes("/packages/config/")||n.includes("/backends/")||t?.exports&&(t.exports.some(i=>i.kind==="ClassDeclaration"||i.kind==="Class")||t.exports.length>5)?"Solid":"Liquid"}static mapClassificationToTier(e){let t=e.toLowerCase();return t==="service"||t==="repository"||t==="model"||t==="controller"||t==="handler"||t==="component"||t==="hook"||t==="titanium"||t==="solid"?"Solid":t==="test"||t==="iron"||t==="virtual"?"Virtual":t==="lead"||t==="intel"?"Intel":t==="ghost"||t==="error"||t==="phantom"?"Phantom":"Liquid"}static getMultiplier(e,t){let n=t?this.mapClassificationToTier(t):this.classify(e);return qu[n]}};G();function Vu(s,e){let t=[];for(let n=0;n<=e.length;n++)t[n]=[n];for(let n=0;n<=s.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=s.length;i++)e.charAt(n-1)===s.charAt(i-1)?t[n][i]=t[n-1][i-1]:t[n][i]=Math.min(t[n-1][i-1]+1,t[n][i-1]+1,t[n-1][i]+1);return t[e.length][s.length]}function Ju(s,e){let t=Vu(s.toLowerCase(),e.toLowerCase()),n=Math.max(s.length,e.length);return Math.round((n-t)/n*100)}function tc(s){let e=[],t="";for(let n=0;n<s.length;n++){let i=s[n],r=i>="A"&&i<="Z",o=i>="a"&&i<="z";r&&t.length>0?(e.push(t),t=i):o||r?t+=i:t.length>0&&(e.push(t),t="")}return t.length>0&&e.push(t),e}function Yu(s,e){let t=tc(e),n=s.toLowerCase();if(t.map(o=>o[0].toLowerCase()).join("")===n)return!0;let r=0;for(let o of t){if(r>=s.length)break;let a=o.toLowerCase();if(a.startsWith(n.slice(r))){r=s.length;break}a[0]===n[r]&&r++}return r===s.length}function Ku(s,e){return tc(e).map(i=>i[0].toLowerCase()).join("")===s.toLowerCase()}function Qu(s,e){let t=s.toLowerCase(),n=e.toLowerCase();if(s===e)return{matchType:"exact",score:100};if(t===n)return{matchType:"exact-case-insensitive",score:98};if(n.startsWith(t))return{matchType:"prefix",score:90+s.length/e.length*8};if(n.endsWith(t))return{matchType:"suffix",score:80+s.length/e.length*8};if(n.includes(t)){let r=s.length/e.length,o=n.indexOf(t)/e.length;return{matchType:"substring",score:70+r*10-o*5}}return Ku(s,e)?{matchType:"acronym",score:75}:Yu(s,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:Ju(s,e)*.6}}function Ln(s,e,t=50,n=5){let i=[];for(let r of e){let{matchType:o,score:a}=Qu(s,r);if(a>=t){let l={exact:1e3,"exact-case-insensitive":900,prefix:800,suffix:700,substring:600,acronym:550,"camel-case":500,levenshtein:100}[o]+a;i.push({match:r,score:a,matchType:o,rank:l})}}return i.sort((r,o)=>o.rank!==r.rank?o.rank-r.rank:o.score!==r.score?o.score-r.score:r.match.length-o.match.length),i.slice(0,n)}rn();var Lt=class s{constructor(e){this.repoPath=e}get filesRepo(){return N.getInstance(this.repoPath).files}get exportsRepo(){return N.getInstance(this.repoPath).exports}get intentLogsRepo(){return N.getInstance(this.repoPath).intentLogs}static normalizeFileType(e){if(e==null)return;let t=Array.isArray(e)?e:e.split(",").map(n=>n.trim().replace(/^\./,""));return t.filter(Boolean).length?t:void 0}static matchesFilters(e,t,n,i){if(t.fileType?.length){let r=e.replace(/^.*\./,"").toLowerCase();if(!t.fileType.some(o=>o.toLowerCase()===r))return!1}if(t.layer!=null||t.excludeLayers&&t.excludeLayers.length>0){let r=i!=null?Xe.mapClassificationToTier(i):Xe.classify(e);if(t.layer!=null&&r!==t.layer||t.excludeLayers?.includes(r))return!1}return!0}async searchByPath(e,t,n,i,r,o=!1){let a=this.extractPathKeywords(e),c=this.isLikelySymbolQuery(e),l=this.filesRepo.findByPathKeywords(a,Math.min((t??50)*(r?ve.FILTERED_QUERY_LIMIT_MULTIPLIER:1),Fe.MAX_LIMIT)).map(_=>({..._,source:"path",keywordHits:this.countPathKeywordHits(_.path,a),relevance:this.scorePathResult(_.path,a,"path",c)}));r&&(l=l.filter(_=>s.matchesFilters(_.path,i,_.mtime,_.classification))),c&&a.length>=3&&(l=l.filter(_=>_.source==="symbol"||_.keywordHits>=2));let p=this.findSymbolBackedPaths(e,a,t*3),u=new Set(l.map(_=>_.path));for(let _ of p){if(u.has(_))continue;let E=this.filesRepo.findByPath(_);E&&(r&&!s.matchesFilters(E.path,i,E.mtime,E.classification)||(l.push({...E,source:"symbol",keywordHits:this.countPathKeywordHits(E.path,a),relevance:this.scorePathResult(E.path,a,"symbol",c)}),u.add(_)))}l.sort((_,E)=>E.relevance-_.relevance),r||(l=l.slice(0,Math.min(t*4,Fe.MAX_LIMIT)));let d=l.length;if(d===0)return{content:[{type:"text",text:`No indexed files match path/filename: "${e}".
|
|
706
761
|
|
|
707
|
-
If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};let h=
|
|
762
|
+
If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};let h=_=>_.replace(this.repoPath,"").replace(/^\//,"");if(o){let E=new Ae(this.repoPath).getSection("gravity"),R=new Map;if(E?.hotspots)for(let v of E.hotspots){let I=R.get(v.filePath)||0;R.set(v.filePath,I+v.gravity)}let T=l.map(v=>{let I=R.get(v.path)||0,$=v.classification?Xe.mapClassificationToTier(v.classification):Xe.classify(v.path);return{...v,gravity:I,layer:$}});T.sort((v,I)=>I.gravity!==v.gravity?I.gravity-v.gravity:I.relevance!==v.relevance?I.relevance-v.relevance:v.path.localeCompare(I.path));let k=T.slice(n,n+t),F=n+t<d;if(k.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${d}.`}]};let B=F?`
|
|
708
763
|
> **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"";return{content:[{type:"text",text:`# Resolved paths: "${e}" (Ranked by Gravity)
|
|
709
764
|
|
|
710
|
-
Showing ${k.length} of ${d} file(s) (offset: ${n}, limit: ${t})${
|
|
765
|
+
Showing ${k.length} of ${d} file(s) (offset: ${n}, limit: ${t})${B}
|
|
711
766
|
|
|
712
|
-
`+k.map((
|
|
767
|
+
`+k.map((v,I)=>{let $=v.gravity>50?" \u269B\uFE0F":v.gravity>0?" \u2022":"",P=v.gravity>0?` [G:${Math.round(v.gravity)}]`:"",U=v.source==="symbol"?" [via symbol]":"";return`${n+I+1}. \`${h(v.path)}\` (${v.layer})${$}${P}${U}`}).join(`
|
|
713
768
|
`)+`
|
|
714
769
|
|
|
715
|
-
> **Legend**: \u269B\uFE0F = High-gravity hotspot (>50), \u2022 = Has gravity, G = Gravity score`}]}}let m=l.slice(n,n+t),f=n+t<d;if(m.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${d}.`}]};let
|
|
770
|
+
> **Legend**: \u269B\uFE0F = High-gravity hotspot (>50), \u2022 = Has gravity, G = Gravity score`}]}}let m=l.slice(n,n+t),f=n+t<d;if(m.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${d}.`}]};let S=f?`
|
|
716
771
|
> **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"";return{content:[{type:"text",text:`# Resolved paths: "${e}"
|
|
717
772
|
|
|
718
|
-
Showing ${m.length} of ${d} file(s) (offset: ${n}, limit: ${t})${
|
|
773
|
+
Showing ${m.length} of ${d} file(s) (offset: ${n}, limit: ${t})${S}
|
|
719
774
|
|
|
720
|
-
`+m.map((
|
|
721
|
-
`)}]}}async searchByConcept(e,t,n,i,r,o=!1,a){
|
|
722
|
-
> **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",
|
|
723
|
-
> _Compact mode: snippets omitted_`:
|
|
724
|
-
> _Adaptive compression enabled under token budget._`:"",
|
|
725
|
-
> _${
|
|
775
|
+
`+m.map((_,E)=>{let R=_.source==="symbol"?" [via symbol]":"";return`${n+E+1}. \`${h(_.path)}\`${_.classification?` (${_.classification})`:""}${R}`}).join(`
|
|
776
|
+
`)}]}}async searchByConcept(e,t,n,i,r,o=!1,a){w.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let c=await ys(e),l=R=>R.replace(this.repoPath,"").replace(/^\//,""),p=Ct.extractKeywords(e),u=this.classifyConceptQuery(e,p),d=this.getConceptConfidenceFloor(u.profile),h=this.getIntentConfidenceFloor(u.profile),m=Math.min(Math.max((t+n)*2,t),Fe.MAX_LIMIT),f=await this.findConceptMatches(e,c,i,r,m,0),S=c?await this.findIntentLogMatches(c,5):[],y=f.filter(R=>(R.score||0)>=d),_=f.filter(R=>(R.score||0)<d),E=S.filter(R=>(R.score||0)>=h);if(y.length>0){let R=y.length,T=y.slice(n,n+t),F=n+t<R?`
|
|
777
|
+
> **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",B=o?`
|
|
778
|
+
> _Compact mode: snippets omitted_`:R>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",M=a&&a>0?`
|
|
779
|
+
> _Adaptive compression enabled under token budget._`:"",v=_.length>0?`
|
|
780
|
+
> _${_.length} lower-confidence candidate(s) were suppressed below the ${Math.round(d*100)}% evidence floor._`:"",I=`# Semantic Concept Search: "${e}"
|
|
726
781
|
|
|
727
|
-
Showing ${
|
|
782
|
+
Showing ${T.length} of ${R} high-confidence file(s) (offset: ${n}, limit: ${t})${F}${B}${M}${v}
|
|
728
783
|
|
|
729
|
-
`,
|
|
730
|
-
> \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${
|
|
731
|
-
> **Rationale**: ${
|
|
784
|
+
`,P=new Ae(this.repoPath).getSection("gravity"),U=new Map;if(P?.hotspots)for(let D of P.hotspots)U.set(D.filePath,D.gravity);let A=T.map((D,J)=>{let z=l(D.path),g=Math.round((D.score||0)*100),O=U.get(D.path)?" \u269B\uFE0F":"";return`${n+J+1}. \`${z}\`${O} (${g}% evidence) - ${D.summary||"No summary"}`}),H=T.map((D,J)=>{let z=l(D.path),g=Math.round((D.score||0)*100),x=U.get(D.path),O=x?" \u269B\uFE0F **CORE**":"",C=x&&x>50?`
|
|
785
|
+
> \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${x.toFixed(0)}). Modifications may have significant architectural impact.`:"",W=`## ${n+J+1}. ${z}${O} (${g}% Evidence Match)
|
|
786
|
+
> **Rationale**: ${D.rationale}${C}
|
|
732
787
|
|
|
733
|
-
`+(
|
|
788
|
+
`+(D.snippet?`**Matched Snippet**:
|
|
734
789
|
\`\`\`typescript
|
|
735
|
-
${
|
|
790
|
+
${D.snippet}
|
|
736
791
|
\`\`\`
|
|
737
792
|
|
|
738
|
-
`:"")+`**Summary**: ${
|
|
739
|
-
`;return{index:n+
|
|
740
|
-
`);else if(a&&a>0){let
|
|
741
|
-
`),
|
|
793
|
+
`:"")+`**Summary**: ${D.summary||"No summary available"}
|
|
794
|
+
`;return{index:n+J+1,relativePath:z,matchPct:g,gravity:x,text:W}}),L="";if(o)L=I+A.join(`
|
|
795
|
+
`);else if(a&&a>0){let D=Math.max(80,Math.floor(a*.12)),J=this.estimateTokenCount(I),z=[],g=[];for(let x of H){let O=this.estimateTokenCount(x.text),C=J+O<=a-D;if(z.length<2||C)z.push(x.text),J+=O;else{let W=x.gravity?" \u269B\uFE0F":"";g.push(`${x.index}. \`${x.relativePath}\`${W} (${x.matchPct}% Evidence Match)`)}}L=I+z.join(`
|
|
796
|
+
`),g.length>0&&(L+=`
|
|
742
797
|
|
|
743
|
-
### Folded Lower-Relevance Matches (${
|
|
798
|
+
### Folded Lower-Relevance Matches (${g.length})
|
|
744
799
|
_Expanded blocks omitted to stay within token budget._
|
|
745
|
-
`+
|
|
746
|
-
`))}else L=
|
|
747
|
-
`);if(
|
|
800
|
+
`+g.join(`
|
|
801
|
+
`))}else L=I+H.map(D=>D.text).join(`
|
|
802
|
+
`);if(E.length>0){let D=`
|
|
748
803
|
|
|
749
804
|
---
|
|
750
|
-
## Intent Vectors (${
|
|
805
|
+
## Intent Vectors (${E.length} matching decision(s))
|
|
751
806
|
|
|
752
|
-
`+
|
|
753
|
-
> ${
|
|
807
|
+
`+E.map((z,g)=>{let x=Math.round((z.score||0)*100),O=z.symbolName?` \`${z.symbolName}\``:"",C=z.missionId?` [Mission #${z.missionId}]`:"",W=z.content.length>200?z.content.slice(0,200)+"...":z.content;return o?`${g+1}. **[${z.type}]**${O}${C} (${x}%) - ${W}`:`### ${g+1}. [${z.type}]${O}${C} (${x}% Evidence Match)
|
|
808
|
+
> ${W}
|
|
754
809
|
`}).join(`
|
|
755
|
-
`),
|
|
810
|
+
`),J=`
|
|
756
811
|
|
|
757
812
|
---
|
|
758
|
-
## Intent Vectors (${
|
|
813
|
+
## Intent Vectors (${E.length} matching decision(s))
|
|
759
814
|
|
|
760
|
-
`+
|
|
761
|
-
`)+(
|
|
762
|
-
> Additional intent matches folded by token budget.`:"");a&&a>0&&this.estimateTokenCount(L+
|
|
815
|
+
`+E.slice(0,2).map((z,g)=>{let x=Math.round((z.score||0)*100),O=z.symbolName?` \`${z.symbolName}\``:"",C=z.missionId?` [Mission #${z.missionId}]`:"";return`${g+1}. **[${z.type}]**${O}${C} (${x}%)`}).join(`
|
|
816
|
+
`)+(E.length>2?`
|
|
817
|
+
> Additional intent matches folded by token budget.`:"");a&&a>0&&this.estimateTokenCount(L+D)>a?L+=J:L+=D}return{content:[{type:"text",text:L}]}}if(n===0){let R=this.filesRepo.getStats(),T=e.toLowerCase().split(/\s+/),k=this.filesRepo.findByPathKeywords(T,t);if(r&&(k=k.filter(F=>s.matchesFilters(F.path,i,F.mtime,F.classification))),k.length>0)return{content:[{type:"text",text:`# Concept Search: "${e}"
|
|
763
818
|
|
|
764
|
-
\u26A0\uFE0F No high-confidence semantic matches cleared the ${Math.round(d*100)}% evidence floor (${
|
|
819
|
+
\u26A0\uFE0F No high-confidence semantic matches cleared the ${Math.round(d*100)}% evidence floor (${R.withSummary}/${R.total} summaries indexed).
|
|
765
820
|
|
|
766
821
|
Found ${k.length} file(s) with matching paths:
|
|
767
822
|
|
|
768
|
-
`+k.map((
|
|
769
|
-
`)}]};if(
|
|
823
|
+
`+k.map((B,M)=>`${M+1}. \`${l(B.path)}\` (${B.classification||"Unknown"})`).join(`
|
|
824
|
+
`)}]};if(_.length>0){let F=_.slice(0,Math.min(3,t)).map((B,M)=>{let v=Math.round((B.score||0)*100);return`${M+1}. \`${l(B.path)}\` (${v}% evidence) - ${B.summary||"No summary"}`}).join(`
|
|
770
825
|
`);return{content:[{type:"text",text:`# Semantic Concept Search: "${e}"
|
|
771
826
|
|
|
772
827
|
No high-confidence semantic matches cleared the evidence floor (${Math.round(d*100)}% required for ${u.profile} queries).
|
|
773
828
|
|
|
774
829
|
Low-confidence candidates were suppressed instead of being presented as relevant matches:
|
|
775
|
-
${
|
|
776
|
-
${
|
|
830
|
+
${F?`
|
|
831
|
+
${F}
|
|
777
832
|
|
|
778
833
|
`:`
|
|
779
834
|
`}Try adding distinctive identifiers, narrowing the concept, or using shadow_search_symbol({ query: "${e}", repoPath }).`}]}}}return{content:[{type:"text",text:`No high-confidence files found matching concept: "${e}"
|
|
780
835
|
|
|
781
|
-
Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}async searchBySymbol(e,t,n,i,r,o="any"){let a=e.toLowerCase(),c=
|
|
836
|
+
Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}async searchBySymbol(e,t,n,i,r,o="any"){let a=e.toLowerCase(),c=v=>v.replace(this.repoPath,"").replace(/^\//,""),l=this.buildFtsQuery(e,o),p;try{p=this.exportsRepo.findFts(l,t+50)}catch{p=this.exportsRepo.findByPartialName(e,t+50)}if(p.length===0){let v=this.exportsRepo.getAllNames(5e3),I=e.trim().split(/\s+/).filter(P=>P.length>0);if(I.length>1){let P=new Map;for(let A of I){let H=Ln(A,v,40,20);for(let L of H){let D=P.get(L.match);D?(D.terms.push(A),D.bestScore=Math.max(D.bestScore,L.score)):P.set(L.match,{terms:[A],bestScore:L.score})}}let U=Array.from(P.entries()).sort((A,H)=>H[1].terms.length!==A[1].terms.length?H[1].terms.length-A[1].terms.length:H[1].bestScore-A[1].bestScore).slice(0,10);if(U.length>0){let A=U.map(([H,L])=>{let D=L.terms.join(", ");return` \u2022 \`${H}\` (matches: ${D}, ${Math.round(L.bestScore)}%)`}).join(`
|
|
782
837
|
`);return{content:[{type:"text",text:`No symbols found matching all terms: "${e}"
|
|
783
838
|
|
|
784
839
|
**Partial matches:**
|
|
785
|
-
${
|
|
840
|
+
${A}
|
|
786
841
|
|
|
787
|
-
\u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let
|
|
842
|
+
\u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let P=Ln(e,v,50,5);if(P.length>0){let U=P.map(A=>` \u2022 \`${A.match}\` (${Math.round(A.score)}% ${A.matchType} match)`).join(`
|
|
788
843
|
`);return{content:[{type:"text",text:`No symbols found matching: "${e}"
|
|
789
844
|
|
|
790
845
|
**Did you mean?**
|
|
791
|
-
${
|
|
846
|
+
${U}
|
|
792
847
|
|
|
793
848
|
\u{1F4A1} Try shadow_search_symbol with fuzzy, or shadow_search_concept for semantic search.`}]}}}return{content:[{type:"text",text:`No symbols found matching: "${e}"
|
|
794
849
|
|
|
795
|
-
\u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(
|
|
796
|
-
`);
|
|
797
|
-
`).trim()}let
|
|
850
|
+
\u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(v=>{let I=this.filesRepo.findByPath(v.file_path);return s.matchesFilters(v.file_path,i,I?.mtime,I?.classification)}));let u=new In(this.repoPath),d=new Ae(this.repoPath),h=u.getAncestorMissionIds(),m=be(this.repoPath)||void 0,f=this.exportsRepo.getGravityMap(h,m),S=d.getSection("gravity"),y=new Map;if(S?.hotspots)for(let v of S.hotspots)y.set(`${v.filePath}::${v.symbol}`,v.gravity);let _="\u{1F525}",E="\u26A1",R="\u269B\uFE0F",T=p.map((v,I)=>{let $=f[v.id],P=y.get(`${v.file_path}::${v.name}`),U=this.filesRepo.findByPath(v.file_path),A=Xe.getMultiplier(v.file_path,U?.classification),H=(ve.SCORE_BASE-I)*A;$&&(H+=$.score*ve.SCORE_BASE),P&&(H+=P*ve.SCORE_BASE*ve.GRAVITY_STRUCTURAL_WEIGHT),v.name.toLowerCase()===a&&(H+=ve.EXACT_MATCH_BONUS*A);let L=U?.mtime;if(L!=null){let J=L>1e10?L/1e3:L,z=(Date.now()/1e3-J)/Rs.SECONDS_PER_DAY;z<ve.RECENT_FILE_THRESHOLD_DAYS?H+=ve.RECENT_FILE_BOOST:z<ve.OLDER_FILE_THRESHOLD_DAYS&&(H+=ve.OLDER_FILE_BOOST)}let D=[];return $&&D.push(...$.reasons),P&&D.push(`Structural Hotspot (Gravity: ${P.toFixed(1)})`),{...v,activeGravity:$,structuralGravity:P,sortScore:H,reasons:D}}).sort((v,I)=>I.sortScore-v.sortScore).slice(n,n+t),k=p.length,F=n+t<k,B=T.map((v,I)=>{let $=c(v.file_path),P=this.filesRepo.getContent(v.file_path),U="";if(P){let L=P.split(`
|
|
851
|
+
`);U=L.slice(Math.max(0,v.start_line-2),Math.min(L.length,v.start_line+3)).join(`
|
|
852
|
+
`).trim()}let A=[];v.activeGravity&&(v.activeGravity.reasons.some(L=>L.includes("Working Set"))?A.push(_):v.activeGravity.reasons.some(L=>L.includes("Recent Intent"))&&A.push(E)),v.structuralGravity&&A.push(R);let H=A.length>0?` ${A.join("")}`:"";return{relPath:$,name:v.name,kind:v.kind,signature:v.signature,line:v.start_line,snippet:U,badgeStr:H,gravityReasons:v.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
|
|
798
853
|
|
|
799
|
-
Showing ${
|
|
854
|
+
Showing ${B.length} matching symbol(s)${F?` (use offset=${n+t} for more)`:""}:
|
|
800
855
|
|
|
801
|
-
`+
|
|
802
|
-
**File**: \`${
|
|
803
|
-
`;return
|
|
804
|
-
`),
|
|
805
|
-
`),
|
|
856
|
+
`+B.map((v,I)=>{let $=`## ${n+I+1}. \`${v.name}\` (${v.kind})${v.badgeStr}
|
|
857
|
+
**File**: \`${v.relPath}:${v.line}\`
|
|
858
|
+
`;return v.gravityReasons&&($+=`> *${v.gravityReasons.join(", ")}*
|
|
859
|
+
`),v.signature&&($+=`**Signature**: \`${v.signature}\`
|
|
860
|
+
`),v.snippet&&($+=`
|
|
806
861
|
\`\`\`typescript
|
|
807
|
-
${
|
|
862
|
+
${v.snippet}
|
|
808
863
|
\`\`\`
|
|
809
|
-
`)
|
|
810
|
-
`)}]}}async findConceptMatches(e,t,n,i,r,o=0){let a=
|
|
811
|
-
${
|
|
812
|
-
${re||""}`,_),Sn=1;if(re){let tn=/\b(class|function|const|let|var|enum)\s+\w+/.test(re);if(/export\s+/.test(re)&&!tn){let Dc=re.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");/\b(class|function|const|let|var|enum)\s+\w+/.test(Dc)||(Sn=.1)}}let Lc=he?.08:we?.1:He>0||ze>0||G?.14:m?.22:.18;if(xe&&z<=Lc&&!G)continue;if(h.length>0&&He===0&&!G){if(m){if(!he&&(_t===0&&ze===0&&z<.4||_t<=1&&ze===0&&z<.34||_t===1&&z<.3))continue}else if(_t===0&&z<.24)continue}if(m&&!he&&ze===0&&_t<=1&&z<.3&&!G||i&&!s.matchesFilters(C.path,n,C.mtime,C.classification))continue;let $c=C.mtime>2e9?Math.floor(C.mtime/1e3):C.mtime,Ac=Math.floor(Date.now()/1e3)-ls.SECONDS_PER_YEAR,Bi=We.getMultiplier(C.path,C.classification),Pc=xe?l.calculateScore(z,$c||Ac):0,Ye=(v.fusedScore*60+Pc*.2)*Bi,wn=d[C.path],Mc=C.classification?We.mapClassificationToTier(C.classification):We.classify(C.path,{content:re??void 0}),ve=`vector_rank: ${this.formatRank(v.vectorRank)} | symbol_vector_rank: ${this.formatRank(v.symbolVectorRank)} | fts_rank: ${this.formatRank(v.ftsRank)} | fused_score: ${v.fusedScore.toFixed(6)} | query_profile: ${g.profile} | Similarity: ${(z*100).toFixed(0)}%, Tier: ${Mc}${Bi!==1?` (${Bi}x)`:""}`;if(he&&(ve+=" | SymbolHint"),j&&(ve+=` | SymbolVec: ${j.symbolName}`),He>0&&(Ye+=He*ge.LEXICAL_WEIGHT,ve+=` | Lexical: +${He.toFixed(1)}`),h.length>0)if(Mt>0){let tn=m?Mt*.45:Mt*.35;Ye+=tn,ve+=` | Keywords: ${(Mt*100).toFixed(0)}%`}else ve+=" | Keywords: 0%",m&&!G&&(Ye*=.55,ve+=" (penalty)");if(_.length>0)if(ze>0){let tn=m?ze*.8:ze*.35;Ye+=tn,ve+=` | Phrases: ${(ze*100).toFixed(0)}%`}else m&&!G&&(Ye*=.72,ve+=" | Phrases: 0% (penalty)");wn&&(Ye+=wn.score,ve+=` | \u{1F525} Gravity: +${wn.score.toFixed(1)} (${wn.reasons.join(", ")})`),m&&this.isGenericConceptPath(C.path)&&_t<=1&&ze===0&&!G&&(Ye*=.75,ve+=" | Generic path penalty"),Sn<1&&(Ye*=Sn,ve+=` | \u{1F4C9} Barrel: x${Sn}`);let Nc=re?ht.extractSnippet(re,e):void 0;A.push({path:C.path,summary:C.summary||"",score:z,fusedScore:v.fusedScore,vectorRank:v.vectorRank,ftsRank:v.ftsRank,decayedScore:Ye,rationale:ve,snippet:Nc}),H.set(C.path,{lexicalScore:He,keywordCoverage:Mt,matchedKeywordCount:_t,phraseCoverage:ze,similarity:z,hasFtsSignal:G,hasSymbolHint:he,hasSymbolVectorSignal:we,lexicalConfirm:0,identifierOverlap:0,isGenericPath:this.isGenericConceptPath(C.path)})}if(A.length>0&&h.length>0){let v=this.exportsRepo.findByFiles(A.map(B=>B.path)),C=new Map;for(let B of v){let j=C.get(B.file_path)??[];j.push(B.name),C.set(B.file_path,j)}for(let B of A){let j=this.calculateIdentifierOverlap(h,C.get(B.path)??[]),J=H.get(B.path);if(J&&(J.identifierOverlap=j),j>0){let z=m?j*.8:j*.25;B.decayedScore=(B.decayedScore||0)+z,B.rationale+=` | Symbols: ${(j*100).toFixed(0)}%`}else m&&this.isGenericConceptPath(B.path)&&(B.decayedScore=(B.decayedScore||0)*.82,B.rationale+=" | Symbols: 0% (generic penalty)")}}let F=new Map;for(let v of A){let C=v.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();C&&C.length>3&&(F.has(C)||F.set(C,[]),F.get(C).push(v))}for(let[v,C]of F.entries())if(new Set(C.map(j=>j.path.split(".").pop())).size>1)for(let j of C)j.decayedScore=(j.decayedScore||0)+.15,j.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${v}')`;if(m&&A.length>1){let v=Math.min(Math.max(r*4,ge.FILTERED_QUERY_LIMIT_MULTIPLIER*20),A.length),C=[...A].sort((j,J)=>(J.decayedScore||0)-(j.decayedScore||0)).slice(0,v),B=this.computeBm25LikeConfirmation(C.map(j=>j.path),h);for(let j of C){let J=B.get(j.path)||0,z=H.get(j.path);if(z&&(z.lexicalConfirm=J),J>0){let G=Math.min(.95,J*.18);j.decayedScore=(j.decayedScore||0)+G,j.rationale+=` | LexConfirm: +${G.toFixed(2)}`}else z&&z.matchedKeywordCount<=1&&z.phraseCoverage===0&&z.lexicalScore===0&&(j.decayedScore=(j.decayedScore||0)*.85,j.rationale+=" | LexConfirm: 0 (penalty)")}}for(let v of A){let C=H.get(v.path);C&&(v.score=this.calculateConceptEvidenceScore({profile:g.profile,queryKeywordCount:h.length,...C}),v.rationale+=` | Evidence: ${(v.score*100).toFixed(0)}%`)}return A.sort((v,C)=>(C.decayedScore||0)-(v.decayedScore||0)),A.slice(o,o+Math.min(r,ke.MAX_LIMIT))}async findIntentLogMatches(e,t){return(await this.intentLogsRepo.findSemanticMatches(e,t)).map(i=>({id:i.id,missionId:i.mission_id,type:i.type,content:i.content,symbolName:i.symbol_name,filePath:i.file_path,score:i.similarity,decayedScore:i.similarity,rationale:`Similarity: ${(i.similarity*100).toFixed(0)}%`,createdAt:i.created_at}))}buildFtsQuery(e,t){let n=e.trim();if(!n.includes(" "))return`"${n}" OR ${n}*`;let i=n.split(/\s+/).filter(r=>r.length>0);switch(t){case"exact":return`"${n}"`;case"all":return i.map(r=>`${r}*`).join(" ");default:return i.map(r=>`${r}*`).join(" OR ")}}extractPathKeywords(e){let t=e.trim();if(!t)return[];let n=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_\/.-]+/).map(r=>r.trim()).filter(r=>r.length>=2),i=new Set;i.add(t.toLowerCase());for(let r of n)i.add(r);return Array.from(i)}isLikelySymbolQuery(e){let t=e.trim();return!t||/[\/\\]/.test(t)?!1:/^[a-z]+(?:[A-Z][a-z0-9]+)+$/.test(t)||!t.includes(" ")&&/[A-Z]/.test(t)}countPathKeywordHits(e,t){let n=e.toLowerCase(),i=t.filter(o=>o.length>=3),r=0;for(let o of i)n.includes(o.toLowerCase())&&(r+=1);return r}scorePathResult(e,t,n,i){let o=this.countPathKeywordHits(e,t)*10;n==="symbol"&&(o+=25);let a=e.toLowerCase(),c=a.includes("/.env")||a.endsWith(".env")||a.endsWith(".yml")||a.endsWith(".yaml")||a.endsWith(".json")||a.endsWith(".md");return i&&c&&(o-=20),i&&a.includes("/tests/")&&(o-=15),o}findSymbolBackedPaths(e,t,n){let i=e.trim().toLowerCase();if(!i)return[];if(/[\/\\]/.test(i))return[];let r=Array.from(new Set([i,...t])).filter(c=>c.length>=3).slice(0,6);if(r.length===0)return[];let o=r.flatMap(c=>{let l=c===i?Math.min(n,60):Math.min(n,30);return this.exportsRepo.findByPartialName(c,l)}),a=new Map;for(let c of o){let l=c.name.toLowerCase(),p=0;l===i&&(p+=6),l.startsWith(i)&&(p+=4),l.includes(i)&&(p+=3);for(let d of t)d.length>=3&&l.includes(d)&&(p+=1);if(p===0)continue;let u=a.get(c.file_path)||0;p>u&&a.set(c.file_path,p)}return Array.from(a.entries()).sort((c,l)=>l[1]-c[1]).slice(0,Math.min(n,ke.MAX_LIMIT)).map(([c])=>c)}rrfMerge(e,t,n,i){let r=new Map,o=i?.vectorWeight??1.2,a=i?.ftsWeight??.8,c=i?.symbolWeight??1.1,l=i?.symbolResults??[];for(let p of e){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.vectorRank=p.rank,u.fusedScore+=o/(n+p.rank),r.set(p.path,u)}for(let p of t){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.ftsRank=p.rank,u.fusedScore+=a/(n+p.rank),r.set(p.path,u)}for(let p of l){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.symbolVectorRank=p.rank,u.symbolName=p.symbolName,u.fusedScore+=c/(n+p.rank),r.set(p.path,u)}return Array.from(r.values()).sort((p,u)=>u.fusedScore-p.fusedScore)}formatRank(e){return e==null?"none":String(e)}getConceptConfidenceFloor(e){switch(e){case"identifier-heavy":return .33;case"lexical-heavy":return .38;case"semantic-exploratory":return .3;default:return .35}}getIntentConfidenceFloor(e){return Math.max(.28,this.getConceptConfidenceFloor(e)-.05)}calculateConceptEvidenceScore(e){let t=Math.min(1,e.lexicalConfirm/Math.max(1,e.queryKeywordCount*1.5)),n=e.profile==="semantic-exploratory"?.72:.58,i=e.profile==="lexical-heavy"?.16:.12,r=e.profile==="identifier-heavy"?.12:.08,o=e.similarity*n+Math.min(1,e.lexicalScore)*.08+e.keywordCoverage*.1+e.phraseCoverage*i+e.identifierOverlap*r+t*.08;return e.hasFtsSignal&&(o+=.04),e.hasSymbolHint?o+=.03:e.hasSymbolVectorSignal&&(o+=.02),e.matchedKeywordCount===0&&e.phraseCoverage===0&&e.lexicalScore===0?o*=e.hasFtsSignal||e.hasSymbolVectorSignal?.72:.6:e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.88),e.isGenericPath&&e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.85),e.queryKeywordCount===0&&(o*=.75),Math.max(0,Math.min(.97,o))}estimateTokenCount(e){return e?Math.ceil(e.length/4):0}classifyConceptQuery(e,t){let n=e.trim(),i=t.length,r=/\b[a-z]+[A-Z][A-Za-z0-9]*\b/.test(n),o=/\b[a-z0-9]+_[a-z0-9_]+\b/i.test(n),a=/[/.:#()]/.test(n),c=i<=1&&!n.includes(" "),l=n.includes('"')||i>=5&&n.split(/\s+/).length>=6;return r||o||a&&i>=2?{profile:"identifier-heavy",rrfK:45,vectorWeight:1,ftsWeight:.75,symbolWeight:1.45,channelMultiplier:5,lexicalWindowMultiplier:5,earlyRejectThreshold:.012}:l?{profile:"lexical-heavy",rrfK:55,vectorWeight:.95,ftsWeight:1.3,symbolWeight:1,channelMultiplier:7,lexicalWindowMultiplier:8,earlyRejectThreshold:.008}:c||i<=2?{profile:"semantic-exploratory",rrfK:70,vectorWeight:1.35,ftsWeight:.6,symbolWeight:.9,channelMultiplier:4,lexicalWindowMultiplier:4,earlyRejectThreshold:.018}:{profile:"balanced",rrfK:60,vectorWeight:1.15,ftsWeight:.9,symbolWeight:1.2,channelMultiplier:6,lexicalWindowMultiplier:6,earlyRejectThreshold:.01}}extractOrderedConceptTerms(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>=3):[]}buildNgrams(e,t,n){if(e.length<t)return[];let i=[];for(let r=t;r<=n&&!(e.length<r);r++)for(let o=0;o<=e.length-r;o++)i.push(e.slice(o,o+r).join(" "));return Array.from(new Set(i))}calculatePhraseCoverage(e,t){if(!e||t.length===0)return 0;let n=e.toLowerCase(),i=0;for(let r of t)n.includes(r)&&(i+=1);return i/t.length}calculateIdentifierOverlap(e,t){if(e.length===0||t.length===0)return 0;let n=new Set(e.map(o=>o.toLowerCase())),i=new Set;for(let o of t){let a=o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(c=>c.trim()).filter(c=>c.length>=3);for(let c of a)i.add(c)}let r=0;for(let o of n)i.has(o)&&(r+=1);return r/n.size}isGenericConceptPath(e){let t=e.toLowerCase();return/(?:^|\/)(index|utils?|helpers?|common|shared|types?|constants?|models?)(?:\/|\.|$)/.test(t)}computeBm25LikeConfirmation(e,t){let n=Array.from(new Set(t.map(u=>u.toLowerCase()).filter(u=>u.length>=3)));if(e.length===0||n.length===0)return new Map;let i=new Set(n),r=[],o=new Map;for(let u of e){let h=(this.filesRepo.getContent(u)??"").toLowerCase().split(/[^a-z0-9_]+/).map(f=>f.trim()).filter(Boolean),m=new Map;for(let f of h)i.has(f)&&m.set(f,(m.get(f)||0)+1);for(let f of n)(m.get(f)||0)>0&&o.set(f,(o.get(f)||0)+1);r.push({path:u,frequencies:m,length:Math.max(h.length,1)})}let a=r.reduce((u,d)=>u+d.length,0)/Math.max(r.length,1),c=1.2,l=.75,p=new Map;for(let u of r){let d=0;for(let h of n){let m=u.frequencies.get(h)||0;if(m===0)continue;let f=o.get(h)||0,_=Math.log(1+(r.length-f+.5)/(f+.5)),g=m*(c+1)/(m+c*(1-l+l*(u.length/Math.max(a,1))));d+=_*g}p.set(u.path,d)}return p}collectConceptSymbolHintPaths(e,t){let n=Array.from(new Set(e.filter(r=>r.length>=4&&!this.isLowSignalConceptKeyword(r)))).slice(0,6);if(n.length===0)return new Set;let i=new Map;for(let r of n){let o=this.exportsRepo.findByPartialName(r,Math.min(t,80));for(let a of o){let c=a.name.toLowerCase(),l=0;c===r&&(l+=3),c.startsWith(r)&&(l+=2),c.includes(r)&&(l+=1),l!==0&&i.set(a.file_path,(i.get(a.file_path)||0)+l)}}return new Set(Array.from(i.entries()).sort((r,o)=>o[1]-r[1]).slice(0,Math.min(t,ke.MAX_LIMIT)).map(([r])=>r))}isLowSignalConceptKeyword(e){return new Set(["type","types","data","update","create","list","item","value","model","helper"]).has(e.toLowerCase())}};q();V();function ki(s){let{fileType:e,layer:t}=s,n={fileType:gt.normalizeFileType(e),layer:t},i=!!(n.fileType?.length||n.layer!=null);return{filters:n,hasFilters:i}}async function $a(s){let e=Ei(s.query??""),t={...s,query:e},n=qn();try{let{repoPath:i}=Ve(t),{query:r,limit:o=ke.DEFAULT_LIMIT,offset:a=0,compact:c=!1,tokenBudget:l}=t;await X(i);let{filters:p,hasFilters:u}=ki(t),h=await new gt(i).searchByConcept(r,o,a,p,u,c,l);try{let m=yi(i);if(m.status==="running"){let[f,_]=m.progress.split("/").map(Number),g=_>0?Math.round(f/_*100):0,b=`\u26A0\uFE0F Symbol embeddings still warming (${m.progress}, ${g}%) \u2014 symbol-level results may be incomplete. File-level results are fully available.
|
|
864
|
+
`),$}).join(`
|
|
865
|
+
`)}]}}async findConceptMatches(e,t,n,i,r,o=0){let a=be(this.repoPath)||void 0,l=new Wi(this.repoPath).getScorer(),u=new In(this.repoPath).getAncestorMissionIds(),d=this.filesRepo.getGravityMap(u,a),h=Ct.extractKeywords(e),m=h.length>=3,f=this.extractOrderedConceptTerms(e),S=this.buildNgrams(f,2,3),y=this.classifyConceptQuery(e,h),_=m?this.collectConceptSymbolHintPaths(h,Math.max(r*10,100)):new Set,E=Math.min(Math.max((r+o)*y.channelMultiplier,ve.FILTERED_QUERY_LIMIT_MULTIPLIER*20),Fe.MAX_LIMIT),R=Math.min(Math.max(E*4,200),4e3),[T,k,F]=await Promise.all([Promise.resolve(t?this.filesRepo.findWithEmbeddings():[]),Promise.resolve(this.filesRepo.findContentFts(e,E)),Promise.resolve(t?this.exportsRepo.findWithEmbeddings(R):[])]),B=[];if(t){for(let g of T)try{let x=JSON.parse(g.embedding),O=qn(t,x);B.push({row:g,similarity:O,vectorRank:0})}catch{}B.sort((g,x)=>x.similarity-g.similarity);for(let g=0;g<B.length;g++)B[g].vectorRank=g+1}let M=[];if(t){for(let g of F)if(g.embedding)try{let x=JSON.parse(g.embedding),O=qn(t,x);if(O<=0)continue;M.push({row:g,similarity:O,symbolVectorRank:0})}catch{}M.sort((g,x)=>x.similarity-g.similarity);for(let g=0;g<M.length;g++)M[g].symbolVectorRank=g+1}let v=new Map;for(let g of T)v.set(g.path,g);for(let g of k)v.has(g.path)||v.set(g.path,g);let I=new Map,$=[],P=new Set;for(let g of M.slice(0,R)){let x=g.row.file_path,O=I.get(x);if((!O||g.similarity>O.similarity)&&I.set(x,{similarity:g.similarity,symbolRank:g.symbolVectorRank,symbolName:g.row.name}),P.has(x))continue;let C=v.get(x);C||(C=this.filesRepo.findByPath(x),C&&v.set(x,C)),C&&($.push({path:x,rank:g.symbolVectorRank,score:g.similarity,row:C,symbolName:g.row.name}),P.add(x))}let U=this.rrfMerge(B.slice(0,E).map(g=>({path:g.row.path,rank:g.vectorRank,score:g.similarity,row:g.row})),k.slice(0,E).map((g,x)=>({path:g.path,rank:x+1,bm25Rank:g.bm25_rank,row:g})),y.rrfK,{vectorWeight:y.vectorWeight,ftsWeight:y.ftsWeight,symbolWeight:y.symbolWeight,symbolResults:$.slice(0,E)});if(U.length===0)return[];let A=new Map;for(let g of B)A.set(g.row.path,g.similarity);let H=Math.min(U.length,Math.max(r*y.lexicalWindowMultiplier,40)),L=new Set(U.slice(0,H).map(g=>g.path)),D=[],J=new Map;for(let g of U){let x=g.row,O=A.get(x.path)||0,C=I.get(x.path),W=C?.similarity||0,j=Math.max(O,W),Z=g.ftsRank!==null,he=g.symbolVectorRank!==null||!!C,Ce=g.vectorRank!==null||he,Ie=_.has(x.path),gt=L.has(x.path)||Z||Ie||he;if(!gt&&g.fusedScore<y.earlyRejectThreshold&&j<.18&&!i)continue;let fe=gt?this.filesRepo.getContent(x.path):null,$e=ve.ENABLE_LEXICAL_SCORING&&fe?Ct.calculateLexicalScore(fe,e):0,Pe=fe?Ct.calculateKeywordCoverageFromKeywords(fe,h):0,Ee=h.length>0?Math.round(Pe*h.length):0,K=this.calculatePhraseCoverage(`${x.path}
|
|
866
|
+
${x.summary||""}
|
|
867
|
+
${fe||""}`,S),ae=1;if(fe){let ce=/\b(class|function|const|let|var|enum)\s+\w+/.test(fe);if(/export\s+/.test(fe)&&!ce){let at=fe.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");/\b(class|function|const|let|var|enum)\s+\w+/.test(at)||(ae=.1)}}let ot=Ie?.08:he?.1:$e>0||K>0||Z?.14:m?.22:.18;if(Ce&&j<=ot&&!Z)continue;if(h.length>0&&$e===0&&!Z){if(m){if(!Ie&&(Ee===0&&K===0&&j<.4||Ee<=1&&K===0&&j<.34||Ee===1&&j<.3))continue}else if(Ee===0&&j<.24)continue}if(m&&!Ie&&K===0&&Ee<=1&&j<.3&&!Z||i&&!s.matchesFilters(x.path,n,x.mtime,x.classification))continue;let yt=x.mtime>2e9?Math.floor(x.mtime/1e3):x.mtime,Be=Math.floor(Date.now()/1e3)-Rs.SECONDS_PER_YEAR,Ue=Xe.getMultiplier(x.path,x.classification),$t=Ce?l.calculateScore(j,yt||Be):0,we=(g.fusedScore*60+$t*.2)*Ue,V=d[x.path],q=x.classification?Xe.mapClassificationToTier(x.classification):Xe.classify(x.path,{content:fe??void 0}),X=`vector_rank: ${this.formatRank(g.vectorRank)} | symbol_vector_rank: ${this.formatRank(g.symbolVectorRank)} | fts_rank: ${this.formatRank(g.ftsRank)} | fused_score: ${g.fusedScore.toFixed(6)} | query_profile: ${y.profile} | Similarity: ${(j*100).toFixed(0)}%, Tier: ${q}${Ue!==1?` (${Ue}x)`:""}`;if(Ie&&(X+=" | SymbolHint"),C&&(X+=` | SymbolVec: ${C.symbolName}`),$e>0&&(we+=$e*ve.LEXICAL_WEIGHT,X+=` | Lexical: +${$e.toFixed(1)}`),h.length>0)if(Pe>0){let ce=m?Pe*.45:Pe*.35;we+=ce,X+=` | Keywords: ${(Pe*100).toFixed(0)}%`}else X+=" | Keywords: 0%",m&&!Z&&(we*=.55,X+=" (penalty)");if(S.length>0)if(K>0){let ce=m?K*.8:K*.35;we+=ce,X+=` | Phrases: ${(K*100).toFixed(0)}%`}else m&&!Z&&(we*=.72,X+=" | Phrases: 0% (penalty)");V&&(we+=V.score,X+=` | \u{1F525} Gravity: +${V.score.toFixed(1)} (${V.reasons.join(", ")})`),m&&this.isGenericConceptPath(x.path)&&Ee<=1&&K===0&&!Z&&(we*=.75,X+=" | Generic path penalty"),ae<1&&(we*=ae,X+=` | \u{1F4C9} Barrel: x${ae}`);let xe=fe?Ct.extractSnippet(fe,e):void 0;D.push({path:x.path,summary:x.summary||"",score:j,fusedScore:g.fusedScore,vectorRank:g.vectorRank,ftsRank:g.ftsRank,decayedScore:we,rationale:X,snippet:xe}),J.set(x.path,{lexicalScore:$e,keywordCoverage:Pe,matchedKeywordCount:Ee,phraseCoverage:K,similarity:j,hasFtsSignal:Z,hasSymbolHint:Ie,hasSymbolVectorSignal:he,lexicalConfirm:0,identifierOverlap:0,isGenericPath:this.isGenericConceptPath(x.path)})}if(D.length>0&&h.length>0){let g=this.exportsRepo.findByFiles(D.map(O=>O.path)),x=new Map;for(let O of g){let C=x.get(O.file_path)??[];C.push(O.name),x.set(O.file_path,C)}for(let O of D){let C=this.calculateIdentifierOverlap(h,x.get(O.path)??[]),W=J.get(O.path);if(W&&(W.identifierOverlap=C),C>0){let j=m?C*.8:C*.25;O.decayedScore=(O.decayedScore||0)+j,O.rationale+=` | Symbols: ${(C*100).toFixed(0)}%`}else m&&this.isGenericConceptPath(O.path)&&(O.decayedScore=(O.decayedScore||0)*.82,O.rationale+=" | Symbols: 0% (generic penalty)")}}let z=new Map;for(let g of D){let x=g.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();x&&x.length>3&&(z.has(x)||z.set(x,[]),z.get(x).push(g))}for(let[g,x]of z.entries())if(new Set(x.map(C=>C.path.split(".").pop())).size>1)for(let C of x)C.decayedScore=(C.decayedScore||0)+.15,C.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${g}')`;if(m&&D.length>1){let g=Math.min(Math.max(r*4,ve.FILTERED_QUERY_LIMIT_MULTIPLIER*20),D.length),x=[...D].sort((C,W)=>(W.decayedScore||0)-(C.decayedScore||0)).slice(0,g),O=this.computeBm25LikeConfirmation(x.map(C=>C.path),h);for(let C of x){let W=O.get(C.path)||0,j=J.get(C.path);if(j&&(j.lexicalConfirm=W),W>0){let Z=Math.min(.95,W*.18);C.decayedScore=(C.decayedScore||0)+Z,C.rationale+=` | LexConfirm: +${Z.toFixed(2)}`}else j&&j.matchedKeywordCount<=1&&j.phraseCoverage===0&&j.lexicalScore===0&&(C.decayedScore=(C.decayedScore||0)*.85,C.rationale+=" | LexConfirm: 0 (penalty)")}}for(let g of D){let x=J.get(g.path);x&&(g.score=this.calculateConceptEvidenceScore({profile:y.profile,queryKeywordCount:h.length,...x}),g.rationale+=` | Evidence: ${(g.score*100).toFixed(0)}%`)}return D.sort((g,x)=>(x.decayedScore||0)-(g.decayedScore||0)),D.slice(o,o+Math.min(r,Fe.MAX_LIMIT))}async findIntentLogMatches(e,t){return(await this.intentLogsRepo.findSemanticMatches(e,t)).map(i=>({id:i.id,missionId:i.mission_id,type:i.type,content:i.content,symbolName:i.symbol_name,filePath:i.file_path,score:i.similarity,decayedScore:i.similarity,rationale:`Similarity: ${(i.similarity*100).toFixed(0)}%`,createdAt:i.created_at}))}buildFtsQuery(e,t){let n=e.trim();if(!n.includes(" "))return`"${n}" OR ${n}*`;let i=n.split(/\s+/).filter(r=>r.length>0);switch(t){case"exact":return`"${n}"`;case"all":return i.map(r=>`${r}*`).join(" ");default:return i.map(r=>`${r}*`).join(" OR ")}}extractPathKeywords(e){let t=e.trim();if(!t)return[];let n=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_\/.-]+/).map(r=>r.trim()).filter(r=>r.length>=2),i=new Set;i.add(t.toLowerCase());for(let r of n)i.add(r);return Array.from(i)}isLikelySymbolQuery(e){let t=e.trim();return!t||/[\/\\]/.test(t)?!1:/^[a-z]+(?:[A-Z][a-z0-9]+)+$/.test(t)||!t.includes(" ")&&/[A-Z]/.test(t)}countPathKeywordHits(e,t){let n=e.toLowerCase(),i=t.filter(o=>o.length>=3),r=0;for(let o of i)n.includes(o.toLowerCase())&&(r+=1);return r}scorePathResult(e,t,n,i){let o=this.countPathKeywordHits(e,t)*10;n==="symbol"&&(o+=25);let a=e.toLowerCase(),c=a.includes("/.env")||a.endsWith(".env")||a.endsWith(".yml")||a.endsWith(".yaml")||a.endsWith(".json")||a.endsWith(".md");return i&&c&&(o-=20),i&&a.includes("/tests/")&&(o-=15),o}findSymbolBackedPaths(e,t,n){let i=e.trim().toLowerCase();if(!i)return[];if(/[\/\\]/.test(i))return[];let r=Array.from(new Set([i,...t])).filter(c=>c.length>=3).slice(0,6);if(r.length===0)return[];let o=r.flatMap(c=>{let l=c===i?Math.min(n,60):Math.min(n,30);return this.exportsRepo.findByPartialName(c,l)}),a=new Map;for(let c of o){let l=c.name.toLowerCase(),p=0;l===i&&(p+=6),l.startsWith(i)&&(p+=4),l.includes(i)&&(p+=3);for(let d of t)d.length>=3&&l.includes(d)&&(p+=1);if(p===0)continue;let u=a.get(c.file_path)||0;p>u&&a.set(c.file_path,p)}return Array.from(a.entries()).sort((c,l)=>l[1]-c[1]).slice(0,Math.min(n,Fe.MAX_LIMIT)).map(([c])=>c)}rrfMerge(e,t,n,i){let r=new Map,o=i?.vectorWeight??1.2,a=i?.ftsWeight??.8,c=i?.symbolWeight??1.1,l=i?.symbolResults??[];for(let p of e){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.vectorRank=p.rank,u.fusedScore+=o/(n+p.rank),r.set(p.path,u)}for(let p of t){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.ftsRank=p.rank,u.fusedScore+=a/(n+p.rank),r.set(p.path,u)}for(let p of l){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.symbolVectorRank=p.rank,u.symbolName=p.symbolName,u.fusedScore+=c/(n+p.rank),r.set(p.path,u)}return Array.from(r.values()).sort((p,u)=>u.fusedScore-p.fusedScore)}formatRank(e){return e==null?"none":String(e)}getConceptConfidenceFloor(e){switch(e){case"identifier-heavy":return .33;case"lexical-heavy":return .38;case"semantic-exploratory":return .3;default:return .35}}getIntentConfidenceFloor(e){return Math.max(.28,this.getConceptConfidenceFloor(e)-.05)}calculateConceptEvidenceScore(e){let t=Math.min(1,e.lexicalConfirm/Math.max(1,e.queryKeywordCount*1.5)),n=e.profile==="semantic-exploratory"?.72:.58,i=e.profile==="lexical-heavy"?.16:.12,r=e.profile==="identifier-heavy"?.12:.08,o=e.similarity*n+Math.min(1,e.lexicalScore)*.08+e.keywordCoverage*.1+e.phraseCoverage*i+e.identifierOverlap*r+t*.08;return e.hasFtsSignal&&(o+=.04),e.hasSymbolHint?o+=.03:e.hasSymbolVectorSignal&&(o+=.02),e.matchedKeywordCount===0&&e.phraseCoverage===0&&e.lexicalScore===0?o*=e.hasFtsSignal||e.hasSymbolVectorSignal?.72:.6:e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.88),e.isGenericPath&&e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.85),e.queryKeywordCount===0&&(o*=.75),Math.max(0,Math.min(.97,o))}estimateTokenCount(e){return e?Math.ceil(e.length/4):0}classifyConceptQuery(e,t){let n=e.trim(),i=t.length,r=/\b[a-z]+[A-Z][A-Za-z0-9]*\b/.test(n),o=/\b[a-z0-9]+_[a-z0-9_]+\b/i.test(n),a=/[/.:#()]/.test(n),c=i<=1&&!n.includes(" "),l=n.includes('"')||i>=5&&n.split(/\s+/).length>=6;return r||o||a&&i>=2?{profile:"identifier-heavy",rrfK:45,vectorWeight:1,ftsWeight:.75,symbolWeight:1.45,channelMultiplier:5,lexicalWindowMultiplier:5,earlyRejectThreshold:.012}:l?{profile:"lexical-heavy",rrfK:55,vectorWeight:.95,ftsWeight:1.3,symbolWeight:1,channelMultiplier:7,lexicalWindowMultiplier:8,earlyRejectThreshold:.008}:c||i<=2?{profile:"semantic-exploratory",rrfK:70,vectorWeight:1.35,ftsWeight:.6,symbolWeight:.9,channelMultiplier:4,lexicalWindowMultiplier:4,earlyRejectThreshold:.018}:{profile:"balanced",rrfK:60,vectorWeight:1.15,ftsWeight:.9,symbolWeight:1.2,channelMultiplier:6,lexicalWindowMultiplier:6,earlyRejectThreshold:.01}}extractOrderedConceptTerms(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>=3):[]}buildNgrams(e,t,n){if(e.length<t)return[];let i=[];for(let r=t;r<=n&&!(e.length<r);r++)for(let o=0;o<=e.length-r;o++)i.push(e.slice(o,o+r).join(" "));return Array.from(new Set(i))}calculatePhraseCoverage(e,t){if(!e||t.length===0)return 0;let n=e.toLowerCase(),i=0;for(let r of t)n.includes(r)&&(i+=1);return i/t.length}calculateIdentifierOverlap(e,t){if(e.length===0||t.length===0)return 0;let n=new Set(e.map(o=>o.toLowerCase())),i=new Set;for(let o of t){let a=o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(c=>c.trim()).filter(c=>c.length>=3);for(let c of a)i.add(c)}let r=0;for(let o of n)i.has(o)&&(r+=1);return r/n.size}isGenericConceptPath(e){let t=e.toLowerCase();return/(?:^|\/)(index|utils?|helpers?|common|shared|types?|constants?|models?)(?:\/|\.|$)/.test(t)}computeBm25LikeConfirmation(e,t){let n=Array.from(new Set(t.map(u=>u.toLowerCase()).filter(u=>u.length>=3)));if(e.length===0||n.length===0)return new Map;let i=new Set(n),r=[],o=new Map;for(let u of e){let h=(this.filesRepo.getContent(u)??"").toLowerCase().split(/[^a-z0-9_]+/).map(f=>f.trim()).filter(Boolean),m=new Map;for(let f of h)i.has(f)&&m.set(f,(m.get(f)||0)+1);for(let f of n)(m.get(f)||0)>0&&o.set(f,(o.get(f)||0)+1);r.push({path:u,frequencies:m,length:Math.max(h.length,1)})}let a=r.reduce((u,d)=>u+d.length,0)/Math.max(r.length,1),c=1.2,l=.75,p=new Map;for(let u of r){let d=0;for(let h of n){let m=u.frequencies.get(h)||0;if(m===0)continue;let f=o.get(h)||0,S=Math.log(1+(r.length-f+.5)/(f+.5)),y=m*(c+1)/(m+c*(1-l+l*(u.length/Math.max(a,1))));d+=S*y}p.set(u.path,d)}return p}collectConceptSymbolHintPaths(e,t){let n=Array.from(new Set(e.filter(r=>r.length>=4&&!this.isLowSignalConceptKeyword(r)))).slice(0,6);if(n.length===0)return new Set;let i=new Map;for(let r of n){let o=this.exportsRepo.findByPartialName(r,Math.min(t,80));for(let a of o){let c=a.name.toLowerCase(),l=0;c===r&&(l+=3),c.startsWith(r)&&(l+=2),c.includes(r)&&(l+=1),l!==0&&i.set(a.file_path,(i.get(a.file_path)||0)+l)}}return new Set(Array.from(i.entries()).sort((r,o)=>o[1]-r[1]).slice(0,Math.min(t,Fe.MAX_LIMIT)).map(([r])=>r))}isLowSignalConceptKeyword(e){return new Set(["type","types","data","update","create","list","item","value","model","helper"]).has(e.toLowerCase())}};G();Y();function zi(s){let{fileType:e,layer:t}=s,n={fileType:Lt.normalizeFileType(e),layer:t},i=!!(n.fileType?.length||n.layer!=null);return{filters:n,hasFilters:i}}async function nc(s){let e=$i(s.query??""),t={...s,query:e},n=ri();try{let{repoPath:i}=st(t),{query:r,limit:o=Fe.DEFAULT_LIMIT,offset:a=0,compact:c=!1,tokenBudget:l}=t;await ie(i);let{filters:p,hasFilters:u}=zi(t),h=await new Lt(i).searchByConcept(r,o,a,p,u,c,l);try{let m=Li(i);if(m.status==="running"){let[f,S]=m.progress.split("/").map(Number),y=S>0?Math.round(f/S*100):0,_=`\u26A0\uFE0F Symbol embeddings still warming (${m.progress}, ${y}%) \u2014 symbol-level results may be incomplete. File-level results are fully available.
|
|
813
868
|
|
|
814
|
-
`;h.content?.[0]?.type==="text"&&(h.content[0].text=
|
|
869
|
+
`;h.content?.[0]?.type==="text"&&(h.content[0].text=_+h.content[0].text)}}catch{}return Zu(i,r,"concept"),n(),h}catch(i){return w.error({error:i,args:s},"Concept Search failed"),n(),await Qt(),{content:[{type:"text",text:`Concept Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Zu(s,e,t){try{let n=N.getInstance(s),i=be(s);n.searchHistory.record(e,t,i)}catch(n){let i=be(s);w.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),Qt()}}G();Y();async function Zs(s){let e=$i(s.query??""),t={...s,query:e},n=ri();try{let{repoPath:i}=st(t),{query:r,limit:o=Fe.DEFAULT_LIMIT,offset:a=0,matchMode:c="any"}=t;await ie(i);let{filters:l,hasFilters:p}=zi(t),d=await new Lt(i).searchBySymbol(r,o,a,l,p,c);return Xu(i,r,"symbol"),n(),d}catch(i){return w.error({error:i,args:s},"Symbol Search failed"),n(),await Qt(),{content:[{type:"text",text:`Symbol Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Xu(s,e,t){try{let n=N.getInstance(s),i=be(s);n.searchHistory.record(e,t,i)}catch(n){let i=be(s);w.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),Qt()}}Y();G();import ln from"path";function ic(s,e){let t=s.findContentByToken(e,100);return{count:t.length,files:t}}async function sc(s){let{repoPath:e,query:t,key:n="",kind:i,limit:r=50,showUsage:o=!1}=s,a=n||t;if(!a&&!i)return{content:[{type:"text",text:'Error: Either "key" or "kind" parameter is required.'}]};await ie(e);let c=N.getInstance(e),{configs:l,files:p}=c;if(a){w.info({repoPath:e,key:a},"Searching for config key in DB...");let m=l.findByKey(a,r);if(m.length===0)return{content:[{type:"text",text:`No configuration found for key: ${a}`}]};if(o){let y=m.map(T=>{let k=ic(p,T.key),F=k.count===0?"\u26A0\uFE0F ORPHANED":`\u2713 ${k.count} usage(s)`;return{file:ln.relative(e,T.file_path),key:T.key,value:T.value,kind:T.kind,usageCount:k.count,usageFiles:k.files.slice(0,5).map(B=>ln.relative(e,B)),status:F}});y.sort((T,k)=>T.usageCount===0&&k.usageCount>0?-1:k.usageCount===0&&T.usageCount>0?1:T.usageCount-k.usageCount);let _=y.filter(T=>T.usageCount===0).length;return{content:[{type:"text",text:(_>0?`# Configuration Search: "${a}" (with Usage Analysis)
|
|
815
870
|
|
|
816
|
-
\u26A0\uFE0F **${
|
|
871
|
+
\u26A0\uFE0F **${_} orphaned var(s)** (defined but never used in code)
|
|
817
872
|
|
|
818
873
|
Found ${m.length} match(es):
|
|
819
874
|
|
|
@@ -821,48 +876,48 @@ Found ${m.length} match(es):
|
|
|
821
876
|
|
|
822
877
|
Found ${m.length} match(es), all in use:
|
|
823
878
|
|
|
824
|
-
`)+
|
|
825
|
-
**${
|
|
826
|
-
> Used in: ${
|
|
879
|
+
`)+y.map(T=>{let k=`## ${T.file} (${T.kind}) ${T.status}
|
|
880
|
+
**${T.key}**: \`${T.value}\``;return T.usageCount>0&&T.usageFiles.length>0&&(k+=`
|
|
881
|
+
> Used in: ${T.usageFiles.map(F=>`\`${F}\``).join(", ")}${T.usageCount>5?` (+${T.usageCount-5} more)`:""}`),k}).join(`
|
|
827
882
|
|
|
828
|
-
`)}]}}let f=m.map(
|
|
883
|
+
`)}]}}let f=m.map(y=>({file:ln.relative(e,y.file_path),key:y.key,value:y.value,kind:y.kind}));return{content:[{type:"text",text:`# Configuration Search: "${a}"
|
|
829
884
|
|
|
830
885
|
Found ${m.length} match(es):
|
|
831
886
|
|
|
832
|
-
`+f.map(
|
|
833
|
-
**${
|
|
887
|
+
`+f.map(y=>`## ${y.file} (${y.kind})
|
|
888
|
+
**${y.key}**: \`${y.value}\``).join(`
|
|
834
889
|
|
|
835
|
-
`)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let u=l.findByKind(i||null,r);if(o){let m=u.map(
|
|
890
|
+
`)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let u=l.findByKind(i||null,r);if(o){let m=u.map(_=>{let E=ic(p,_.key);return{file:ln.relative(e,_.file_path),key:_.key,value:_.value,kind:_.kind,usageCount:E.count,usageFiles:E.files.slice(0,3).map(R=>ln.relative(e,R)),status:E.count===0?"ORPHANED":"in-use"}});m.sort((_,E)=>_.usageCount===0&&E.usageCount>0?-1:E.usageCount===0&&_.usageCount>0?1:_.usageCount-E.usageCount);let f=m.filter(_=>_.usageCount===0).length,S=m.length,y=`# Config Discovery (${i||"all"}) with Usage Analysis
|
|
836
891
|
|
|
837
|
-
`;return
|
|
892
|
+
`;return y+=`**Summary**: ${S} config(s) found, ${f} orphaned
|
|
838
893
|
|
|
839
|
-
`,f>0&&(
|
|
840
|
-
`,
|
|
841
|
-
`),
|
|
894
|
+
`,f>0&&(y+=`## \u26A0\uFE0F Orphaned (${f})
|
|
895
|
+
`,y+=m.filter(_=>_.usageCount===0).map(_=>`- \`${_.key}\` in ${_.file}`).join(`
|
|
896
|
+
`),y+=`
|
|
842
897
|
|
|
843
|
-
`),
|
|
844
|
-
`,
|
|
845
|
-
`),u.length===r&&(
|
|
898
|
+
`),y+=`## \u2713 In Use (${S-f})
|
|
899
|
+
`,y+=m.filter(_=>_.usageCount>0).map(_=>{let E=_.usageFiles.length>0?`, used in ${_.usageFiles.map(R=>`\`${R}\``).join(", ")}${_.usageCount>3?` (+${_.usageCount-3} more)`:""}`:"";return`- \`${_.key}\`=\`${_.value}\` in \`${_.file}\` (${_.usageCount} usages${E})`}).join(`
|
|
900
|
+
`),u.length===r&&(y+=`
|
|
846
901
|
|
|
847
|
-
> Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:
|
|
902
|
+
> Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:y}]}}let d=u.map(m=>({...m,file:ln.relative(e,m.file_path)})),h=JSON.stringify(d,null,2);return u.length===r&&(h=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
|
|
848
903
|
|
|
849
|
-
`+h),h+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:h}]}}
|
|
850
|
-
import `)&&!n.startsWith("import ")||e&&
|
|
851
|
-
`),r=
|
|
852
|
-
export `);return t<=0?s:s.slice(0,t).trim()}async function
|
|
853
|
-
`)}catch{p=null}Array.isArray(l.exports)&&p&&(l.exports=l.exports.map(m=>{let f=typeof m.signature=="string"?m.signature:"",
|
|
904
|
+
`+h),h+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:h}]}}Y();Ut();import ed from"fs";import rc from"path";var td=new Set(["ClassDeclaration","FunctionDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","VariableDeclaration"]);function oc(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xs(s,e,t){let n=t.trim();return!!(!n||n.length>8e3||/^\w{1,4}\s+['"].*['"];?$/.test(n)&&!n.startsWith("export ")||n.includes(`
|
|
905
|
+
import `)&&!n.startsWith("import ")||e&&td.has(e)&&s&&!new RegExp(`\\b${oc(s)}\\b`).test(n))}function nd(s,e){let t=Math.max(0,(s.start_line||1)-1),n=Math.min(e.length,Math.max(t+1,(s.end_line||s.start_line||1)+1,t+120)),i=e.slice(t,n).join(`
|
|
906
|
+
`),r=We(i,s.kind);return r?r.length>800?`${r.slice(0,797)}...`:r:s.signature||""}function id(s,e,t){if(!s)return null;let n=oc(s),i=[];e==="TsTypeAliasDeclaration"&&i.push(new RegExp(`^\\s*export\\s+type\\s+${n}\\b`)),e==="TsInterfaceDeclaration"&&i.push(new RegExp(`^\\s*export\\s+interface\\s+${n}\\b`)),e==="FunctionDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:async\\s+)?function\\s+${n}\\b`)),e==="ClassDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:abstract\\s+)?class\\s+${n}\\b`)),e==="VariableDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`)),i.push(new RegExp(`\\b${n}\\b`));for(let r of i)for(let o=0;o<t.length;o++)if(r.test(t[o]))return o+1;return null}function sd(s,e,t){let n=Math.max(0,s-1);if(e==="TsTypeAliasDeclaration"||e==="VariableDeclaration"||e==="TsEnumDeclaration"){for(let i=n;i<t.length;i++){if(t[i].includes(";"))return i+1;if(/^\s*export\s+(type|interface|class|function|const|let|var)\b/.test(t[i])&&i>n)return i}return Math.min(t.length,s+20)}if(e==="TsInterfaceDeclaration"||e==="ClassDeclaration"||e==="FunctionDeclaration"){let i=0,r=!1;for(let o=n;o<t.length;o++){let a=t[o];for(let c of a)c==="{"?(i+=1,r=!0):c==="}"&&(i-=1);if(r&&i<=0)return o+1}return Math.min(t.length,s+120)}return Math.min(t.length,s+40)}function rd(s){return Array.isArray(s)?s.filter(e=>e.module!=="__type_reference__"):s}function od(s,e){return s?e==="TsTypeAliasDeclaration"?`type ${s}`:e==="TsInterfaceDeclaration"?`interface ${s}`:e==="FunctionDeclaration"?`function ${s}()`:e==="ClassDeclaration"?`class ${s}`:e==="VariableDeclaration"?`const ${s}`:`${e||"symbol"} ${s}`:e||"symbol"}function ad(s,e){if(!s||e!=="TsTypeAliasDeclaration"&&e!=="TsInterfaceDeclaration")return s;let t=s.indexOf(`
|
|
907
|
+
export `);return t<=0?s:s.slice(0,t).trim()}async function Hi(s){let{repoPath:e,filePath:t}=st(s);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=s.detailLevel||"signatures";await ie(e);let{files:i,exports:r}=N.getInstance(e),o=i.findByPath(t),a=rc.basename(t),c=/\.(ts|tsx|php|py|go)$/.test(a),l;c?l=await wn(t):l={exports:r.findByFile(t),imports:[]};let p=null;if(c)try{p=ed.readFileSync(t,"utf8").split(`
|
|
908
|
+
`)}catch{p=null}Array.isArray(l.exports)&&p&&(l.exports=l.exports.map(m=>{let f=typeof m.signature=="string"?m.signature:"",S=m.start_line??m.line??1,y=m.end_line??m.endLine??S;if(Xs(m.name||"",m.kind,f)){let E=id(m.name||"",m.kind,p),R=E??S,T=E?sd(R,m.kind,p):y,k=nd({name:m.name||"",kind:m.kind,signature:f,start_line:R,end_line:T},p),F=ad(k,m.kind),B=Xs(m.name||"",m.kind,F)?od(m.name||"",m.kind):F;return{...m,signature:B,start_line:R,end_line:T,line:R,endLine:T,members:Array.isArray(m.members)?m.members.filter(M=>{let v=typeof M.signature=="string"?M.signature:"";return!Xs(M.name||"",M.kind,v)}):m.members}}return m})),l.imports=rd(l.imports),n==="structure"?(l.exports=l.exports.map(m=>{let f={name:m.name,kind:m.kind,line:m.start_line,classification:m.classification};return m.members&&m.members.length>0?{...f,members:m.members.map(S=>({name:`${m.name}.${S.name}`,kind:S.kind,line:S.start_line}))}:f}),delete l.imports):n==="signatures"&&(l.exports=l.exports.map(m=>{let f={name:m.name,kind:m.kind,signature:m.signature,line:m.start_line,classification:m.classification,capabilities:JSON.parse(m.capabilities||"[]")};return m.members&&m.members.length>0?{...f,members:m.members.map(S=>({name:`${m.name}.${S.name}`,kind:S.kind,signature:S.signature,line:S.start_line}))}:f}),delete l.imports);let u=rc.relative(e,t),d=l.exports?.length||0,h="";return n==="structure"&&d>0?h=`
|
|
854
909
|
|
|
855
910
|
\u{1F4A1} Showing ${d} symbol names. For full signatures: shadow_inspect_file({ filePath: "${u}", detailLevel: "signatures" })`:n==="signatures"&&d>0&&(h=`
|
|
856
911
|
|
|
857
|
-
\u{1F4A1} Showing ${d} complete signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...l,fileDescription:o?.summary||"",classification:o?.classification&&o.classification!=="Unknown"?o.classification:
|
|
858
|
-
`),i=[],r=0;for(let u=0;u<Math.min(n.length,50);u++){let d=n[u].trim();if(d.startsWith("import ")||d.startsWith("from ")||d.startsWith("export ")&&d.includes(" from "))r=u+1;else if(d&&!d.startsWith("//")&&!d.startsWith("/*")&&!d.startsWith("*")&&d!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((u,d)=>u.startLine-d.startLine),a=0,c=0;for(let u of o)if(u.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${u.name} \u2501\u2501\u2501`);let d=n.slice(u.startLine-1,u.endLine);i.push(...d),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),c++}else{let d=u.signature||
|
|
859
|
-
`),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:c,siblingsFolded:a}}function
|
|
860
|
-
However, it likely exists inside: ${
|
|
861
|
-
Try: shadow_inspect_symbol({ symbolName: "${
|
|
912
|
+
\u{1F4A1} Showing ${d} complete signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...l,fileDescription:o?.summary||"",classification:o?.classification&&o.classification!=="Unknown"?o.classification:Bt(t,N.getInstance(e)).layer},null,2)+h}]}}Y();import ac from"path";import cd from"fs";function ld(s,e,t){let n=s.split(`
|
|
913
|
+
`),i=[],r=0;for(let u=0;u<Math.min(n.length,50);u++){let d=n[u].trim();if(d.startsWith("import ")||d.startsWith("from ")||d.startsWith("export ")&&d.includes(" from "))r=u+1;else if(d&&!d.startsWith("//")&&!d.startsWith("/*")&&!d.startsWith("*")&&d!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((u,d)=>u.startLine-d.startLine),a=0,c=0;for(let u of o)if(u.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${u.name} \u2501\u2501\u2501`);let d=n.slice(u.startLine-1,u.endLine);i.push(...d),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),c++}else{let d=u.signature||pd(n,u.startLine-1,u.kind);d&&(i.push(`${d}`),i.push(` /* implementation: ${u.lineCount} lines */`),i.push(""),a++)}let l=o[o.length-1];if(l)for(let u=l.endLine;u<n.length;u++){let d=n[u].trim();if(d==="}"||d==="};"){i.push(n[u]);break}else if(d&&!d.startsWith("//"))break}return{foldedSource:i.join(`
|
|
914
|
+
`),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:c,siblingsFolded:a}}function pd(s,e,t){let n=s[e];if(t.includes("Function")||t.includes("Method")||t.includes("Arrow")){let i="";for(let r=e;r<Math.min(e+5,s.length);r++)if(i+=s[r],i.includes("{")||i.includes("=>")){let o=i.indexOf("{");o>0&&(i=i.substring(0,o).trim());break}return i.trim()}return n}function ud(s,e=","){let t=[],n="",i=0,r=0,o=0,a=0,c=null,l=!1;for(let u of s){if(c){if(n+=u,l){l=!1;continue}if(u==="\\"){l=!0;continue}u===c&&(c=null);continue}if(u==='"'||u==="'"||u==="`"){c=u,n+=u;continue}if(u==="("?i++:u===")"?i=Math.max(0,i-1):u==="{"?r++:u==="}"?r=Math.max(0,r-1):u==="["?o++:u==="]"?o=Math.max(0,o-1):u==="<"?a++:u===">"&&(a=Math.max(0,a-1)),u===e&&i===0&&r===0&&o===0&&a===0){let d=n.trim();d&&t.push(d),n="";continue}n+=u}let p=n.trim();return p&&t.push(p),t}function dd(s){let e=s.indexOf("(");if(e<0)return null;let t=0;for(let n=e;n<s.length;n++){let i=s[n];if(i==="("&&t++,i===")"&&(t--,t===0))return{start:e,end:n}}return null}function Bi(s,e){let t=0,n=0,i=0,r=0,o=null,a=!1;for(let c=0;c<s.length;c++){let l=s[c];if(o){a?a=!1:l==="\\"?a=!0:l===o&&(o=null);continue}if(l==='"'||l==="'"||l==="`"){o=l;continue}if(l==="("?t++:l===")"?t=Math.max(0,t-1):l==="{"?n++:l==="}"?n=Math.max(0,n-1):l==="["?i++:l==="]"?i=Math.max(0,i-1):l==="<"?r++:l===">"&&(r=Math.max(0,r-1)),l===e&&t===0&&n===0&&i===0&&r===0)return c}return-1}function md(s){let t=s.trim(),n=!1;t.startsWith("...")&&(n=!0,t=t.slice(3).trim());let i=Bi(t,"="),r=i>=0,o=r?t.slice(0,i).trim():t,a=r?t.slice(i+1).trim():void 0,c=Bi(o,":"),l=(c>=0?o.slice(0,c):o).replace(/^(?:readonly\s+)?(?:public|private|protected)\s+/,"").trim(),p=l.includes("?"),u=l.replace(/\?/g,"").trim(),d=c>=0&&o.slice(c+1).trim()||null;return{name:u||"(anonymous)",type:d,optional:p,rest:n,hasDefault:r,...a?{defaultValue:a}:{}}}function hd(s,e){let t=s.slice(e+1).trim();if(!t)return null;let n=t.indexOf("=>");if(n>=0){let r=t.slice(0,n).trim(),o=Bi(r,":");if(o>=0){let c=r.slice(o+1).trim();if(c)return c}return t.slice(n+2).replace(/\{.*$/,"").trim()||null}let i=Bi(t,":");return i>=0&&t.slice(i+1).replace(/\{.*$/,"").trim()||null}function fd(s){let e=s.trim();if(!e)return[];if(e==="*")return["*"];if(e.startsWith("[")&&e.endsWith("]"))try{let n=JSON.parse(e);if(Array.isArray(n))return n.map(i=>String(i).trim()).filter(Boolean).map(i=>i.replace(/^['"`]|['"`]$/g,""))}catch{}return e.replace(/^\{|\}$/g,"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.replace(/^type\s+/,"")).map(n=>n.split(/\s+as\s+/i)[0]?.trim()||n).map(n=>n.replace(/^['"`]|['"`]$/g,""))}function gd(s,e,t){let n=s?.replace(/\s+/g," ").trim()||null,r=n?.match(/\b(public|private|protected)\b/)?.[1]||null,a=(n?.match(/\bfunction\s*\*?\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/^(?:export\s+)?(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\(/))?.[1]||e,c=n?dd(n):null,l=n&&c?n.slice(c.start+1,c.end):"",p=l?ud(l).map(md):[],u=n&&c?hd(n,c.end):null,d=n?.match(/(?:function\s+[A-Za-z_$][A-Za-z0-9_$]*|[A-Za-z_$][A-Za-z0-9_$]*)\s*(<[^>]+>)\s*\(/);return{raw:s,normalized:n,symbol:a,kind:t,visibility:r,isStatic:/\bstatic\b/.test(n||""),isAsync:/\basync\b/.test(n||""),isGenerator:/function\s*\*/.test(n||"")||/\*\s*[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(n||""),isArrowFunction:/=>/.test(n||""),typeParameters:d?.[1]||null,parameters:p,parameterCount:p.length,returnType:u}}function yd(s,e,t=5){let n=new Map;for(let o of s){let a=n.get(o.file_path)||{classification:o.classification||null,importedSymbols:new Set,wildcard:!1},c=fd(o.imported_symbols);(c.length===0||c.includes("*"))&&(a.wildcard=!0);for(let l of c)a.importedSymbols.add(l);!a.classification&&o.classification&&(a.classification=o.classification),n.set(o.file_path,a)}let i=Array.from(n.entries()).map(([o,a])=>({file:ac.relative(e,o),classification:a.classification,importedSymbols:a.importedSymbols.size>0?Array.from(a.importedSymbols).sort():["*"],wildcard:a.wildcard})),r=i.slice(0,Math.max(1,t));return{totalVerifiedCallers:i.length,showing:r.length,wildcardCallers:i.filter(o=>o.wildcard).length,topCallers:r.map(({wildcard:o,...a})=>a)}}async function pn(s){let{repoPath:e,filePath:t,resolver:n}=st(s),i=String(s.symbolName),r=s.context||"definition";if(t&&!n.isWithinRoot(t))return{content:[{type:"text",text:`Error: Access denied. Path ${t} is outside the repository root.`}],isError:!0};await ie(e);let o=N.getInstance(e),a=[];if(i.includes(".")){let[v,I]=i.split(".");a=o.exports.findMemberCandidates(v,I,t)}else a=o.exports.findDefinitionCandidates(i,t);if(a.length===0){let v=o.exports.findPotentialParents(i);if(v.length>0){let U=v.map(A=>`\`${A.name}\` (in ${n.getRelative(A.file_path)})`).join(", ");return{content:[{type:"text",text:`Symbol "${i}" not found as a top-level export.
|
|
915
|
+
However, it likely exists inside: ${U}.
|
|
916
|
+
Try: shadow_inspect_symbol({ symbolName: "${v[0].name}", context: "full" }) to see the class body.`}]}}let $=o.exports.findFuzzyCandidates(i).map(U=>U.name),P=Ln(i,$,50,3);if(P.length>0){let U=P.map(A=>` \u2022 \`${A.match}\` (${A.score}% match)`).join(`
|
|
862
917
|
`);return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
|
|
863
918
|
|
|
864
919
|
Suggestions:
|
|
865
|
-
${
|
|
920
|
+
${U}
|
|
866
921
|
|
|
867
922
|
Next steps:
|
|
868
923
|
\u2022 Search semantically: shadow_search_concept({ query: "${i}" })
|
|
@@ -871,8 +926,8 @@ Next steps:
|
|
|
871
926
|
Next steps:
|
|
872
927
|
\u2022 Search for it: shadow_search_concept({ query: "${i}" })
|
|
873
928
|
\u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${i}", filePath: "..." })
|
|
874
|
-
`}]}}let c=a[0];if(c.kind==="ExportSpecifier"||c.kind==="ExportAllDeclaration"){let
|
|
875
|
-
`),u=c.end_line-c.start_line+1,d=150,h,m=!1,f=null;if(r==="definition"&&u>d){let
|
|
929
|
+
`}]}}let c=a[0];if(c.kind==="ExportSpecifier"||c.kind==="ExportAllDeclaration"){let v=o.imports.findImportSource(c.file_path,i);if(v&&v.resolved_path)return pn({...s,filePath:v.resolved_path})}let l=cd.readFileSync(c.file_path,"utf8"),p=l.split(`
|
|
930
|
+
`),u=c.end_line-c.start_line+1,d=150,h,m=!1,f=null;if(r==="definition"&&u>d){let I=o.exports.findSiblings(c.file_path).map($=>({name:$.name,kind:$.kind,signature:$.signature||"",startLine:$.start_line,endLine:$.end_line,lineCount:$.end_line-$.start_line+1,isTarget:$.name===c.name&&$.start_line===c.start_line,parentName:$.parent_name}));if(I.length>1){f=ld(l,{name:c.name,startLine:c.start_line,endLine:c.end_line},I);let $=n.getRelative(c.file_path);h=f.foldedSource+`
|
|
876
931
|
|
|
877
932
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
878
933
|
\u{1F4CA} Semantic Fold Applied (context: "definition")
|
|
@@ -882,29 +937,29 @@ Next steps:
|
|
|
882
937
|
Target Symbol: ${c.name}
|
|
883
938
|
\u{1F4A1} Need more context?
|
|
884
939
|
\u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${c.name}", context: "full" })
|
|
885
|
-
\u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${
|
|
940
|
+
\u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${$}", detailLevel: "signatures" })
|
|
886
941
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,m=!0}else h=p.slice(c.start_line-1,c.start_line-1+d).join(`
|
|
887
942
|
`)+`
|
|
888
943
|
|
|
889
944
|
... (truncated ${u-d} lines)`,m=!0}else h=p.slice(c.start_line-1,c.end_line).join(`
|
|
890
|
-
`);let
|
|
945
|
+
`);let S=c.parent_name?`${c.parent_name}.${c.name}`:c.name,y=o.exports.findHydratedById(c.id),_=c.parent_name||c.name,E=o.imports.findProxies(c.file_path).map(v=>v.file_path),R=Array.from(new Set([c.file_path,...E])),T=o.imports.findVerifiedDependents(R,_),k=yd(T,e),F=gd(c.signature,S,c.kind),B={name:S,kind:c.kind,signature:F,file:n.getRelative(c.file_path),startLine:c.start_line,endLine:c.end_line,totalLines:u,...m&&{truncated:!0,previewLines:d},classification:c.classification,callerSummary:k,source:h};if(y&&y.recent_intents&&y.recent_intents.length>0){let v={},I=Date.now();for(let $ of y.recent_intents){if($.is_crystallized&&$.type!=="crystal")continue;let P=$.created_at;P<1e10&&(P*=1e3);let U=new Date(P).getTime(),A=I-U,H="just now";if(A>0){let L=Math.floor(A/1e3),D=Math.floor(L/60),J=Math.floor(D/60),z=Math.floor(J/24);z>0?H=`${z}d ago`:J>0?H=`${J}h ago`:D>0?H=`${D}m ago`:H=`${L}s ago`}v[$.type]||(v[$.type]=[]),v[$.type].push(`[${H}] ${$.content}`)}B.intelligence={working_set_of:y.active_missions.map($=>`Mission #${$.id}: ${$.name}`),total_intents:y.intent_log_count,recent_activity:v}}else y&&(B.intelligence={working_set_of:y.active_missions.map(v=>`Mission #${v.id}: ${v.name}`),total_intents:y.intent_log_count,recent_activity:null});try{let{generateEmbedding:v}=await Promise.resolve().then(()=>(qe(),Et)),I=`Symbol: ${B.name}
|
|
891
946
|
Signature: ${c.signature||""}
|
|
892
|
-
File: ${
|
|
947
|
+
File: ${B.file}`,$=await v(I);if($){let P=o.intentLogs.findSemanticMatches($,3,c.id),U=new Promise(H=>setTimeout(()=>H([]),100)),A=await Promise.race([P,U]);A&&A.length>0&&(B.intelligence||(B.intelligence={}),B.intelligence.related_knowledge=A.map(H=>({type:H.type,content:H.content,from_symbol:H.symbol_name,similarity:`${(H.similarity*100).toFixed(0)}%`})))}}catch{}if(r==="definition")return{content:[{type:"text",text:JSON.stringify(B,null,2)}]};let M={definition:B,dependencies:o.imports.getImportsForFile(c.file_path).map(v=>({module:v.module_specifier,symbols:v.imported_symbols,relativePath:v.resolved_path?ac.relative(e,v.resolved_path):null})),callerSummary:k};return M.verifiedUsages=k.topCallers,{content:[{type:"text",text:JSON.stringify(M,null,2)}]}}async function cc(s,e){let t=Mn.resolve(e.dir);await Q(async()=>{ge("Semantic Concept Search");let n=Oe();n.start(`Analyzing intent: "${b.bold(s)}"...`);try{let i=await nc({repoPath:t,query:s});n.stop("Analysis complete.");let r=i.content[0].text;if(r.includes("Found")){let a=r.split("## ").slice(1).map(c=>{let[l,...p]=c.split(`
|
|
893
948
|
|
|
894
|
-
`),[u,d]=l.split(" ( "),h=(u??"").replace(/^\d+\.\s*/,"").trim(),m=p.find(f=>f.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:h,matchPct:d??"",summaryLine:m}});if(a.forEach(({name:c,matchPct:l,summaryLine:p})=>{
|
|
895
|
-
`),p=l[0],u=l.find(
|
|
949
|
+
`),[u,d]=l.split(" ( "),h=(u??"").replace(/^\d+\.\s*/,"").trim(),m=p.find(f=>f.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:h,matchPct:d??"",summaryLine:m}});if(a.forEach(({name:c,matchPct:l,summaryLine:p})=>{ue(`${b.green(c)} ${b.dim("("+(l||""))}`,p,"blue"),console.log("")}),e.interactive&&a.length>1){let c=await si("Inspect a file",a.map(l=>({value:{name:l.name},label:l.name,hint:l.summaryLine.slice(0,50)})),{limit:15});if(c){let l=c.name.startsWith(t)?c.name:Mn.join(t,c.name),p=await Hi({repoPath:t,filePath:l});p.content?.[0]&&(console.log(""),ue(b.bold("File summary"),p.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function lc(s,e){let t=Mn.resolve(e.dir);await Q(async()=>{ge("Symbol Search");let n=Oe();n.start(`Searching symbols: "${b.bold(s)}"...`);try{let i=await Zs({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;try{let o=JSON.parse(r);if(Array.isArray(o)){if(console.log(""),ni(["Symbol","Kind","File","Line"],o.map(a=>[b.bold(b.green(a.name)),b.dim(a.kind??""),b.cyan(a.file??""),b.yellow(String(a.line??""))])),e.interactive&&o.length>1){let a=o.map(l=>({value:l,label:l.name,hint:`${l.file??""}:${l.line??""}`})),c=await si("Inspect symbol",a,{limit:15});if(c){let l=await pn({repoPath:t,symbolName:c.name});l.content?.[0]&&(console.log(""),ue(b.bold(c.name),l.content[0].text,"cyan"))}}}else console.log(r)}catch{console.log(r)}}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function pc(s,e){let t=Mn.resolve(e.dir);await Q(async()=>{ge("Fuzzy Symbol Search");let n=Oe();n.start(`Fuzzy matching: "${b.bold(s)}"...`);try{let i=await Zs({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;if(r.includes("## ")){let a=r.split("## ").slice(1).map(c=>{let l=c.split(`
|
|
950
|
+
`),p=l[0],u=l.find(y=>y.startsWith("**Match**:"))||"",d=l.find(y=>y.startsWith("**File**:"))||"",h=p.match(/`([^`]+)`/),m=h?h[1]:"",f=u.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),S=d.match(/`([^:]+):(\d+)`/);return{symbolName:m,file:S?S[1]:"",line:S?S[2]:"",matchType:f?f[1]:"",confidence:f?f[2]:""}});if(console.log(""),console.log(b.dim(`Found ${a.length} fuzzy match(es):`)),console.log(""),a.forEach((c,l)=>{console.log(`${b.dim(`${l+1}.`)} ${b.bold(b.green(c.symbolName))} ${b.dim(`(${c.matchType}, ${c.confidence}% match)`)}`),console.log(` ${b.cyan(c.file)}:${b.yellow(c.line)}`),console.log("")}),e.interactive&&a.length>1){let c=await si("Inspect symbol",a.map(l=>({value:l,label:l.symbolName,hint:`${l.file}:${l.line}`})),{limit:15});if(c){let l=await pn({repoPath:t,symbolName:c.symbolName});l.content?.[0]&&(console.log(""),ue(b.bold(c.symbolName),l.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function uc(s,e){let t=Mn.resolve(e.dir);await Q(async()=>{ge("Config Search");let n=Oe();n.start(`Searching config: ${b.bold(s||"all")}...`);try{let i=await sc({repoPath:t,key:s,kind:e.kind});n.stop("Search complete."),ue("\u2699\uFE0F Results",i.content[0].text,"yellow")}finally{await ne(t)}})}G();var er=w.child({module:"mcp:tools:env:hooks"});async function Ui(s){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:i}=s;if(t==="install"){er.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:i},"Installing git hooks");let r=mo({repoPath:e,enableAutoRefresh:n??!0,enableSymbolHealing:i??!0}),o=["# Git Hooks Installation","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(a=>`- \`${a}\``).join(`
|
|
896
951
|
`):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(a=>`- \`${a}\` (already installed)`).join(`
|
|
897
952
|
`):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
|
|
898
953
|
`)),o.push("")),o.push("---"),o.push("**What happens now?**"),(n??!0)&&o.push("- After `git pull` or `git checkout`: Index auto-refreshes in background"),(i??!0)&&o.push("- After `git commit`: Symbol shift detection runs automatically"),{content:[{type:"text",text:o.join(`
|
|
899
|
-
`)}]}}if(t==="remove"){
|
|
954
|
+
`)}]}}if(t==="remove"){er.info({repoPath:e},"Uninstalling git hooks");let r=ho(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(a=>`- \`${a}\``).join(`
|
|
900
955
|
`):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
|
|
901
956
|
`))),{content:[{type:"text",text:o.join(`
|
|
902
|
-
`)}]}}if(t==="status"){
|
|
957
|
+
`)}]}}if(t==="status"){er.info({repoPath:e},"Checking git hooks status");let r=Zt(e),o=r.statuses["post-checkout"];return{content:[{type:"text",text:["# Git Hooks Status","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(c=>`- \`${c}\``).join(`
|
|
903
958
|
`):"- None","",`## Missing (${r.missing.length})`,r.missing.length>0?r.missing.map(c=>`- \`${c}\``).join(`
|
|
904
959
|
`):"- None","",`## Foreign (${r.foreign.length})`,r.foreign.length>0?r.foreign.map(c=>`- \`${c}\` (non-Liquid hook content)`).join(`
|
|
905
960
|
`):"- None","",`## Disabled (${r.disabled.length})`,r.disabled.length>0?r.disabled.map(c=>`- \`${c}\` (not executable)`).join(`
|
|
906
961
|
`):"- None","","---",`**Post-checkout status**: \`${o}\``,o==="installed"?"**Branch-switch delta reindex**: active":"**Branch-switch delta reindex**: inactive",'**To install hooks**: Use `shadow_env_hooks({ action: "install" })`'].join(`
|
|
907
|
-
`)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function
|
|
962
|
+
`)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function dc(s){let[e,t="."]=s;if(!e||!["install","uninstall","status"].includes(e)){console.log(""),console.log(` ${b.bold("Usage: ")} liquid-shadow hooks <install|uninstall|status> [path]`),console.log(""),console.log(` ${b.bold("Commands: ")}`),console.log(` ${b.cyan("install")} Install git hooks for automatic index refresh and symbol healing`),console.log(` ${b.cyan("uninstall")} Remove installed git hooks`),console.log(` ${b.cyan("status")} Check git hooks installation status`),console.log(""),console.log(` ${b.bold("Examples: ")}`),console.log(" liquid-shadow hooks install ."),console.log(" liquid-shadow hooks status /path/to/repo"),console.log("");return}await Q(async()=>{let n=ll("path").resolve(t);switch(e){case"install":{let i=await Ui({repoPath:n,action:"install",enableAutoRefresh:!0,enableSymbolHealing:!0});if(console.log(""),console.log(` ${b.green("\u2714")} ${b.bold("Git hooks installed successfully")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);console.log(` ${b.bold("Installed hooks: ")}`),r.hooks.forEach(o=>{console.log(` ${b.cyan("\u2022")} ${o}`)}),console.log("")}catch{console.log(i.content[0].text)}break}case"uninstall":{await Ui({repoPath:n,action:"remove"}),console.log(""),console.log(` ${b.green("\u2714")} ${b.bold("Git hooks uninstalled successfully")}`),console.log("");break}case"status":{let i=await Ui({repoPath:n,action:"status"});if(console.log(""),console.log(` ${b.bold("Git Hooks Status")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);r.installed&&r.installed.length>0?(console.log(` ${b.green("\u2714")} Installed hooks:`),r.installed.forEach(o=>{console.log(` ${b.cyan("\u2022")} ${o}`)})):console.log(` ${b.yellow("\u26A0")} No hooks installed`),r.missing&&r.missing.length>0&&(console.log(""),console.log(` ${b.dim("Missing hooks: ")}`),r.missing.forEach(o=>{console.log(` ${b.dim("\u2022")} ${o}`)}))}catch{console.log(i.content[0].text)}console.log("");break}}})}Y();G();import bd from"path";import _d from"fs";var mc=w.child({module:"mcp:tools:workspace:list"});async function hc(s){let{repoPaths:e,status:t,limit:n,summarize:i=!1}=s;mc.info({repoCount:e.length,status:t,summarize:i},"Getting workspace missions");let r=[];for(let a of e)if(_d.existsSync(a))try{let{missions:c}=N.getInstance(a),l=c.findAll(t);for(let p of l){let u=c.getLinks(p.id);r.push({...p,repo_path:a,repo_name:bd.basename(a),cross_repo_links:u})}}catch(c){mc.error({error:c,repoPath:a},"Failed to query repo missions")}if(r.sort((a,c)=>{let l=d=>d==="in-progress"?0:d==="verifying"?1:2,p=l(a.status),u=l(c.status);return p!==u?p-u:(a.created_at||0)-(c.created_at||0)}),i||r.length>50&&!n){let a=n||20,c=r.slice(0,a),l=r.reduce((u,d)=>(u[d.status]=(u[d.status]||0)+1,u),{}),p=r.reduce((u,d)=>(u[d.repo_name]=(u[d.repo_name]||0)+1,u),{});return{content:[{type:"text",text:JSON.stringify({summary:{total_missions:r.length,by_status:l,by_repo:p,showing_top:a},top_missions:c,hint:`Showing top ${a} of ${r.length} missions. Use limit to adjust or summarize:false for full list.`},null,2)}]}}let o=n?r.slice(0,n):r;return{content:[{type:"text",text:JSON.stringify({total_missions:r.length,showing:o.length,missions:o},null,2)}]}}Y();G();var Ed=w.child({module:"mcp:tools:workspace:link"});async function fc(s){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:i,relationship:r="related"}=s;Ed.info({parentRepoPath:e,childRepoPath:n},"Linking cross-repo missions");let{missions:o}=N.getInstance(e),{missions:a}=N.getInstance(n);try{let c=o.findById(t),l=a.findById(i);if(!c)throw new Error(`Parent mission ${t} not found`);if(!l)throw new Error(`Child mission ${i} not found`);return o.createLink(t,n,i,r,"parent"),a.createLink(i,e,t,r,"child"),{content:[{type:"text",text:JSON.stringify({status:"linked",relationship:r},null,2)}]}}catch(c){throw new Error(`Failed to link: ${c.message}`)}}G();import Id from"path";G();ut();import Sd from"better-sqlite3";import un from"path";import gc from"fs";import wd from"os";import xd from"crypto";var yc=w.child({module:"fusion-connection"}),ji=5,vd=1,bc=["files","exports","imports","configs","schema_migrations"],tr=3,Gi=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),yc.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=un.dirname(this.fusionDbPath);gc.existsSync(t)||gc.mkdirSync(t,{recursive:!0}),this.fusionDb=new Sd(this.fusionDbPath),this.fusionDb.pragma("journal_mode = WAL"),this.fusionDb.pragma("busy_timeout = 5000"),this.initFusionSchema();for(let n of e.repoPaths)this.attachRepo(n)}getFusionDbPath(e){let t=wd.homedir(),n=un.join(t,".mcp-liquid-shadow","fused"),i=e.replace(/[^a-zA-Z0-9-_]/g,"_");return un.join(n,`${i}.db`)}initFusionSchema(){this.fusionDb.exec(`
|
|
908
963
|
CREATE TABLE IF NOT EXISTS fused_repos (
|
|
909
964
|
alias TEXT PRIMARY KEY,
|
|
910
965
|
repo_path TEXT NOT NULL UNIQUE,
|
|
@@ -938,19 +993,19 @@ File: ${U.file}`,I=await E(T);if(I){let M=o.intentLogs.findSemanticMatches(I,3,c
|
|
|
938
993
|
|
|
939
994
|
CREATE INDEX IF NOT EXISTS idx_virtual_edges_source ON virtual_edges(source_repo, source_file_path);
|
|
940
995
|
CREATE INDEX IF NOT EXISTS idx_virtual_edges_target ON virtual_edges(target_repo, target_file_path);
|
|
941
|
-
`),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(
|
|
942
|
-
VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(c){if(this.isLockContentionError(c)&&a<
|
|
996
|
+
`),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(vd.toString())}attachRepo(e){let t=un.resolve(e);if(this.attachedRepos.has(t))return;if(!pt(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=De(t),i=n.name;this.validateSchemaCompatibility(n,t);let r=this.getSchemaVersion(n),o=this.generateAlias(t);for(let a=1;a<=tr;a++)try{this.fusionDb.exec(`ATTACH DATABASE '${i}' AS ${o}`);let c={alias:o,repoPath:t,dbPath:i,schemaVersion:r,attached:!0};this.attachedRepos.set(t,c),this.fusionDb.prepare(`INSERT OR REPLACE INTO fused_repos (alias, repo_path, db_path, schema_version, attached_at, last_validated_at)
|
|
997
|
+
VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(c){if(this.isLockContentionError(c)&&a<tr){yc.warn({repoPath:t,attempt:a,maxAttempts:tr},"Attach failed due to lock contention; retrying");continue}throw c}}checkHealth(){let e=[];for(let t of this.attachedRepos.values())try{this.fusionDb.prepare(`SELECT 1 FROM ${t.alias}.files LIMIT 1`).get(),e.push({alias:t.alias,repoPath:t.repoPath,accessible:!0})}catch(n){e.push({alias:t.alias,repoPath:t.repoPath,accessible:!1,error:n instanceof Error?n.message:String(n)})}return{healthy:e.every(t=>t.accessible),repos:e}}detachRepo(e){let t=un.resolve(e),n=this.attachedRepos.get(t);n&&(this.fusionDb.exec(`DETACH DATABASE ${n.alias}`),this.attachedRepos.delete(t),this.fusionDb.prepare("DELETE FROM fused_repos WHERE repo_path = ?").run(t))}refreshRepo(e){this.detachRepo(e),this.attachRepo(e)}refreshAll(){let e=Array.from(this.attachedRepos.keys());for(let t of e)this.refreshRepo(t)}validateSchemas(){let e=Array.from(this.attachedRepos.values()).map(t=>{let n=De(t.repoPath),i=bc.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=ji&&i.length===0,missingTables:i}});return{valid:e.every(t=>t.compatible),minVersion:ji,repos:e}}getAttachedRepos(){return Array.from(this.attachedRepos.values())}prepare(e){return this.fusionDb.prepare(e)}exec(e){this.fusionDb.exec(e)}close(){for(let e of this.attachedRepos.values())try{this.fusionDb.exec(`DETACH DATABASE ${e.alias}`)}catch{}this.attachedRepos.clear(),this.fusionDb.open&&this.fusionDb.close()}generateAlias(e){let t=un.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=xd.createHash("sha256").update(e).digest("hex").substring(0,6);return`repo_${t}_${n}`}getSchemaVersion(e){try{return e.prepare("SELECT MAX(version) as version FROM schema_migrations").get()?.version||0}catch{return 0}}validateSchemaCompatibility(e,t){let n=this.getSchemaVersion(e);if(n<ji)throw new Error(`Schema version mismatch for ${t}. Expected >= ${ji}, got ${n}.`);let i=bc.filter(r=>!this.checkTableExists(e,r));if(i.length>0)throw new Error(`Missing tables in ${t}: ${i.join(", ")}`)}checkTableExists(e,t){try{return!!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)}catch{return!1}}isLockContentionError(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("locked")||t.includes("busy")}get nameValue(){return this.name}get dbPath(){return this.fusionDbPath}};G();var Mt=w.child({module:"edge-scanner"});function nr(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Rd(s){if(!s)return null;try{let e=JSON.parse(s);return e.path||e.name||null}catch{return null}}function Td(s,e){let t=nr(s),n=nr(e);if(t===n)return!0;let i=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function kd(s){Mt.info("Starting HTTP gap detection scan");let e=s.getAttachedRepos();if(e.length<2)return Mt.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
|
|
943
998
|
SELECT id, name, file_path, capabilities
|
|
944
999
|
FROM ${r.alias}.exports
|
|
945
1000
|
WHERE kind = 'HTTP Route'
|
|
946
|
-
`,a=s.executeRawQuery(o);for(let c of a){let l=
|
|
1001
|
+
`,a=s.executeRawQuery(o);for(let c of a){let l=Rd(c.capabilities)||c.name;l&&l.startsWith("/")&&t.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,symbolId:c.id,routePath:l})}}catch(o){Mt.warn({repo:r.alias,error:o},"Failed to query backend routes")}Mt.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
|
|
947
1002
|
SELECT file_path, name
|
|
948
1003
|
FROM ${r.alias}.event_synapses
|
|
949
1004
|
WHERE type = 'api_route' AND direction = 'produce'
|
|
950
|
-
`,a=s.executeRawQuery(o);for(let c of a){let l=
|
|
951
|
-
`));let
|
|
1005
|
+
`,a=s.executeRawQuery(o);for(let c of a){let l=nr(c.name);l&&l.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,routePath:l})}}catch(o){Mt.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}Mt.debug({count:n.length},"Found frontend API calls");let i=0;for(let r of n)for(let o of t)if(r.repoPath!==o.repoPath&&Td(r.routePath,o.routePath))try{s.addVirtualEdge({sourceRepo:r.repoPath,sourceFilePath:r.filePath,targetRepo:o.repoPath,targetFilePath:o.filePath,targetSymbolId:o.symbolId,relationship:"api_call",metadata:{frontendPath:r.routePath,backendPath:o.routePath,method:o.method},confidence:1}),i++}catch(a){Mt.debug({source:r.filePath,target:o.filePath,error:a},"Skipped duplicate edge")}return Mt.info({edgesCreated:i,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),i}function _c(s){let e=kd(s);return{httpGaps:e,totalEdges:e}}G();var Cd=w.child({module:"fusion-index-service"}),qi=class{constructor(e){this.connection=e}executeFederatedQuery(e,...t){return this.connection.prepare(e).all(...t).map(r=>{let{_repo_alias:o,_repo_path:a,...c}=r;return{repo:o,repoPath:a,data:c}})}executeRawQuery(e,...t){return this.connection.prepare(e).all(...t)}buildAdvancedQuery(e){let t=this.connection.getAttachedRepos();if(t.length===0)throw new Error("No repositories attached");let{table:n,tableAlias:i,columns:r,joins:o,where:a,groupBy:c,having:l,orderBy:p,limit:u,offset:d}=e,h=i||n.charAt(0),m=r.join(", "),S=t.map(y=>{let _=`${y.alias}.${n} ${h}`,E="";o&&o.length>0&&(E=o.map(F=>{let B=F.alias||F.table.charAt(0);return`${F.type} JOIN ${y.alias}.${F.table} ${B} ON ${F.on}`}).join(`
|
|
1006
|
+
`));let R=a?`WHERE ${a}`:"",T=c&&c.length>0?`GROUP BY ${c.join(", ")}`:"",k=l?`HAVING ${l}`:"";return`SELECT '${y.alias}' as _repo_alias, '${y.repoPath}' as _repo_path, ${m} FROM ${_} ${E} ${R} ${T} ${k}`.trim()}).join(`
|
|
952
1007
|
UNION ALL
|
|
953
|
-
`);return p&&(
|
|
1008
|
+
`);return p&&(S=`SELECT * FROM (${S}) AS federated_results ORDER BY ${p}`),u!==void 0&&(S+=` LIMIT ${u}`),d!==void 0&&(S+=` OFFSET ${d}`),S}buildFtsQuery(e,t,n,i,r=50){let o=this.connection.getAttachedRepos();if(o.length===0)throw new Error("No repositories attached");let a=n.replace(/"/g,'""'),c=i.map(p=>`c.${p}`).join(", ");return`${o.map(p=>`
|
|
954
1009
|
SELECT '${p.alias}' as _repo_alias, '${p.repoPath}' as _repo_path, ${c}, bm25(${p.alias}.${e}) as _fts_rank
|
|
955
1010
|
FROM ${p.alias}.${e} fts
|
|
956
1011
|
JOIN ${p.alias}.${t} c ON fts.rowid = c.id
|
|
@@ -972,7 +1027,7 @@ WHERE i.resolved_path IS NOT NULL`);return t.join(`
|
|
|
972
1027
|
INSERT INTO virtual_edges
|
|
973
1028
|
(source_repo, source_file_path, source_symbol_id, target_repo, target_file_path, target_symbol_id, relationship, metadata, confidence, updated_at)
|
|
974
1029
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
|
|
975
|
-
`).run(e.sourceRepo,e.sourceFilePath,e.sourceSymbolId||null,e.targetRepo,e.targetFilePath,e.targetSymbolId||null,e.relationship,e.metadata?JSON.stringify(e.metadata):null,e.confidence??1).lastInsertRowid}scanEdges(){return ad.info({name:this.connection.nameValue},"Starting edge scan"),Ja(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var Ya=S.child({module:"fused-index"}),Us=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Ai(e),this.service=new Pi(this.connection)}attachRepo(e){this.connection.attachRepo(e)}detachRepo(e){this.connection.detachRepo(e)}refreshRepo(e){this.connection.refreshRepo(e)}getAttachedRepos(){return this.connection.getAttachedRepos()}checkHealth(){return this.connection.checkHealth()}close(){this.connection.close(),Ya.info({name:this.configName},"Fused index closed")}getStatus(){let e=this.service.executeRawQuery("SELECT COUNT(*) as count FROM virtual_edges");return{name:this.connection.nameValue,path:this.connection.dbPath,attachedRepos:this.connection.getAttachedRepos().length,repos:this.connection.getAttachedRepos(),virtualEdgesCount:e[0]?.count||0}}searchExports(e,t=50){return this.service.searchExports(e,t)}searchFiles(e,t=50){return this.service.searchFiles(e,t)}getVirtualEdges(e,t){return this.service.getVirtualEdges(e,t)}addVirtualEdge(e){return this.service.addVirtualEdge(e)}scanEdges(){return this.service.scanEdges()}buildUnionQuery(e,t,n){return this.service.buildUnionQuery(e,t,n)}executeFederatedQuery(e,...t){return this.service.executeFederatedQuery(e,...t)}executeRawQuery(e,...t){return this.service.executeRawQuery(e,...t)}buildAdvancedQuery(e){return this.service.buildAdvancedQuery(e)}buildFtsQuery(e,t,n,i,r){return this.service.buildFtsQuery(e,t,n,i,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return Ya.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},zs=new Map;function Ka(s){let e=zs.get(s.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),i=new Set(s.repoPaths.map(o=>cd.resolve(o)));if(n.size===i.size&&[...n].every(o=>i.has(o)))return e;e.close(),zs.delete(s.name)}let t=new Us(s);return zs.set(s.name,t),t}q();var ld=S.child({module:"mcp:tools:workspace:fuse"});async function Qa(s){let{repoPaths:e,name:t}=s;ld.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=Ka({repoPaths:e,name:t||`workspace-${Date.now()}`});return{content:[{type:"text",text:JSON.stringify({message:"Fused index created",status:n.getStatus()},null,2)}]}}catch(n){throw new Error(`Failed to fuse: ${n.message}`)}}import Mi from"path";async function Xa(s){let[e,...t]=s;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${y.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${y.bold("Commands: ")}`),console.log(` ${y.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${y.cyan("link")} <args...> Link missions across repositories`),console.log(` ${y.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${y.bold("Examples: ")}`),console.log(" liquid-shadow workspace missions /frontend /backend"),console.log(" liquid-shadow workspace link /frontend 5 /backend 12"),console.log(" liquid-shadow workspace fuse /frontend /backend --name my-app"),console.log("");return}await Y(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${y.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>Mi.resolve(r)),i=await ja({repoPaths:n});if(console.log(""),console.log(` ${y.bold("Workspace Missions")}`),console.log(""),i.content&&i.content[0]){let r=JSON.parse(i.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${y.cyan("\u2022")} ${y.bold(o.name)} (ID: ${o.id})`),console.log(` ${y.dim("Repo: ")} ${o.repo_path}`),console.log(` ${y.dim("Status: ")} ${o.status}`),console.log(` ${y.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${y.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${y.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${y.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,i,r,o,a]=t;await Ba({parentRepoPath:Mi.resolve(n),parentMissionId:parseInt(i,10),childRepoPath:Mi.resolve(r),childMissionId:parseInt(o,10),relationship:a}),console.log(""),console.log(` ${y.green("\u2714")} ${y.bold("Missions linked successfully")}`),console.log(` ${y.dim("Parent: ")} ${n} (Mission ${i})`),console.log(` ${y.dim("Child: ")} ${r} (Mission ${o})`),a&&console.log(` ${y.dim("Relationship: ")} ${a}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${y.red("\u2716")} Please provide at least one repository path`);return}let n,i=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):i.push(Mi.resolve(t[o]));let r=await Qa({repoPaths:i,name:n});if(console.log(""),console.log(` ${y.green("\u2714")} ${y.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${y.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${y.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${y.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${y.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}q();q();var pd=S.child({module:"strategy-normalizer"}),Ie=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(i){return pd.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:this.normalizeSteps(t)}}static normalizeSteps(e){return Array.isArray(e)?e.map((t,n)=>typeof t=="string"?{id:`step-${n}`,description:t,status:"pending"}:typeof t=="object"&&t!==null?{id:t.id||`step-${n}`,description:t.description||t.content||t.name||`Step ${n+1}`,status:t.status||"pending",dependencies:t.dependencies||t.deps,verification:t.verification,...t}:{id:`step-${n}`,description:String(t),status:"pending"}):e.steps&&Array.isArray(e.steps)?this.normalizeSteps(e.steps):typeof e=="object"?Object.entries(e).map(([t,n],i)=>typeof n=="string"?{id:t,description:n,status:"pending"}:typeof n=="object"&&n!==null?{id:t,description:n.description||n.content||n.name||t,status:n.status||"pending",dependencies:n.dependencies||n.deps,verification:n.verification,...n}:{id:t||`step-${i}`,description:String(n),status:"pending"}):[]}static stringify(e){return JSON.stringify(e,null,2)}static validate(e){let t=[];if(!e)return{valid:!0,errors:[]};try{let n=this.normalize(e),i=new Set;for(let r of n.steps)if(i.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),i.add(r.id),r.dependencies)for(let o of r.dependencies)i.has(o)||t.push(`Step "${r.id}" depends on non-existent step "${o}"`);return{valid:t.length===0,errors:t}}catch(n){return t.push(`Strategy validation failed: ${n instanceof Error?n.message:String(n)}`),{valid:!1,errors:t}}}};q();import js from"fs";import Za from"path";import ud from"os";var dd=[{id:"step-0",description:"Analyze impact: identify dependents and call sites",status:"pending"},{id:"step-1",description:"Implement refactor and update call sites",status:"pending"},{id:"step-2",description:"Run tests and verify behavior; update docs if needed",status:"pending"}],md=[{id:"step-0",description:"Capture requirements and acceptance criteria",status:"pending"},{id:"step-1",description:"Implement feature with tests",status:"pending"},{id:"step-2",description:"Integrate and verify end-to-end",status:"pending"}],hd=[{id:"step-0",description:"Reproduce the bug and document steps",status:"pending"},{id:"step-1",description:"Diagnose root cause and plan fix",status:"pending"},{id:"step-2",description:"Apply fix and add/update regression test",status:"pending"},{id:"step-3",description:"Verify fix and run full test suite",status:"pending"}],ec=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:dd},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:md},{id:"bug-fix",name:"Bug fix",description:"Reproduction \u2192 diagnosis \u2192 fix \u2192 regression test",defaultGoal:"Fix {{target}}: reproduce, diagnose, fix, and add regression test.",steps:hd}],Bs=new Map(ec.map(s=>[s.id,s])),Ni=!1;function fd(){if(Ni)return;let s=Za.join(ud.homedir(),".shadow","templates");if(!js.existsSync(s)){S.debug({templatesDir:s},"Custom templates directory does not exist"),Ni=!0;return}try{let e=js.readdirSync(s).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=Za.join(s,t),i=js.readFileSync(n,"utf8"),r=JSON.parse(i);if(!r.id||!r.name||!r.defaultGoal||!r.steps){S.warn({file:t,template:r},"Invalid custom template structure - skipping");continue}if(!Array.isArray(r.steps)||r.steps.length===0){S.warn({file:t},"Template has no steps - skipping");continue}if(ec.some(o=>o.id===r.id)){S.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}Bs.set(r.id,r),S.info({file:t,templateId:r.id},"Loaded custom template")}catch(n){S.warn({file:t,error:n},"Failed to load custom template")}Ni=!0}catch(e){S.warn({error:e,templatesDir:s},"Failed to read custom templates directory"),Ni=!0}}function gd(s){return fd(),Bs.get(s)}function yd(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function tc(s,e,t={}){let n=gd(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(Bs.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=yd(n.defaultGoal,{...t,target:i}),a=Ie.normalize({steps:n.steps}),c=Ie.stringify(a);return{name:r,goal:o,strategy:c}}V();gn();var En=S.child({module:"mcp:tools:ops:plan"}),bd=["name","goal","strategy","parentId","outcomeContract"],_d="Mission update requires at least one updatable field: name, goal, strategy, parentId, outcomeContract.",Ed="Mission requires name and goal (or templateId with optional templateVars).";async function nc(s){let{repoPath:e,name:t,goal:n,strategy:i,missionId:r,parentId:o,outcomeContract:a,templateId:c,templateVars:l}=s,{missions:p}=O.getInstance(e),u=me(e),d=De(e);En.info({repoPath:e,name:t,missionId:r,templateId:c},"Planning mission");try{let h=t,m=n,f=i;if(!r&&c){let b=tc(c,t,l||{});h=h??b.name,m=m??b.goal,f=f??b.strategy}let _,g;if(r){let b=p.findById(r);if(!b)throw new Error(`Mission ${r} not found.`);let w;if(i!==void 0)if(i){let R=Ie.normalize(i);w=Ie.stringify(R);let k=Ie.validate(w);k.valid||En.warn({errors:k.errors,strategy:i},"Strategy validation warnings detected")}else w=null;let x={commit_sha:d};if(t!==void 0&&(x.name=t),n!==void 0&&(x.goal=n),w!==void 0&&(x.strategy_graph=w),o!==void 0&&(x.parent_id=o),a!==void 0&&(x.outcome_contract=a),Object.keys(x).length===1)throw new Error(_d);p.update(r,{...x}),_=r,g=`Mission "${t??b.name}" updated.`}else{if(!h||!m)throw new Error(Ed);let b=null;if(f){let w=Ie.normalize(f);b=Ie.stringify(w);let x=Ie.validate(b);x.valid||En.warn({errors:x.errors,strategy:f},"Strategy validation warnings detected")}_=p.create({name:h,goal:m,strategy_graph:b,status:"planned",git_branch:u,commit_sha:d,parent_id:o||null,verification_context:null,outcome_contract:a||null}),g=`Mission "${h}" planned.`}try{await new Fe(e).syncMissionToGitNotes(Number(_))}catch(b){En.info({missionId:_,...ye(b)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:_,status:"planned",message:g,strategy_saved:!!f,contract_saved:!!a,updateable_fields:bd,from_template:c??void 0,commit:d},null,2)}]}}catch(h){let m=At(h);throw En.error({repoPath:e,...ye(h)},"Failed to plan mission"),new Error(`Failed to plan mission: ${m}`)}}q();V();var Di=class s{constructor(e){this.intentLogs=e}static RECENCY_HALF_LIFE_HOURS=48;static WEIGHTS={recency:.4,activity:.3,statusBoost:.2,blockerBoost:.1};score(e){if(e.length===0)return[];let t=Math.floor(Date.now()/1e3),n=e.map(c=>c.id),i=this.intentLogs.countByMissions(n),r=this.intentLogs.findMissionsWithBlockers(n),o=Math.max(1,...Object.values(i));return e.map(c=>{let l=this.computeRecency(c.updated_at,t),p=(i[c.id]||0)/o,u=this.computeStatusBoost(c.status),d=r.has(c.id)?1:0,h=s.WEIGHTS,m=l*h.recency+p*h.activity+u*h.statusBoost+d*h.blockerBoost;return{mission:c,score:Math.round(m*1e3)/1e3,breakdown:{recency:Math.round(l*1e3)/1e3,activity:Math.round(p*1e3)/1e3,blockerBoost:d,statusBoost:u}}}).sort((c,l)=>l.score-c.score)}computeRecency(e,t){let n=Math.max(0,(t-e)/3600);return Math.pow(.5,n/s.RECENCY_HALF_LIFE_HOURS)}computeStatusBoost(e){switch(e){case"in-progress":return 1;case"verifying":return .8;case"planned":return .4;default:return 0}}};V();q();var Sd=S.child({module:"collision-service"}),Oi=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=me(this.repoPath);if(!e)return[];let{missions:t,intentLogs:n}=O.getInstance(this.repoPath),i=t.findActive().filter(a=>a.git_branch&&a.git_branch!==e),r=[],o=new Set;for(let a of i){let c=a.git_branch;if(o.has(c))continue;o.add(c),Sd.info({branch:c,currentBranch:e},"Checking predictive collisions"),wo(this.repoPath,e,c)&&r.push({branch:c,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${c}'.`});let p=t.findActive(e),u=new Set;for(let m of p)t.getWorkingSet(m.id).forEach(f=>u.add(f.file_path));let h=t.getWorkingSet(a.id).filter(m=>u.has(m.file_path));h.length>0&&r.push({branch:c,type:"intent",description:`Logical conflict: Mission '${a.name}' on '${c}' is modifying files you are currently working on.`,conflictingFiles:h.map(m=>m.file_path)})}return r}};var Fi=class{constructor(e){this.repoPath=e}async getBriefing(e={}){let{missionId:t,scope:n="mission",altitude:i,activeMissionsLimit:r,recentActivityLimit:o,compact:a}=e,c=a??(i==="orbit"||i==="atmosphere"),l=o??(i==="orbit"?0:i==="ground"?20:10),{missions:p,intentLogs:u}=O.getInstance(this.repoPath),d=De(this.repoPath),h=me(this.repoPath);return n==="project"?this.getProjectBriefing({altitude:i,activeMissionsLimit:r,recentActivityLimit:l,compact:c,currentBranch:h,currentCommit:d}):this.getMissionBriefing({missionId:t,altitude:i,recentActivityLimit:l,currentBranch:h,currentCommit:d})}async getProjectBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i}=O.getInstance(t),{altitude:r,activeMissionsLimit:o,recentActivityLimit:a,compact:c,currentBranch:l,currentCommit:p}=e,u=n.findActive(l||void 0),d=u.length;o&&u.length>o&&(u=u.slice(0,o));let h=n.findParentOnlyIds(u),m=new Set(h),f=u.filter(N=>!m.has(N.id)),g=new Di(i).score(f),b=.15,w=3,x=c&&g.length>w?g.filter((N,$)=>$<w||N.score>=b):g,R=x.map(N=>N.mission),k=new Map(x.map(N=>[N.mission.id,N.score])),D=N=>({id:N.id,name:N.name,goal:N.goal,status:N.status,relevance:k.get(N.id)});if(r==="orbit")return{scope:"project",altitude:"orbit",counts:n.getStats(),next_work_candidates:R.map(D),meta:{current_branch:l,activeMissionsTotal:d,ember:this.getEmberLabel(t)}};let U={},P=[];for(let N of u)N.parent_id!=null?(U[N.parent_id]||(U[N.parent_id]=[]),U[N.parent_id].push(N)):P.push(N);let E=n.findRecentCompleted(5).map(D),T=a>0?i.findRecentDecisionActivity(a):void 0,I=h.map(N=>{let $=u.find(L=>L.id===N);return{parent:c?{...$,strategy_graph:void 0,verification_context:void 0}:$,children:U[N]??[]}}),M=P.filter(N=>!m.has(N.id));return{scope:"project",altitude:r||"atmosphere",counts:n.getStats(),analytics:n.getAnalytics(),hierarchy:I.length>0?I:void 0,standalone_active:M.length>0?M:void 0,active_missions:I.length===0?c?u.map(N=>({...N,strategy_graph:void 0})):u:void 0,next_work_candidates:R.map(D),recent_completed:E,recent_activity:T,meta:{current_branch:l,current_commit:p,activeMissionsTotal:d,active_limit_applied:!!o,relevance_filtered:x.length<g.length?{shown:x.length,total:g.length}:void 0,ember:this.getEmberLabel(t)}}}getEmberLabel(e){try{let{status:t,progress:n}=yi(e);if(t==="idle")return;if(t==="done")return"symbols: fully embedded";let[i,r]=n.split("/").map(Number),o=r>0?Math.round(i/r*100):0;return t==="running"?`symbols: warming ${n} (${o}%)`:`symbols: ${t} ${n}`}catch{return}}async getMissionBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i}=O.getInstance(t),{missionId:r,altitude:o,recentActivityLimit:a,currentBranch:c,currentCommit:l}=e,p;if(r?p=n.findById(r):p=n.findActive(c||void 0)[0],!p)return null;let u=null;try{p.strategy_graph&&(u=JSON.parse(p.strategy_graph))}catch{}if(o==="orbit")return{altitude:"orbit",mission:{id:p.id,name:p.name,goal:p.goal,status:p.status,last_updated:new Date(p.updated_at*1e3).toISOString()},strategy_snapshot:u};let d="No external shadow changes detected.";try{new qt(t).analyzeGhostChanges(p.commit_sha||void 0),d="Shadow Trace completed: Checked for external modifications."}catch{}let h={repaired:0,failed:0};try{h=new qe(t).detectAndRepairShifts()}catch{}let m=n.getHandoffs(p.id).map(_=>{let g=null;try{g=JSON.parse(_.metadata??"")}catch{}return{artifactId:_.id,kind:_.identifier,confidence:g?.confidence??null,findingsCount:g?.findings?.length??0,risksCount:g?.risks?.length??0,missionsCreated:g?.missionsCreated??[],createdAt:_.created_at}}),f={altitude:o||"atmosphere",mission:{id:p.id,name:p.name,goal:p.goal,status:p.status,last_updated:new Date(p.updated_at*1e3).toISOString(),git_branch:p.git_branch,commit_sha:p.commit_sha,outcome_contract:p.outcome_contract},artifacts:n.getArtifacts(p.id),handoffs:m,shadow_trace:{ghost_analysis:d,symbols_repaired:h.repaired,symbols_missing:h.failed},context:{current_commit:l,working_set:n.getWorkingSet(p.id).map(_=>_.file_path)},strategy_snapshot:u,recent_activity:o==="ground"?i.findByMission(p.id,a||20):i.findByMissionPreferCrystal(p.id,15),ancestor_activity_summary:[],predictive_collisions:[]};try{let _=new Oi(t);f.predictive_collisions=await _.analyzePotentialCollisions()}catch{}if(p.parent_id){let _=o==="ground"?i.findByMission(p.parent_id,5):i.findByMissionPreferCrystal(p.parent_id,3);f.ancestor_activity_summary=_.map(g=>({type:g.type,content:g.content,date:new Date(g.created_at*1e3).toISOString()}))}return f}};var ic=S.child({module:"mcp:tools:ops:briefing"});async function sc(s){let{repoPath:e,scope:t="mission"}=s;ic.info({repoPath:e,missionId:s.missionId,scope:t},"Generating briefing");try{let i=await new Fi(e).getBriefing(s);if(!i&&t==="mission")return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let r;if(t==="project"){let o=i.counts;r=i.next_work_candidates.length===0&&o.active===0?{tool:"shadow_ops_plan",reason:"No open work; create a mission"}:{tool:"shadow_ops_track",reason:"Select a mission from hierarchy or next_work_candidates to execute"}}return{content:[{type:"text",text:JSON.stringify(i,null,2)}],suggestedNext:r}}catch(n){throw ic.error({error:n,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${n instanceof Error?n.message:String(n)}`)}}q();V();V();q();q();var wd=S.child({module:"reasoning-engine"}),Wi=class{analyze(e){wd.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[],sourceMissions:[]};for(let i of e){let r=i.content.toLowerCase(),o=this.matchesContext(r,i.type),a=this.matchesDecision(r,i.type),c=this.matchesConsequence(r,i.type),l=this.matchesRecommendation(r,i.type);o?t.context.push(i.content):a?t.decisions.push(i.content):l?t.recommendations.push(i.content):c?t.consequences.push(i.content):i.type==="decision"?t.decisions.push(i.content):i.type==="discovery"||i.type==="fix"?t.consequences.push(i.content):t.unclassified.push(i.content)}let n=new Set;for(let i of e)i.mission_id!=null&&n.add(i.mission_id);return t.sourceMissions=[...n],t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(i=>e.includes(i))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(i=>e.includes(i))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(i=>e.includes(i))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(i=>e.includes(i))}};var Hi=S.child({module:"briefing-engine"}),tt=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=O.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Wi,this.persistencePivot=new Fe(e)}async distillMission(e,t=!0){Hi.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.gatherConsolidatedLogs(e);if(n.length===0)return{missionId:e,adr:"No intent logs found for this mission.",metrics:{totalLogs:0,symbolCount:0}};let i=this.reasoningEngine.analyze(n),r=new Set(n.map(a=>a.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
|
|
1030
|
+
`).run(e.sourceRepo,e.sourceFilePath,e.sourceSymbolId||null,e.targetRepo,e.targetFilePath,e.targetSymbolId||null,e.relationship,e.metadata?JSON.stringify(e.metadata):null,e.confidence??1).lastInsertRowid}scanEdges(){return Cd.info({name:this.connection.nameValue},"Starting edge scan"),_c(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var Ec=w.child({module:"fused-index"}),sr=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Gi(e),this.service=new qi(this.connection)}attachRepo(e){this.connection.attachRepo(e)}detachRepo(e){this.connection.detachRepo(e)}refreshRepo(e){this.connection.refreshRepo(e)}getAttachedRepos(){return this.connection.getAttachedRepos()}checkHealth(){return this.connection.checkHealth()}close(){this.connection.close(),Ec.info({name:this.configName},"Fused index closed")}getStatus(){let e=this.service.executeRawQuery("SELECT COUNT(*) as count FROM virtual_edges");return{name:this.connection.nameValue,path:this.connection.dbPath,attachedRepos:this.connection.getAttachedRepos().length,repos:this.connection.getAttachedRepos(),virtualEdgesCount:e[0]?.count||0}}searchExports(e,t=50){return this.service.searchExports(e,t)}searchFiles(e,t=50){return this.service.searchFiles(e,t)}getVirtualEdges(e,t){return this.service.getVirtualEdges(e,t)}addVirtualEdge(e){return this.service.addVirtualEdge(e)}scanEdges(){return this.service.scanEdges()}buildUnionQuery(e,t,n){return this.service.buildUnionQuery(e,t,n)}executeFederatedQuery(e,...t){return this.service.executeFederatedQuery(e,...t)}executeRawQuery(e,...t){return this.service.executeRawQuery(e,...t)}buildAdvancedQuery(e){return this.service.buildAdvancedQuery(e)}buildFtsQuery(e,t,n,i,r){return this.service.buildFtsQuery(e,t,n,i,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return Ec.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},ir=new Map;function Sc(s){let e=ir.get(s.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),i=new Set(s.repoPaths.map(o=>Id.resolve(o)));if(n.size===i.size&&[...n].every(o=>i.has(o)))return e;e.close(),ir.delete(s.name)}let t=new sr(s);return ir.set(s.name,t),t}G();var Ld=w.child({module:"mcp:tools:workspace:fuse"});async function wc(s){let{repoPaths:e,name:t}=s;Ld.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=Sc({repoPaths:e,name:t||`workspace-${Date.now()}`});return{content:[{type:"text",text:JSON.stringify({message:"Fused index created",status:n.getStatus()},null,2)}]}}catch(n){throw new Error(`Failed to fuse: ${n.message}`)}}import Vi from"path";async function xc(s){let[e,...t]=s;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${b.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${b.bold("Commands: ")}`),console.log(` ${b.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${b.cyan("link")} <args...> Link missions across repositories`),console.log(` ${b.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${b.bold("Examples: ")}`),console.log(" liquid-shadow workspace missions /frontend /backend"),console.log(" liquid-shadow workspace link /frontend 5 /backend 12"),console.log(" liquid-shadow workspace fuse /frontend /backend --name my-app"),console.log("");return}await Q(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${b.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>Vi.resolve(r)),i=await hc({repoPaths:n});if(console.log(""),console.log(` ${b.bold("Workspace Missions")}`),console.log(""),i.content&&i.content[0]){let r=JSON.parse(i.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${b.cyan("\u2022")} ${b.bold(o.name)} (ID: ${o.id})`),console.log(` ${b.dim("Repo: ")} ${o.repo_path}`),console.log(` ${b.dim("Status: ")} ${o.status}`),console.log(` ${b.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${b.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${b.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${b.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,i,r,o,a]=t;await fc({parentRepoPath:Vi.resolve(n),parentMissionId:parseInt(i,10),childRepoPath:Vi.resolve(r),childMissionId:parseInt(o,10),relationship:a}),console.log(""),console.log(` ${b.green("\u2714")} ${b.bold("Missions linked successfully")}`),console.log(` ${b.dim("Parent: ")} ${n} (Mission ${i})`),console.log(` ${b.dim("Child: ")} ${r} (Mission ${o})`),a&&console.log(` ${b.dim("Relationship: ")} ${a}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${b.red("\u2716")} Please provide at least one repository path`);return}let n,i=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):i.push(Vi.resolve(t[o]));let r=await wc({repoPaths:i,name:n});if(console.log(""),console.log(` ${b.green("\u2714")} ${b.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${b.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${b.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${b.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${b.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}G();G();var Ji=w.child({module:"strategy-normalizer"}),ze=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(i){return Ji.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:this.normalizeSteps(t)}}static normalizeSteps(e){return Array.isArray(e)?e.map((t,n)=>{if(typeof t=="string")return{id:`step-${n}`,description:t,status:"pending"};if(typeof t=="object"&&t!==null){let{verification:i,...r}=t,o=this.sanitizeVerification(i);return{...r,id:t.id||`step-${n}`,description:t.description||t.content||t.name||`Step ${n+1}`,status:t.status||"pending",dependencies:t.dependencies||t.deps,...o!==void 0?{verification:o}:{}}}return{id:`step-${n}`,description:String(t),status:"pending"}}):e.steps&&Array.isArray(e.steps)?this.normalizeSteps(e.steps):typeof e=="object"?Object.entries(e).map(([t,n],i)=>{if(typeof n=="string")return{id:t,description:n,status:"pending"};if(typeof n=="object"&&n!==null){let{verification:r,...o}=n,a=this.sanitizeVerification(r);return{...o,id:t,description:n.description||n.content||n.name||t,status:n.status||"pending",dependencies:n.dependencies||n.deps,...a!==void 0?{verification:a}:{}}}return{id:t||`step-${i}`,description:String(n),status:"pending"}}):[]}static looksLikeNaturalLanguage(e){return e.trim().split(/\s+/).length>=5}static VALID_VERIFICATION_TYPES=new Set(["usage","import","pattern"]);static sanitizeVerificationRule(e){if(!e)return null;if(typeof e=="string")return this.looksLikeNaturalLanguage(e)?(Ji.warn({verification:e},"Stripping natural-language verification rule (not a valid pattern)"),null):{type:"pattern",target:e};if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.target!="string"||!t.target)return Ji.warn({verification:e},"Stripping verification rule without target"),null;if(this.looksLikeNaturalLanguage(t.target))return Ji.warn({verification:e},"Stripping natural-language verification target (not a valid pattern)"),null;let i={type:typeof t.type=="string"&&this.VALID_VERIFICATION_TYPES.has(t.type)?t.type:"pattern",target:t.target};return typeof t.context=="string"&&(i.context=t.context),typeof t.filePath=="string"&&(i.filePath=t.filePath),i}static sanitizeVerification(e){if(e!=null){if(Array.isArray(e)){let t=e.map(n=>this.sanitizeVerificationRule(n)).filter(Boolean);return t.length>0?t.length===1?t[0]:t:void 0}return this.sanitizeVerificationRule(e)??void 0}}static stringify(e){return JSON.stringify(e,null,2)}static validate(e){let t=[];if(!e)return{valid:!0,errors:[]};try{let n=this.normalize(e),i=new Set;for(let r of n.steps)if(i.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),i.add(r.id),r.dependencies)for(let o of r.dependencies)i.has(o)||t.push(`Step "${r.id}" depends on non-existent step "${o}"`);return{valid:t.length===0,errors:t}}catch(n){return t.push(`Strategy validation failed: ${n instanceof Error?n.message:String(n)}`),{valid:!1,errors:t}}}};G();import rr from"fs";import vc from"path";import Md from"os";var Ad=[{id:"step-0",description:"Analyze impact: identify dependents and call sites",status:"pending"},{id:"step-1",description:"Implement refactor and update call sites",status:"pending"},{id:"step-2",description:"Run tests and verify behavior; update docs if needed",status:"pending"}],$d=[{id:"step-0",description:"Capture requirements and acceptance criteria",status:"pending"},{id:"step-1",description:"Implement feature with tests",status:"pending"},{id:"step-2",description:"Integrate and verify end-to-end",status:"pending"}],Pd=[{id:"step-0",description:"Reproduce the bug and document steps",status:"pending"},{id:"step-1",description:"Diagnose root cause and plan fix",status:"pending"},{id:"step-2",description:"Apply fix and add/update regression test",status:"pending"},{id:"step-3",description:"Verify fix and run full test suite",status:"pending"}],Rc=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:Ad},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:$d},{id:"bug-fix",name:"Bug fix",description:"Reproduction \u2192 diagnosis \u2192 fix \u2192 regression test",defaultGoal:"Fix {{target}}: reproduce, diagnose, fix, and add regression test.",steps:Pd}],or=new Map(Rc.map(s=>[s.id,s])),Yi=!1;function Nd(){if(Yi)return;let s=vc.join(Md.homedir(),".shadow","templates");if(!rr.existsSync(s)){w.debug({templatesDir:s},"Custom templates directory does not exist"),Yi=!0;return}try{let e=rr.readdirSync(s).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=vc.join(s,t),i=rr.readFileSync(n,"utf8"),r=JSON.parse(i);if(!r.id||!r.name||!r.defaultGoal||!r.steps){w.warn({file:t,template:r},"Invalid custom template structure - skipping");continue}if(!Array.isArray(r.steps)||r.steps.length===0){w.warn({file:t},"Template has no steps - skipping");continue}if(Rc.some(o=>o.id===r.id)){w.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}or.set(r.id,r),w.info({file:t,templateId:r.id},"Loaded custom template")}catch(n){w.warn({file:t,error:n},"Failed to load custom template")}Yi=!0}catch(e){w.warn({error:e,templatesDir:s},"Failed to read custom templates directory"),Yi=!0}}function Dd(s){return Nd(),or.get(s)}function Od(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function Tc(s,e,t={}){let n=Dd(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(or.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=Od(n.defaultGoal,{...t,target:i}),a=ze.normalize({steps:n.steps}),c=ze.stringify(a);return{name:r,goal:o,strategy:c}}Y();Cn();import kc from"node:path";var An=w.child({module:"mcp:tools:ops:plan"}),Fd=["name","goal","strategy","parentId","outcomeContract"],Wd="Mission update requires at least one updatable field: name, goal, strategy, parentId, outcomeContract.",zd="Mission requires name and goal (or templateId with optional templateVars).";async function Cc(s){let{repoPath:e,name:t,goal:n,strategy:i,workingSet:r,missionId:o,parentId:a,outcomeContract:c,templateId:l,templateVars:p}=s,{missions:u}=N.getInstance(e),d=be(e),h=Ke(e);An.info({repoPath:e,name:t,missionId:o,templateId:l},"Planning mission");try{let m=t,f=n,S=i;if(!o&&l){let E=Tc(l,t,p||{});m=m??E.name,f=f??E.goal,S=S??E.strategy}let y,_;if(o){let E=u.findById(o);if(!E)throw new Error(`Mission ${o} not found.`);let R;if(i!==void 0)if(i){let k=ze.normalize(i);R=ze.stringify(k);let F=ze.validate(R);F.valid||An.warn({errors:F.errors,strategy:i},"Strategy validation warnings detected")}else R=null;let T={commit_sha:h};if(t!==void 0&&(T.name=t),n!==void 0&&(T.goal=n),R!==void 0&&(T.strategy_graph=R),a!==void 0&&(T.parent_id=a),c!==void 0&&(T.outcome_contract=c),Object.keys(T).length===1)throw new Error(Wd);u.update(o,{...T}),y=o,_=`Mission "${t??E.name}" updated.`}else{if(!m||!f)throw new Error(zd);let E=null;if(S){let R=ze.normalize(S);E=ze.stringify(R);let T=ze.validate(E);T.valid||An.warn({errors:T.errors,strategy:S},"Strategy validation warnings detected")}if(y=u.create({name:m,goal:f,strategy_graph:E,status:"planned",git_branch:d,commit_sha:h,parent_id:a||null,verification_context:null,outcome_contract:c||null}),r&&r.length>0){u.clearWorkingSet(Number(y));for(let R of r){let T=kc.isAbsolute(R)?R:kc.join(e,R);u.addToWorkingSet(Number(y),T,"planned")}}_=`Mission "${m}" planned.`}try{await new Ze(e).syncMissionToGitNotes(Number(y))}catch(E){An.info({missionId:y,...Re(E)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:y,status:"planned",message:_,strategy_saved:!!S,working_set_populated:r?.length||0,working_set_seeded:r?.length||0,contract_saved:!!c,updateable_fields:Fd,from_template:l??void 0,commit:h},null,2)}]}}catch(m){let f=qt(m);throw An.error({repoPath:e,...Re(m)},"Failed to plan mission"),new Error(`Failed to plan mission: ${f}`)}}G();Y();var Ki=class s{constructor(e){this.intentLogs=e}static RECENCY_HALF_LIFE_HOURS=48;static WEIGHTS={recency:.4,activity:.3,statusBoost:.2,blockerBoost:.1};score(e){if(e.length===0)return[];let t=Math.floor(Date.now()/1e3),n=e.map(c=>c.id),i=this.intentLogs.countByMissions(n),r=this.intentLogs.findMissionsWithBlockers(n),o=Math.max(1,...Object.values(i));return e.map(c=>{let l=this.computeRecency(c.updated_at,t),p=(i[c.id]||0)/o,u=this.computeStatusBoost(c.status),d=r.has(c.id)?1:0,h=s.WEIGHTS,m=l*h.recency+p*h.activity+u*h.statusBoost+d*h.blockerBoost;return{mission:c,score:Math.round(m*1e3)/1e3,breakdown:{recency:Math.round(l*1e3)/1e3,activity:Math.round(p*1e3)/1e3,blockerBoost:d,statusBoost:u}}}).sort((c,l)=>l.score-c.score)}computeRecency(e,t){let n=Math.max(0,(t-e)/3600);return Math.pow(.5,n/s.RECENCY_HALF_LIFE_HOURS)}computeStatusBoost(e){switch(e){case"in-progress":return 1;case"verifying":return .8;case"planned":return .4;default:return 0}}};Y();G();var Hd=w.child({module:"collision-service"}),Qi=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=be(this.repoPath);if(!e)return[];let{missions:t}=N.getInstance(this.repoPath),n=t.findActive(e)??[],i=new Set(n.map(l=>l.id)),r=(t.findActive()??[]).filter(l=>!i.has(l.id)),o=[],a=new Set;for(let l of r){let p=l.git_branch||"unknown",u=[e,p].sort().join("::");Hd.info({branch:p,currentBranch:e,missionId:l.id},"Checking predictive collisions"),p!==e&&!a.has(u)&&(a.add(u),Vo(this.repoPath,e,p)&&o.push({branch:p,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${p}'.`}))}let c=this.analyzeMissionOverlaps([...i]);for(let l of c)o.push({branch:e,mission_id:l.missionB.id,mission_name:l.missionB.name,type:"intent",description:`Logical conflict: Mission '${l.missionA.name}' overlaps with '${l.missionB.name}'.`,conflictingFiles:l.sharedFiles});return o}analyzeMissionOverlaps(e){let t=be(this.repoPath);if(!t)return[];let{missions:n}=N.getInstance(this.repoPath),i=n.findActive(t)??[],r=e&&e.length>0?i.filter(a=>e.includes(a.id)):i,o=[];for(let a=0;a<r.length;a+=1){let c=r[a],l=new Set(n.getWorkingSet(c.id).map(p=>p.file_path));for(let p=a+1;p<r.length;p+=1){let u=r[p],d=n.getWorkingSet(u.id).map(m=>m.file_path),h=Array.from(new Set(d.filter(m=>l.has(m)))).sort();h.length!==0&&o.push({missionA:{id:c.id,name:c.name},missionB:{id:u.id,name:u.name},sharedFiles:h})}}return o}};Y();var ar=new Set(["planned","in-progress","verifying","suspended"]),$n=class{constructor(e){this.repoPath=e}buildPlanForParent(e){let{missions:t,claims:n}=N.getInstance(this.repoPath);if(!t.findById(e))throw new Error(`Mission ${e} not found`);let o=t.findByParentId(e).filter(d=>ar.has(d.status)).map(d=>{let h=t.getWorkingSet(d.id).map(m=>m.file_path);return{id:d.id,name:d.name,status:d.status,files:h}}),a=this.computeOverlapMatrix(o),c=this.colorIntoWaves(o,a),l=new Set(o.map(d=>d.id)),p=Array.from(new Set(o.flatMap(d=>d.files))),u=n.getClaimsByFiles(p).filter(d=>!l.has(d.mission_id)).map(d=>({file_path:d.file_path,mission_id:d.mission_id,mission_name:d.mission_name,mission_status:d.mission_status,mission_branch:d.mission_branch}));return this.composePlan(o,a,u,e)}buildPlanForMissions(e,t={}){let{includeClaimCheck:n=!0}=t,{missions:i,claims:r}=N.getInstance(this.repoPath),a=i.findByIds(e).filter(p=>ar.has(p.status)).map(p=>({id:p.id,name:p.name,status:p.status,files:i.getWorkingSet(p.id).map(u=>u.file_path)})),c=this.computeOverlapMatrix(a),l=n?this.computeExternalClaims(a,r.getClaimsByFiles(Array.from(new Set(a.flatMap(p=>p.files))))):[];return this.composePlan(a,c,l)}toHandlerPayload(e){let t=new Map(e.child_missions.map(p=>[p.id,p])),n=e.waves.map(p=>({waveIndex:p.wave,missions:p.missions.map(u=>{let d=t.get(u);return{id:u,name:d?.name??`Mission ${u}`,workingSetSize:d?.file_count??0}})})),i=e.overlap_matrix.map(p=>({missionA:p.mission_a,missionB:p.mission_b,sharedFiles:p.shared_files})),r=e.external_claims.map(p=>({filePath:p.file_path,claimedByMissionId:p.mission_id,claimedByMissionName:p.mission_name,claimedByMissionStatus:p.mission_status,claimedByMissionBranch:p.mission_branch})),o=e.child_missions.length,a=n.length,c=n[0]?.missions.length??0,l=`${o} missions in ${a} waves, ${c} parallelizable in wave 1`;return{waves:n,overlapMatrix:i,externalClaims:r,summary:l}}groupMissionsForParallelism(e){let{missions:t}=N.getInstance(this.repoPath),i=t.findByIds(e).filter(o=>ar.has(o.status)).map(o=>({id:o.id,name:o.name,status:o.status,files:t.getWorkingSet(o.id).map(a=>a.file_path)})),r=this.computeOverlapMatrix(i);return this.colorIntoWaves(i,r)}composePlan(e,t,n,i){let r=this.colorIntoWaves(e,t);return{...i!==void 0?{parent_mission_id:i}:{},mission_ids:e.map(o=>o.id),child_missions:e.map(o=>({id:o.id,name:o.name,status:o.status,file_count:o.files.length})),waves:r,overlap_matrix:t,external_claims:n}}computeExternalClaims(e,t){let n=new Set(e.map(i=>i.id));return t.filter(i=>!n.has(i.mission_id)).map(i=>({file_path:i.file_path,mission_id:i.mission_id,mission_name:i.mission_name,mission_status:i.mission_status,mission_branch:i.mission_branch}))}computeOverlapMatrix(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n],r=new Set(i.files);for(let o=n+1;o<e.length;o+=1){let a=e[o],c=a.files.filter(l=>r.has(l));c.length!==0&&t.push({mission_a:i.id,mission_b:a.id,shared_files:Array.from(new Set(c)).sort()})}}return t}colorIntoWaves(e,t){if(e.length===0)return[];let n=new Map;for(let a of e)n.set(a.id,new Set);for(let a of t)n.get(a.mission_a)?.add(a.mission_b),n.get(a.mission_b)?.add(a.mission_a);let i=[...e].sort((a,c)=>{let l=(n.get(c.id)?.size??0)-(n.get(a.id)?.size??0);return l!==0?l:a.id-c.id}),r=new Map;for(let a of i){let c=new Set;for(let p of n.get(a.id)??[]){let u=r.get(p);u!==void 0&&c.add(u)}let l=1;for(;c.has(l);)l+=1;r.set(a.id,l)}let o=new Map;for(let[a,c]of r.entries()){let l=o.get(c)??[];l.push(a),o.set(c,l)}return[...o.entries()].sort((a,c)=>a[0]-c[0]).map(([a,c])=>({wave:a,missions:c.sort((l,p)=>l-p)}))}};var Zi=class{constructor(e){this.repoPath=e}async getBriefing(e={}){let{missionId:t,scope:n="mission",altitude:i,activeMissionsLimit:r,recentActivityLimit:o,compact:a}=e,c=a??(i==="orbit"||i==="atmosphere"),l=o??(i==="orbit"?0:i==="ground"?20:10),{missions:p,intentLogs:u}=N.getInstance(this.repoPath),d=Ke(this.repoPath),h=be(this.repoPath);return n==="project"?this.getProjectBriefing({altitude:i,activeMissionsLimit:r,recentActivityLimit:l,compact:c,currentBranch:h,currentCommit:d}):this.getMissionBriefing({missionId:t,altitude:i,recentActivityLimit:l,currentBranch:h,currentCommit:d})}async getProjectBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i,claims:r}=N.getInstance(t),{altitude:o,activeMissionsLimit:a,recentActivityLimit:c,compact:l,currentBranch:p,currentCommit:u}=e,d=n.findActive(p||void 0),h=d.length;a&&d.length>a&&(d=d.slice(0,a));let m=n.findParentOnlyIds(d),f=new Set(m),S=d.filter(g=>!f.has(g.id)),_=new Ki(i).score(S),E=.15,R=3,T=l&&_.length>R?_.filter((g,x)=>x<R||g.score>=E):_,k=T.map(g=>g.mission),F=new Map(T.map(g=>[g.mission.id,g.score])),B=new Set(d.map(g=>g.id)),M=r.listClaims().filter(g=>B.has(g.mission_id)).map(g=>({file_path:g.file_path,mission_id:g.mission_id,mission_name:g.mission_name,mission_status:g.mission_status,mission_branch:g.mission_branch,claimed_at:g.claimed_at,updated_at:g.updated_at})),v=new $n(t).groupMissionsForParallelism(d.map(g=>g.id)),I=v.length,$=new Map;for(let g of M)$.set(g.mission_id,($.get(g.mission_id)??0)+1);let P=g=>({id:g.id,name:g.name,goal:g.goal,status:g.status,relevance:F.get(g.id),claimedFileCount:$.get(g.id)??0}),U=g=>({...g,claimedFileCount:$.get(g.id)??0});if(o==="orbit")return{scope:"project",altitude:"orbit",counts:n.getStats(),next_work_candidates:k.map(P),parallel_wave_count:I,claims_count:M.length,meta:{current_branch:p,activeMissionsTotal:h,ember:this.getEmberLabel(t)}};let A={},H=[];for(let g of d)g.parent_id!=null?(A[g.parent_id]||(A[g.parent_id]=[]),A[g.parent_id].push(g)):H.push(g);let L=n.findRecentCompleted(5).map(P),D=c>0?i.findRecentDecisionActivity(c):void 0,J=m.map(g=>{let x=d.find(C=>C.id===g);return{parent:l?{...U(x),strategy_graph:void 0,verification_context:void 0}:U(x),children:(A[g]??[]).map(U)}}),z=H.filter(g=>!f.has(g.id)).map(U);return{scope:"project",altitude:o||"atmosphere",counts:n.getStats(),analytics:n.getAnalytics(),hierarchy:J.length>0?J:void 0,standalone_active:z.length>0?z:void 0,active_missions:J.length===0?l?d.map(g=>({...U(g),strategy_graph:void 0})):d.map(U):void 0,claims:M,parallel_groups:v,next_work_candidates:k.map(P),recent_completed:L,recent_activity:D,meta:{current_branch:p,current_commit:u,activeMissionsTotal:h,active_limit_applied:!!a,relevance_filtered:T.length<_.length?{shown:T.length,total:_.length}:void 0,ember:this.getEmberLabel(t)}}}getEmberLabel(e){try{let{status:t,progress:n}=Li(e);if(t==="idle")return;if(t==="done")return"symbols: fully embedded";let[i,r]=n.split("/").map(Number),o=r>0?Math.round(i/r*100):0;return t==="running"?`symbols: warming ${n} (${o}%)`:`symbols: ${t} ${n}`}catch{return}}async getMissionBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i,claims:r}=N.getInstance(t),{missionId:o,altitude:a,recentActivityLimit:c,currentBranch:l,currentCommit:p}=e,u;if(o?u=n.findById(o):u=n.findActive(l||void 0)[0],!u)return null;let d=null;try{u.strategy_graph&&(d=JSON.parse(u.strategy_graph))}catch{}if(a==="orbit")return{altitude:"orbit",mission:{id:u.id,name:u.name,goal:u.goal,status:u.status,last_updated:new Date(u.updated_at*1e3).toISOString()},strategy_snapshot:d};let h="No external shadow changes detected.";try{new on(t).analyzeGhostChanges(u.commit_sha||void 0),h="Shadow Trace completed: Checked for external modifications."}catch{}let m={repaired:0,failed:0};try{m=new it(t).detectAndRepairShifts()}catch{}let f=n.getHandoffs(u.id).map(y=>{let _=null;try{_=JSON.parse(y.metadata??"")}catch{}return{artifactId:y.id,kind:y.identifier,confidence:_?.confidence??null,findingsCount:_?.findings?.length??0,risksCount:_?.risks?.length??0,missionsCreated:_?.missionsCreated??[],createdAt:y.created_at}}),S={altitude:a||"atmosphere",mission:{id:u.id,name:u.name,goal:u.goal,status:u.status,last_updated:new Date(u.updated_at*1e3).toISOString(),git_branch:u.git_branch,commit_sha:u.commit_sha,outcome_contract:u.outcome_contract},artifacts:n.getArtifacts(u.id),handoffs:f,shadow_trace:{ghost_analysis:h,symbols_repaired:m.repaired,symbols_missing:m.failed},context:{current_commit:p,working_set:n.getWorkingSet(u.id).map(y=>y.file_path)},claims:r.getClaimsForMission(u.id),parallel_groups:new $n(t).groupMissionsForParallelism(n.findActive(l||void 0).map(y=>y.id)),strategy_snapshot:d,recent_activity:a==="ground"?i.findByMission(u.id,c||20):i.findByMissionPreferCrystal(u.id,15),ancestor_activity_summary:[],predictive_collisions:[]};try{let y=new Qi(t);S.predictive_collisions=await y.analyzePotentialCollisions()}catch{}if(u.parent_id){let y=a==="ground"?i.findByMission(u.parent_id,5):i.findByMissionPreferCrystal(u.parent_id,3);S.ancestor_activity_summary=y.map(_=>({type:_.type,content:_.content,date:new Date(_.created_at*1e3).toISOString()}))}return S}};var Ic=w.child({module:"mcp:tools:ops:briefing"});async function Lc(s){let{repoPath:e,scope:t="mission"}=s;Ic.info({repoPath:e,missionId:s.missionId,scope:t},"Generating briefing");try{let i=await new Zi(e).getBriefing(s);if(!i&&t==="mission")return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let r;if(t==="project"){let o=i.counts;r=i.next_work_candidates.length===0&&o.active===0?{tool:"shadow_ops_plan",reason:"No open work; create a mission"}:{tool:"shadow_ops_track",reason:"Select a mission from hierarchy or next_work_candidates to execute"}}return{content:[{type:"text",text:JSON.stringify(i,null,2)}],suggestedNext:r}}catch(n){throw Ic.error({error:n,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${n instanceof Error?n.message:String(n)}`)}}G();Y();Y();G();G();var Bd=w.child({module:"reasoning-engine"}),Xi=class{analyze(e){Bd.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[],sourceMissions:[]};for(let i of e){let r=i.content.toLowerCase(),o=this.matchesContext(r,i.type),a=this.matchesDecision(r,i.type),c=this.matchesConsequence(r,i.type),l=this.matchesRecommendation(r,i.type);o?t.context.push(i.content):a?t.decisions.push(i.content):l?t.recommendations.push(i.content):c?t.consequences.push(i.content):i.type==="decision"?t.decisions.push(i.content):i.type==="discovery"||i.type==="fix"?t.consequences.push(i.content):t.unclassified.push(i.content)}let n=new Set;for(let i of e)i.mission_id!=null&&n.add(i.mission_id);return t.sourceMissions=[...n],t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(i=>e.includes(i))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(i=>e.includes(i))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(i=>e.includes(i))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(i=>e.includes(i))}};var es=w.child({module:"briefing-engine"}),mt=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=N.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Xi,this.persistencePivot=new Ze(e)}async distillMission(e,t=!0){es.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.gatherConsolidatedLogs(e);if(n.length===0)return{missionId:e,adr:"No intent logs found for this mission.",metrics:{totalLogs:0,symbolCount:0}};let i=this.reasoningEngine.analyze(n),r=new Set(n.map(a=>a.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
|
|
976
1031
|
|
|
977
1032
|
`;if(o+=`## Summary of Intent
|
|
978
1033
|
`,o+=`Collected ${n.length} intent events across ${r.size} symbols.
|
|
@@ -994,8 +1049,8 @@ WHERE i.resolved_path IS NOT NULL`);return t.join(`
|
|
|
994
1049
|
`}),o+=`
|
|
995
1050
|
`),o+=`
|
|
996
1051
|
---
|
|
997
|
-
*Generated by Liquid Shadow Reasoning Engine v1*`,t){this.intentLogs.create({mission_id:e,type:"adr",content:o,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:null});try{await this.persistencePivot.syncMissionToGitNotes(e),Hi.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(a){Hi.error({missionId:e,error:a},"Failed to sync ADR to Git Notes")}}else Hi.info({missionId:e},"Tactical Briefing synthesized (dry-run).");return{missionId:e,adr:o,metrics:{totalLogs:n.length,symbolCount:r.size}}}gatherConsolidatedLogs(e,t=0){let n=this.intentLogs.findByMissionPreferCrystal(e,500);if(t>2)return n;let i=this.missions.findByParentId(e);for(let r of i)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};q();import{Visitor as xd}from"@swc/core/Visitor.js";import*as rc from"@swc/core";var vd=S.child({module:"verification-engine"}),Gs=class extends xd{foundUsage=!1;foundImport=!1;rule;currentFunctionName=null;constructor(e){super(),this.rule=e}visitImportDeclaration(e){return this.rule.type==="import"&&e.source.value===this.rule.target&&(this.foundImport=!0),super.visitImportDeclaration(e)}visitFunctionDeclaration(e){let t=this.currentFunctionName;this.currentFunctionName=e.identifier.value;let n=super.visitFunctionDeclaration(e);return this.currentFunctionName=t,n}visitCallExpression(e){return this.rule.type==="usage"&&e.callee.type==="Identifier"&&e.callee.value===this.rule.target&&(!this.rule.context||this.currentFunctionName===this.rule.context)&&(this.foundUsage=!0),super.visitCallExpression(e)}},zi=class{async verify(e,t){try{let n=await rc.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new Gs(t);i.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=i.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=i.foundUsage,!r){let a=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${a} not found.`)}}else t.type==="pattern"&&(r=new RegExp(t.target).test(e),r||o.push(`Required pattern "${t.target}" not found.`));return{passed:r,errors:o}}catch(n){return vd.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};gn();import oc from"path";import Ui from"fs";var Le=S.child({module:"mcp:tools:ops:track"});function qs(s,e){return oc.isAbsolute(e)?e:oc.join(s,e)}async function ac(s,e,t){let{missions:n,intentLogs:i}=O.getInstance(s),r=n.findById(e);if(!r?.parent_id)return;let o=n.findByParentId(r.parent_id);if(!o.every(l=>l.status==="completed"))return;let c=n.findById(r.parent_id);if(!(!c||c.status==="completed")){Le.info({parentId:c.id,childCount:o.length},"All children completed \u2014 cascading parent completion"),n.updateStatus(c.id,"completed",t||void 0),n.clearWorkingSet(c.id),i.create({mission_id:c.id,type:"system",content:`Parent auto-completed: all ${o.length} child missions finished`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:t});try{await new tt(s).distillMission(c.id),Le.info({parentId:c.id},"Parent Auto-Synthesis completed")}catch(l){Le.info({parentId:c.id,...ye(l)},"Parent Auto-Synthesis deferred")}try{await new Fe(s).syncMissionToGitNotes(c.id)}catch(l){Le.info({parentId:c.id,...ye(l)},"Parent Git Notes sync deferred")}await ac(s,c.id,t)}}async function cc(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:a}=s,{missions:c,intentLogs:l}=O.getInstance(e),p=De(e);Le.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:a?.length},"Updating mission status");try{if(a&&Array.isArray(a))for(let h of a)c.addArtifact(t,h.type,h.identifier,h.metadata);let u=[];if(o&&Array.isArray(o)&&u.push(...o),n&&i&&u.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(c.updateStatus(t,i,p||void 0),i==="completed"&&c.clearWorkingSet(t),l.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),i==="completed"){try{await new tt(e).distillMission(t),Le.info({missionId:t},"Auto-Synthesis completed successfully")}catch(h){Le.info({missionId:t,...ye(h)},"Auto-Synthesis deferred or failed")}await ac(e,t,p)}if(!u.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:i,message:"Mission status updated successfully.",artifacts_added:a?.length||0,commit:p},null,2)}]}}if(u.length===0&&(!a||a.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let d=[];for(let h of u){let{stepId:m,status:f,contextPivot:_}=h,g=c.findById(t);if(!g)throw new Error(`Mission ID ${t} not found`);let b=JSON.parse(g.strategy_graph||"{}"),w=null;if(Array.isArray(b)?w=b.find(x=>x.id===m):b.nodes&&Array.isArray(b.nodes)?w=b.nodes.find(x=>x.id===m):b.steps?Array.isArray(b.steps)?w=b.steps.find(x=>x.id===m):w=b.steps[m]:b[m]&&(w=b[m]),!w)throw new Error(`Step ID "${m}" not found`);if(f==="completed"&&w.verification){let x=new zi,R=Array.isArray(w.verification)?w.verification:[w.verification];for(let k of R){let D=k;if(typeof k=="string"&&(D={type:"pattern",target:k}),!D||!D.target){Le.warn({rule:k},"Skipping invalid verification rule (missing target)");continue}let U=D.filePath;if(U&&(U=qs(e,U)),U){if(!Ui.existsSync(U))throw new Error(`Verification failed: File not found at ${U}`);let P=await x.verify(Ui.readFileSync(U,"utf8"),D);if(!P.passed)throw new Error(`Verification failed: ${P.errors.join("")}`)}else{let P=c.getWorkingSet(t),E=!1;P.length===0&&Le.warn("No working set files to verify against for rule");for(let T of P){let I=qs(e,T.file_path);if(!Ui.existsSync(I))continue;if((await x.verify(Ui.readFileSync(I,"utf8"),D)).passed){E=!0;break}}if(!E)throw new Error(`Verification failed: Rule "${D.target}" not satisfied in any working set file.`)}}}if(w.status=f,c.update(t,{strategy_graph:JSON.stringify(b),commit_sha:p}),l.create({mission_id:t,type:"system",content:`Step "${m}" updated to "${f}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),_){let x=_.trim();if(x.startsWith("{")||x.startsWith("["))try{let R=JSON.parse(x);if(R.files&&Array.isArray(R.files)){c.clearWorkingSet(t);for(let k of R.files)c.addToWorkingSet(t,qs(e,k))}}catch(R){Le.warn({error:R},"Failed to apply context pivot")}}d.push({stepId:m,status:f})}try{await new Fe(e).syncMissionToGitNotes(t)}catch(h){Le.info({missionId:t,...ye(h)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,updates:d,artifacts_added:a?.length||0,message:"Status updated",commit:p},null,2)}]}}catch(u){let d=At(u);throw Le.error({repoPath:e,...ye(u)},"Failed to update status"),new Error(`Failed to update status: ${d}`)}}q();var dc=S.child({module:"mcp:tools:ops:graph"});async function mc(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;dc.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(uc(),pc));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw dc.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}V();q();import hc from"node:path";var Xt=S.child({module:"mcp:tools:ops:log"}),Td=["in-progress","verifying"];function Rd(s){for(let e of Td){let t=s.find(n=>n.status===e);if(t)return t.id}return s[0]?.id??null}function kd(s,e){return e?hc.isAbsolute(e)?e:hc.join(s,e):null}async function fc(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o,standalone:a}=s;Xt.info({repoPath:e,type:n,symbolName:o,standalone:a},"Logging intent");let{missions:c,exports:l,intentLogs:p}=O.getInstance(e),u=kd(e,r);try{let d=t??null,h=me(e)||void 0;if(a)d=null,Xt.debug("Standalone intent requested; mission auto-resolution skipped");else if(d){if(!c.findById(d))throw new Error(`Mission ${d} not found. Use shadow_ops_briefing to see available missions.`)}else{let w=c.findActive(h);w.length>0?(d=Rd(w),Xt.debug({missionId:d,currentBranch:h},"Auto-resolved to active mission on current branch")):(d=null,Xt.debug({currentBranch:h},"No active mission found on current branch; logging as system/unlinked intent"))}let m=null,f=null,_=o||null,g=u;if(o){let x=(u?l.findByNameAndFile(o,u):l.findByName(o))[0];x?(m=x.id,f=x.signature,_=x.name,g=x.file_path||g):Xt.warn({symbolName:o,filePath:u??r},"Symbol not found for intent linking")}let b=p.create({mission_id:d,symbol_id:m,file_path:g,type:n,content:i,confidence:1,symbol_name:_,signature:f,commit_sha:null});return d&&g&&c.addToWorkingSet(d,g,m?"symbol":"intent"),{content:[{type:"text",text:JSON.stringify({logId:b,missionId:d,symbolId:m,status:"logged",message:m?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(d){throw Xt.error({error:d,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${d instanceof Error?d.message:String(d)}`)}}V();q();var gc=S.child({module:"mcp:tools:ops:synthesize"});async function yc(s){let{repoPath:e,missionId:t}=s;gc.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=O.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new tt(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics},null,2)}]}}catch(i){throw gc.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}import Cd from"path";var ne={...y,box:se,table:jn,list:Nr};async function bc(s){let[e,...t]=s;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${ne.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${ne.bold("Actions: ")}`),console.log(` ${ne.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${ne.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${ne.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${ne.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${ne.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${ne.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await Y(async()=>{let n=t[0]?Cd.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${ne.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let a=await nc({repoPath:n,name:r,goal:o}),c=JSON.parse(a.content[0].text);console.log(` ${ne.green("\u2714")} Mission planned (ID: ${c.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${ne.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await cc({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${ne.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...a]=t;if(!r||!o||a.length===0){console.error(` ${ne.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await fc({repoPath:n,missionId:parseInt(r),type:o,content:a.join(" ")}),console.log(` ${ne.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${ne.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await yc({repoPath:n,missionId:parseInt(r)});console.log(""),ne.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await mc({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i=await sc({repoPath:n});if(i.content&&i.content[0]){let r=i.content[0].text;try{let o=JSON.parse(r);if(o.mission){console.log(""),console.log(ne.bold(ne.cyan(` Mission Dashboard: ${o.mission.name} `))),ne.box("Tactical Goal",o.mission.goal,"cyan");let a=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",c=[["Status",ne.bold(ne[a](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];ne.table(["Field","Value"],c),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${ne.bold("Recent Activity:")}`),ne.list(o.recent_activity.slice(0,5).map(l=>`${ne.dim(`[${l.type.toUpperCase()}]`)} ${l.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import Js from"path";async function _c(s){let[e,...t]=s;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${y.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${y.bold("Actions: ")}`),console.log(` ${y.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${y.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await Y(async()=>{let n=t[0]?Js.resolve(t[0]):process.cwd();if(e==="symbol"){let i=t[1];if(!i){console.error(` ${y.red("\u2716")} Please provide a symbol name`);return}let r=await Kt({repoPath:n,symbolName:i});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let i=t[1];if(!i){console.error(` ${y.red("\u2716")} Please provide a file path`);return}let r=Js.isAbsolute(i)?i:Js.join(n,i),o=await Ci({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var Ec=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],Id=["--help","-h","--version","-v","--dir","-d"],Ld={index:["--output","-o","--level","-l","--subPath","--force","--deep"],tree:["--subPath","--depth","-d"],trace:["--dir","-d"],"search-config":["--dir","-d","--kind"],"search-concept":["--dir","-d","--interactive","-i"],"search-symbol":["--dir","-d","--interactive","-i"],"search-fuzzy":["--dir","-d","--interactive","-i"]};function $d(){let s=Object.entries(Ld).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
|
|
998
|
-
`),e=
|
|
1052
|
+
*Generated by Liquid Shadow Reasoning Engine v1*`,t){this.intentLogs.create({mission_id:e,type:"adr",content:o,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:null});try{await this.persistencePivot.syncMissionToGitNotes(e),es.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(a){es.error({missionId:e,error:a},"Failed to sync ADR to Git Notes")}}else es.info({missionId:e},"Tactical Briefing synthesized (dry-run).");return{missionId:e,adr:o,metrics:{totalLogs:n.length,symbolCount:r.size}}}gatherConsolidatedLogs(e,t=0){let n=this.intentLogs.findByMissionPreferCrystal(e,500);if(t>2)return n;let i=this.missions.findByParentId(e);for(let r of i)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};G();import{Visitor as Ud}from"@swc/core/Visitor.js";import*as Mc from"@swc/core";var jd=w.child({module:"verification-engine"}),cr=class extends Ud{foundUsage=!1;foundImport=!1;rule;currentFunctionName=null;constructor(e){super(),this.rule=e}visitImportDeclaration(e){return this.rule.type==="import"&&e.source.value===this.rule.target&&(this.foundImport=!0),super.visitImportDeclaration(e)}visitFunctionDeclaration(e){let t=this.currentFunctionName;this.currentFunctionName=e.identifier.value;let n=super.visitFunctionDeclaration(e);return this.currentFunctionName=t,n}visitCallExpression(e){return this.rule.type==="usage"&&e.callee.type==="Identifier"&&e.callee.value===this.rule.target&&(!this.rule.context||this.currentFunctionName===this.rule.context)&&(this.foundUsage=!0),super.visitCallExpression(e)}},ts=class{async verify(e,t){try{let n=await Mc.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new cr(t);i.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=i.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=i.foundUsage,!r){let a=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${a} not found.`)}}else t.type==="pattern"&&(r=new RegExp(t.target).test(e),r||o.push(`Required pattern "${t.target}" not found.`));return{passed:r,errors:o}}catch(n){return jd.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};Cn();import Ac from"path";import ns from"fs";var Te=w.child({module:"mcp:tools:ops:track"});function lr(s,e){return Ac.isAbsolute(e)?e:Ac.join(s,e)}async function $c(s,e,t){let{missions:n,intentLogs:i}=N.getInstance(s),r=n.findById(e);if(!r?.parent_id)return;let o=n.findByParentId(r.parent_id);if(!o.every(p=>p.status==="completed"))return;let c=n.findById(r.parent_id);if(!c||c.status==="completed")return;Te.info({parentId:c.id,childCount:o.length},"All children completed \u2014 cascading parent completion"),n.updateStatus(c.id,"completed",t||void 0),n.clearWorkingSet(c.id);let{claims:l}=N.getInstance(s);l.releaseAllForMission(c.id),i.create({mission_id:c.id,type:"system",content:`Parent auto-completed: all ${o.length} child missions finished`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:t});try{await new mt(s).distillMission(c.id),Te.info({parentId:c.id},"Parent Auto-Synthesis completed")}catch(p){Te.info({parentId:c.id,...Re(p)},"Parent Auto-Synthesis deferred")}try{await new Ze(s).syncMissionToGitNotes(c.id)}catch(p){Te.info({parentId:c.id,...Re(p)},"Parent Git Notes sync deferred")}await $c(s,c.id,t)}async function Pc(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:a}=s,{missions:c,intentLogs:l}=N.getInstance(e),p=Ke(e);Te.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:a?.length},"Updating mission status");try{if(a&&Array.isArray(a))for(let h of a)c.addArtifact(t,h.type,h.identifier,h.metadata);let u=[];if(o&&Array.isArray(o)&&u.push(...o),n&&i&&u.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(c.updateStatus(t,i,p||void 0),i==="completed"){c.clearWorkingSet(t);let{claims:h}=N.getInstance(e),m=h.releaseAllForMission(t);m>0&&Te.info({missionId:t,released:m},"Auto-released file claims on completion")}if(l.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),i==="completed"){try{await new mt(e).distillMission(t),Te.info({missionId:t},"Auto-Synthesis completed successfully")}catch(h){Te.info({missionId:t,...Re(h)},"Auto-Synthesis deferred or failed")}await $c(e,t,p)}if(!u.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:i,message:"Mission status updated successfully.",artifacts_added:a?.length||0,commit:p},null,2)}]}}if(u.length===0&&(!a||a.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let d=[];for(let h of u){let{stepId:m,status:f,contextPivot:S}=h,y=c.findById(t);if(!y)throw new Error(`Mission ID ${t} not found`);let _=JSON.parse(y.strategy_graph||"{}"),E=null;if(Array.isArray(_)?E=_.find(R=>R.id===m):_.nodes&&Array.isArray(_.nodes)?E=_.nodes.find(R=>R.id===m):_.steps?Array.isArray(_.steps)?E=_.steps.find(R=>R.id===m):E=_.steps[m]:_[m]&&(E=_[m]),!E)throw new Error(`Step ID "${m}" not found`);if(f==="completed"&&E.verification){let R=new ts,T=Array.isArray(E.verification)?E.verification:[E.verification];for(let k of T){let F=k;if(typeof k=="string"){if(k.trim().split(/\s+/).length>=5){Te.warn({rule:k},"Skipping natural-language verification rule");continue}F={type:"pattern",target:k}}if(!F||!F.target){Te.warn({rule:k},"Skipping invalid verification rule (missing target)");continue}if(typeof F.target=="string"&&F.target.trim().split(/\s+/).length>=5){Te.warn({rule:F},"Skipping natural-language verification target");continue}let B=F.filePath;if(B&&(B=lr(e,B)),B){if(!ns.existsSync(B))throw new Error(`Verification failed: File not found at ${B}`);let M=await R.verify(ns.readFileSync(B,"utf8"),F);if(!M.passed)throw new Error(`Verification failed: ${M.errors.join("")}`)}else{let M=c.getWorkingSet(t),v=!1;M.length===0&&Te.warn("No working set files to verify against for rule");for(let I of M){let $=lr(e,I.file_path);if(!ns.existsSync($))continue;if((await R.verify(ns.readFileSync($,"utf8"),F)).passed){v=!0;break}}if(!v)throw new Error(`Verification failed: Rule "${F.target}" not satisfied in any working set file.`)}}}if(E.status=f,c.update(t,{strategy_graph:JSON.stringify(_),commit_sha:p}),l.create({mission_id:t,type:"system",content:`Step "${m}" updated to "${f}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),S){let R=S.trim();if(R.startsWith("{")||R.startsWith("["))try{let T=JSON.parse(R);if(T.files&&Array.isArray(T.files)){c.clearWorkingSet(t);for(let k of T.files)c.addToWorkingSet(t,lr(e,k))}}catch(T){Te.warn({error:T},"Failed to apply context pivot")}}d.push({stepId:m,status:f})}try{await new Ze(e).syncMissionToGitNotes(t)}catch(h){Te.info({missionId:t,...Re(h)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,updates:d,artifacts_added:a?.length||0,message:"Status updated",commit:p},null,2)}]}}catch(u){let d=qt(u);throw Te.error({repoPath:e,...Re(u)},"Failed to update status"),new Error(`Failed to update status: ${d}`)}}G();var Fc=w.child({module:"mcp:tools:ops:graph"});async function Wc(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;Fc.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(Oc(),Dc));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw Fc.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}Y();G();import zc from"node:path";var dn=w.child({module:"mcp:tools:ops:log"}),Gd=["in-progress","verifying"];function qd(s){for(let e of Gd){let t=s.find(n=>n.status===e);if(t)return t.id}return s[0]?.id??null}function Vd(s,e){return e?zc.isAbsolute(e)?e:zc.join(s,e):null}async function Hc(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o,standalone:a}=s;dn.info({repoPath:e,type:n,symbolName:o,standalone:a},"Logging intent");let{missions:c,exports:l,intentLogs:p}=N.getInstance(e),u=Vd(e,r);try{let d=t??null,h=be(e)||void 0;if(a)d=null,dn.debug("Standalone intent requested; mission auto-resolution skipped");else if(d){if(!c.findById(d))throw new Error(`Mission ${d} not found. Use shadow_ops_briefing to see available missions.`)}else{let E=c.findActive(h);E.length>0?(d=qd(E),dn.debug({missionId:d,currentBranch:h},"Auto-resolved to active mission on current branch")):(d=null,dn.debug({currentBranch:h},"No active mission found on current branch; logging as system/unlinked intent"))}let m=null,f=null,S=o||null,y=u;if(o){let R=(u?l.findByNameAndFile(o,u):l.findByName(o))[0];R?(m=R.id,f=R.signature,S=R.name,y=R.file_path||y):dn.warn({symbolName:o,filePath:u??r},"Symbol not found for intent linking")}let _=p.create({mission_id:d,symbol_id:m,file_path:y,type:n,content:i,confidence:1,symbol_name:S,signature:f,commit_sha:null});return d&&y&&c.addToWorkingSet(d,y,m?"symbol":"intent"),{content:[{type:"text",text:JSON.stringify({logId:_,missionId:d,symbolId:m,status:"logged",message:m?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(d){throw dn.error({error:d,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${d instanceof Error?d.message:String(d)}`)}}Y();G();var Bc=w.child({module:"mcp:tools:ops:synthesize"});async function Uc(s){let{repoPath:e,missionId:t}=s;Bc.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=N.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new mt(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics},null,2)}]}}catch(i){throw Bc.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}import Jd from"path";var oe={...b,box:ue,table:ni,list:oo};async function jc(s){let[e,...t]=s;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${oe.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${oe.bold("Actions: ")}`),console.log(` ${oe.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${oe.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${oe.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${oe.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${oe.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${oe.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await Q(async()=>{let n=t[0]?Jd.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${oe.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let a=await Cc({repoPath:n,name:r,goal:o}),c=JSON.parse(a.content[0].text);console.log(` ${oe.green("\u2714")} Mission planned (ID: ${c.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${oe.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await Pc({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${oe.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...a]=t;if(!r||!o||a.length===0){console.error(` ${oe.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await Hc({repoPath:n,missionId:parseInt(r),type:o,content:a.join(" ")}),console.log(` ${oe.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${oe.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await Uc({repoPath:n,missionId:parseInt(r)});console.log(""),oe.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await Wc({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i=await Lc({repoPath:n});if(i.content&&i.content[0]){let r=i.content[0].text;try{let o=JSON.parse(r);if(o.mission){console.log(""),console.log(oe.bold(oe.cyan(` Mission Dashboard: ${o.mission.name} `))),oe.box("Tactical Goal",o.mission.goal,"cyan");let a=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",c=[["Status",oe.bold(oe[a](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];oe.table(["Field","Value"],c),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${oe.bold("Recent Activity:")}`),oe.list(o.recent_activity.slice(0,5).map(l=>`${oe.dim(`[${l.type.toUpperCase()}]`)} ${l.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import ur from"path";async function Gc(s){let[e,...t]=s;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${b.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${b.bold("Actions: ")}`),console.log(` ${b.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${b.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await Q(async()=>{let n=t[0]?ur.resolve(t[0]):process.cwd();if(e==="symbol"){let i=t[1];if(!i){console.error(` ${b.red("\u2716")} Please provide a symbol name`);return}let r=await pn({repoPath:n,symbolName:i});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let i=t[1];if(!i){console.error(` ${b.red("\u2716")} Please provide a file path`);return}let r=ur.isAbsolute(i)?i:ur.join(n,i),o=await Hi({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var qc=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],Yd=["--help","-h","--version","-v","--dir","-d"],Kd={index:["--output","-o","--level","-l","--subPath","--force","--deep"],tree:["--subPath","--depth","-d"],trace:["--dir","-d"],"search-config":["--dir","-d","--kind"],"search-concept":["--dir","-d","--interactive","-i"],"search-symbol":["--dir","-d","--interactive","-i"],"search-fuzzy":["--dir","-d","--interactive","-i"]};function Qd(){let s=Object.entries(Kd).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
|
|
1053
|
+
`),e=qc.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
|
|
999
1054
|
_liquid_shadow() {
|
|
1000
1055
|
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
1001
1056
|
local words=("\${COMP_WORDS[@]}")
|
|
@@ -1005,7 +1060,7 @@ _liquid_shadow() {
|
|
|
1005
1060
|
if [[ "\${words[$i]}" != -* ]]; then cmd="\${words[$i]}"; break; fi
|
|
1006
1061
|
((i++))
|
|
1007
1062
|
done
|
|
1008
|
-
local opts="${
|
|
1063
|
+
local opts="${Yd.join(" ")}"
|
|
1009
1064
|
if [ -n "$cmd" ]; then
|
|
1010
1065
|
case "$cmd" in
|
|
1011
1066
|
${s}
|
|
@@ -1017,11 +1072,11 @@ ${s}
|
|
|
1017
1072
|
COMPREPLY=($(compgen -W "$opts" -- "$cur"))
|
|
1018
1073
|
}
|
|
1019
1074
|
complete -F _liquid_shadow liquid-shadow
|
|
1020
|
-
`}function
|
|
1075
|
+
`}function Zd(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
|
|
1021
1076
|
# Run after compinit (e.g. in .zshrc after compinit)
|
|
1022
1077
|
|
|
1023
1078
|
_liquid_shadow() {
|
|
1024
|
-
local -a cmds; cmds=(${
|
|
1079
|
+
local -a cmds; cmds=(${qc.map(e=>`'${e}'`).join(" ")})
|
|
1025
1080
|
if [ $CURRENT -eq 2 ]; then
|
|
1026
1081
|
_describe 'command' cmds
|
|
1027
1082
|
return
|
|
@@ -1038,7 +1093,7 @@ _liquid_shadow() {
|
|
|
1038
1093
|
_describe 'flag' fl
|
|
1039
1094
|
}
|
|
1040
1095
|
compdef _liquid_shadow liquid-shadow
|
|
1041
|
-
`}async function
|
|
1096
|
+
`}async function Vc(s){s==="bash"?console.log(Qd()):s==="zsh"?console.log(Zd()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}import Xd from"fs";import em from"path";var tm=2e3;async function Jc(s){let e=em.resolve(s);await Q(async()=>{ge("Watch mode");let t=ct(e),n=null,i=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(b.dim(" Changes detected, reindexing...")),await ie(e,5,!1,!0),console.log(b.green(" Reindex complete."))}catch(r){console.error(b.red(" Reindex failed:"),r instanceof Error?r.message:r)}},tm)};try{Xd.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&i()}),console.log(b.cyan(` Watching ${e}`)),console.log(b.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),Ve("Ctrl+C to stop"),await new Promise((r,o)=>{process.on("SIGINT",()=>o(new Error("SIGINT"))),process.on("SIGTERM",()=>o(new Error("SIGTERM")))}).catch(()=>{})}finally{n&&clearTimeout(n),await ne(e)}})}Y();G();var nm=w.child({module:"narrative-service"}),is=class{missions;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t}=N.getInstance(e);this.missions=t,this.briefingEngine=new mt(e)}async generateChronicle(e={}){nm.info(e,"Generating Repo Chronicle...");let n=this.missions.findAll().filter(l=>l.parent_id===null&&l.status!=="planned");e.branch&&(n=n.filter(l=>!l.git_branch||l.git_branch===e.branch)),e.since&&(n=n.filter(l=>l.updated_at>=e.since)),e.until&&(n=n.filter(l=>l.updated_at<=e.until)),n.sort((l,p)=>p.updated_at-l.updated_at);let i=e.offset||0,r=e.limit||10;n=n.slice(i,i+r);let o=[],a=[],c=[];for(let l of n){let p=this.missions.findByParentId(l.id),u=p.length>0,d=await this.briefingEngine.distillMission(l.id,!1);if(u){let h=[];for(let f of p)h.push(await this.mapMissionToEpisode(f));h.unshift(await this.mapMissionToEpisode(l));let m={kind:"initiative",root_mission_id:l.id,title:l.name,strategy_graph:l.strategy_graph?JSON.parse(l.strategy_graph):{},episodes:e.compact?[]:h,synthesized_narrative:e.compact?this.truncateText(d.adr):d.adr||""};o.push(m),c.push(m)}else{let h=await this.mapMissionToEpisode(l,d.adr,e.compact);a.push(h),c.push(h)}}return{repo_path:this.repoPath,generated_at:Date.now(),initiatives:o,unattached_episodes:a,timeline:c}}async mapMissionToEpisode(e,t,n=!1){let i=t;return i||(i=(await this.briefingEngine.distillMission(e.id,!1)).adr),{kind:"episode",mission_id:e.id,title:e.name,goal:e.goal,outcome:e.outcome_contract,intents:[],adr_summary:n?this.truncateText(i):i}}truncateText(e,t=300){return e?e.length<=t?e:e.slice(0,t)+"... (truncated)":""}renderChronicleMarkdown(e){let t=`# Repository Chronicle
|
|
1042
1097
|
|
|
1043
1098
|
`;if(t+=`*Generated at ${new Date(e.generated_at).toISOString()}*
|
|
1044
1099
|
|
|
@@ -1049,7 +1104,7 @@ compdef _liquid_shadow liquid-shadow
|
|
|
1049
1104
|
`,t+=`${n.adr_summary}
|
|
1050
1105
|
|
|
1051
1106
|
`),t+=`---
|
|
1052
|
-
`;return t}};
|
|
1107
|
+
`;return t}};G();import im from"path";async function Yc(s,e){let t=im.resolve(s||process.cwd()),n=e.format==="json"?"json":"markdown",i=w.child({module:"cli:chronicle",repoPath:t});i.info("Generating repository chronicle...");try{let r=new is(t),o=await r.generateChronicle({limit:e.limit,offset:e.offset,since:e.since,until:e.until});console.log(n==="json"?JSON.stringify(o,null,2):r.renderChronicleMarkdown(o))}catch(r){i.error({error:r},"Failed to generate chronicle"),console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}}import At from"fs";import mn from"path";import om from"os";import He from"fs";import rt from"path";import sm from"os";var Kc={shadow_audit:'---\nname: audit\ndescription: Perform codebase health audits to identify dead code, circular dependencies, and technical debt. Use when auditing code quality, finding unused code, detecting circular dependencies, or when the user asks about codebase health, technical debt, or code cleanup.\n---\n\n# Codebase Audit\n\nComprehensive health audit using Shadow analyze toolkit.\n\n## \u{1F680} Workflow\n\n1. **Session Context**: `shadow_ops_context` (repoPath) \u2014 **ONE CALL** for hologram + chronicle + briefing. Get architecture baseline.\n2. **Dead Code Detection**: `shadow_analyze_debt` (mode: "dead-code", limit: 100, includeTests: false, repoPath) \u2014 Unused exports.\n3. **Circular Dependencies**: `shadow_analyze_debt` (mode: "circular-deps", limit: 20, repoPath) \u2014 Import cycles.\n4. **Layer Integrity** (optional): `shadow_recon_topography` (repoPath) \u2014 Detailed layer analysis if hologram summary isn\'t enough.\n5. **Log Findings**: `shadow_ops_log` (missionId, type: "discovery", content, repoPath).\n6. **Create Cleanup Mission** (optional): `shadow_ops_plan` (name: "Codebase Cleanup", templateId: "refactoring", templateVars, repoPath).\n\n## \u{1F6E0} Precise Tooling\n\n| Audit Target | Atomic Tool |\n| :------------------- | :------------------------------------------------------------------------------------- |\n| **Session Start** \u{1F680} | `shadow_ops_context` (repoPath) \u2014 **START HERE** for baseline |\n| **Architecture** | `shadow_recon_hologram` (repoPath) \u2014 if you need standalone |\n| **Dead Code** | `shadow_analyze_debt` (mode: "dead-code", limit: 100, **confidenceThreshold: "high"**) |\n| **Circular Deps** | `shadow_analyze_debt` (mode: "circular-deps") |\n| **Layers** | `shadow_recon_topography` \u2014 detailed breakdown if needed |\n| **Config Audit** | `shadow_search_config` (kind: "Env", **showUsage: true**) \u2014 find orphaned env vars |\n| **Event Mesh** | `shadow_analyze_mesh` (repoPath) \u2014 audit all HTTP routes, socket events, pubsub topics |\n| **Type Integrity** | `shadow_analyze_type_graph` (filePath, repoPath) \u2014 interface/type inheritance chains |\n| **Theme Patterns** | `shadow_ops_crystallize_theme` (query, repoPath) \u2014 recurring issues across missions |\n\n## \u{1F4A1} Intelligence Options\n\n- **`shadow_analyze_debt` confidence levels**: Use `confidenceThreshold: "high"` for likely dead code, `"medium"` for possibly intentional (test fixtures, etc.), `"all"` for everything.\n- **`shadow_analyze_debt` exclusion filters**: Use `excludePatterns`, `includeMigrations: false`, `includeFixtures: false` to reduce noise.\n- **`shadow_search_config` with `showUsage: true`**: Cross-references config vars with code to show usage counts and identify orphaned vars (defined but never used).\n\n## \u{1F50D} Health Criteria\n\n- **Critical Issues**: Circular deps in core logic, >50 dead exports, orphaned env vars with secrets\n- **Warning Signs**: Layer violations (Test \u2192 Logic), >20 dead exports, >10 orphaned configs\n- **Good Health**: Clean layers, <10 dead exports, no circular deps, all configs in use\n',shadow_chronicle:`---
|
|
1053
1108
|
name: chronicle
|
|
1054
1109
|
description: Retrieve and analyze the repository's narrative archive as recorded in Git-native memory. Use when you need to understand historical decisions, catch up on repository progress, review recently completed missions, or when the user asks for a project history, changelog, or chronological overview of architectural changes.
|
|
1055
1110
|
---
|
|
@@ -1368,9 +1423,9 @@ _Note: Use fused search after \`shadow_workspace_fuse\` to look up concepts acro
|
|
|
1368
1423
|
## \u{1F6E0} Tooling Strategy
|
|
1369
1424
|
|
|
1370
1425
|
Use **\`shadow_workspace_fuse\`** early in multi-repo sessions to unlock "X-Ray" vision across boundaries.
|
|
1371
|
-
`};import*as
|
|
1372
|
-
command = "${
|
|
1373
|
-
args = ${t}`}function
|
|
1426
|
+
`};import*as ht from"@clack/prompts";function rm(s){return[{name:"Claude Code",dir:rt.join(s,".claude","skills"),folderBased:!0,createIfMissing:!1},{name:"Cursor",dir:rt.join(s,".cursor","skills"),folderBased:!0,createIfMissing:!1},{name:"Gemini CLI",dir:rt.join(s,".gemini","skills"),folderBased:!0,createIfMissing:!0},{name:"Codex",dir:rt.join(s,".codex","skills"),folderBased:!0,createIfMissing:!1},{name:"Antigravity",dir:rt.join(s,".gemini","antigravity","global_workflows"),folderBased:!1,createIfMissing:!1}]}function dr(s=!1){let e=sm.homedir(),t=rm(e),n=0;for(let i of t){if(!He.existsSync(i.dir))if(i.createIfMissing)He.mkdirSync(i.dir,{recursive:!0});else continue;if(i.folderBased)try{for(let r of He.readdirSync(i.dir))r.startsWith("shadow_shadow_")&&He.rmSync(rt.join(i.dir,r),{recursive:!0,force:!0})}catch{}for(let[r,o]of Object.entries(Kc))if(i.folderBased){let a=rt.join(i.dir,r);He.existsSync(a)||He.mkdirSync(a,{recursive:!0});let c=rt.join(a,"skill.md");He.existsSync(c)&&He.unlinkSync(c);let l=rt.join(a,"SKILL.md");(s||!He.existsSync(l))&&(He.writeFileSync(l,o),n++)}else{let a=rt.join(i.dir,`${r}.md`);(s||!He.existsSync(a))&&(He.writeFileSync(a,o),n++)}}return n}async function Qc(){ht.intro("\u{1F311} Liquid Shadow: Skills Update");let s=ht.spinner();s.start("Deploying latest skill definitions...");let e=dr(!0);s.stop("Done."),e>0?ht.note(`Updated ${e} skill files across all detected targets.`,"Manifest"):ht.note("No skill targets found (Claude Code, Cursor, Gemini CLI, Codex, Antigravity).","Manifest"),ht.outro("\u{1F311} Skills are up to date.")}import{pino as am}from"pino";import*as _e from"@clack/prompts";var ft=am({transport:{target:"pino-pretty",options:{colorize:!0}}}),Vt="liquid-shadow",mr="liquid-shadow-mcp";function cm(s){let e=(s||mr).trim();return e.length>0?e:mr}function lm(s){let e=[],t=/[^\s"']+|"([^"]*)"|'([^']*)'/g,n;for(;(n=t.exec(s))!==null;)e.push(n[1]??n[2]??n[0]??"");return e}function Xc(s){if(!s)return[];let e=s.trim();if(!e)return[];if(e.startsWith("[")){let t;try{t=JSON.parse(e)}catch{throw new Error('--mcp-args JSON parsing failed. Use a valid JSON array like ["--flag","value"].')}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error("--mcp-args JSON must be an array of strings.");return t}return lm(e)}function Zc(s){return s.replaceAll("\\","\\\\").replaceAll('"','\\"')}function pm(s,e){let t=`[${e.map(n=>`"${Zc(n)}"`).join(", ")}]`;return`[mcp_servers.${Vt}]
|
|
1427
|
+
command = "${Zc(s)}"
|
|
1428
|
+
args = ${t}`}function um(s,e,t){let n=s.split(/\r?\n/),i=n.findIndex(c=>c.trim()===e);if(i===-1)return`${s.length===0||s.endsWith(`
|
|
1374
1429
|
`)?s:`${s}
|
|
1375
1430
|
`}
|
|
1376
1431
|
${t}
|
|
@@ -1379,4 +1434,4 @@ ${t}
|
|
|
1379
1434
|
`).replace(/\n{3,}/g,`
|
|
1380
1435
|
|
|
1381
1436
|
`).trimEnd()}
|
|
1382
|
-
`}async function Cc(s=!1,e=!1,t=Ks,n=[]){de.intro("\u{1F311} Liquid Shadow: Tactical Onboarding");let i=Hd.homedir(),r=0,o=Ud(t),a=Array.isArray(n)?n:[],c=e||await de.confirm({message:"Deploy Autonomous Reasoning Skills? (Injects /onboard, /understand, etc.)",initialValue:!0});if(de.isCancel(c)){de.outro("Onboarding aborted.");return}let l=e||await de.confirm({message:"Connect to MCP Reasoning Engines? (Claude Code, Claude Desktop, Gemini CLI, Codex)",initialValue:!0});if(de.isCancel(l)){de.outro("Onboarding aborted.");return}if(!c&&!l){de.outro("No actions selected. Operational state unchanged.");return}let p=de.spinner();p.start("Establishing intelligence assets..."),c&&(r=Ys(!0)),l&&(qd(i,o,a,!0),Vd(i,o,a,!0)),p.stop("Intelligence layer established."),r>0?de.note(`Successfully deployed ${r} tactical skills.`,"Manifest"):de.note("No new skills deployed (up to date or scope skipped).","Manifest"),de.outro("\u{1F311} Liquid Shadow is operational.")}function qd(s,e,t,n){let i=[{name:"Claude Code",path:Zt.join(s,".claude.json"),extraFields:{type:"stdio"},createIfMissing:!1},{name:"Claude Desktop",path:Zt.join(s,"Library","Application Support","Claude","claude_desktop_config.json"),createIfMissing:!1},{name:"Gemini CLI",path:Zt.join(s,".gemini","settings.json"),createIfMissing:!0},{name:"Antigravity IDE",path:Zt.join(s,".gemini","antigravity","mcp_config.json"),createIfMissing:!1}];for(let r of i){if(!bt.existsSync(r.path))if(r.createIfMissing)bt.mkdirSync(Zt.dirname(r.path),{recursive:!0}),bt.writeFileSync(r.path,"{}");else{it.debug(`${r.name} config not found at ${r.path}, skipping.`);continue}try{let o=JSON.parse(bt.readFileSync(r.path,"utf8"));if(o.mcpServers||(o.mcpServers={}),o.mcpServers[Pt]){if(!n){it.info(`${r.name}: ${Pt} already configured.`);continue}it.info(`${r.name}: updating existing ${Pt} configuration.`)}o.mcpServers[Pt]={command:e,args:t,env:{},...r.extraFields??{}},bt.writeFileSync(r.path,JSON.stringify(o,null,2)),it.info(`Updated ${r.name} config at ${r.path}`)}catch(o){it.error(`Failed to update ${r.name} config at ${r.path}: ${o}`)}}}function Vd(s,e,t,n){let i=Zt.join(s,".codex","config.toml");if(!bt.existsSync(i)){it.debug(`Codex config not found at ${i}, skipping.`);return}try{let r=bt.readFileSync(i,"utf8"),o=`[mcp_servers.${Pt}]`,a=Bd(e,t);if(r.includes(o)&&!n){it.info(`Codex: ${Pt} already configured.`);return}let c=Gd(r,o,a);bt.writeFileSync(i,c),it.info(`Updated Codex config at ${i}`)}catch(r){it.error(`Failed to update Codex config at ${i}: ${r}`)}}St();import{readFileSync as Jd}from"node:fs";var en={name:"@precisionutilityguild/liquid-shadow",version:"0.0.0",license:"UNLICENSED",description:"Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem"};function Ic(){let s=JSON.parse(Jd(_e("package.json"),"utf8"));return{name:typeof s.name=="string"&&s.name.trim().length>0?s.name:en.name,version:typeof s.version=="string"&&s.version.trim().length>0?s.version:en.version,license:typeof s.license=="string"&&s.license.trim().length>0?s.license:en.license,description:typeof s.description=="string"&&s.description.trim().length>0?s.description:en.description}}function be(s){let e=process.cwd();return Vi(e,s.flags)}process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),Q().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),Q().then(()=>process.exit(1))});var Qs=en;try{Qs=Ic()}catch(s){console.error("Failed to parse package.json, using defaults",s)}var ie=Yd().name("liquid-shadow").version(Qs.version).description(Qs.description).scriptName("liquid-shadow");ie.command("index","Index the repository for AI analysis",{parameters:["[dir]"],flags:{output:{type:String,alias:"o",description:"Export to JSON file instead of indexing"},level:{type:String,alias:"l",description:"Detail level",default:"detailed"},subPath:{type:String,description:"Only process files within this subpath"},force:{type:Boolean,description:"Force re-indexing of all files",default:!1},deep:{type:Boolean,description:"Perform deep semantic indexing (headings + symbol embeddings)",default:!0}}}).on("index",async s=>{let e=be(s),t={...s.flags,dir:s.flags.dir??e.dir,level:s.flags.level??e.level,deep:s.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await pa(s.parameters.dir||e.dir,t)});ie.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=be(s);await Dr(s.parameters.dir||e.dir)});ie.command("dashboard","Operational intelligence dashboard (TUI)",{parameters:["[dir]"]}).on("dashboard",async s=>{let e=be(s);await cs(s.parameters.dir||e.dir)});ie.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=be(s);await Br(s.parameters.dir||e.dir)});ie.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=be(s);await da(s.parameters.dir||e.dir)});ie.command("tree","Visualize repository structure as a tree",{parameters:["[dir]"],flags:{subPath:{type:String,description:"Subpath to visualize"},depth:{type:String,alias:"d",description:"Max depth",default:"3"}}}).on("tree",async s=>{let e=be(s);await aa(s.parameters.dir||e.dir,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("recon","Repository reconnaissance and architecture analysis",{parameters:["<mode>","[dir]"],flags:{subPath:{type:String,description:"Subpath to focus on"}}}).on("recon",async s=>{let e=be(s);await Ca(s.parameters.mode,s.parameters.dir||e.dir,{...s.flags})});ie.command("trace","Trace execution flow for a given file/symbol",{parameters:["<file>","[symbolName]"],flags:{dir:{type:String,alias:"d",default:"."}}}).on("trace",async s=>{let e=be(s);await Sa(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});ie.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"],flags:{contextPivot:{type:Boolean,default:!1,description:"Opt in to suspend other-branch missions and resume current-branch missions"},mergeSentinel:{type:Boolean,default:!1,description:"Opt in to auto-complete missions from merged branches"}}}).on("sync",async s=>{let e=be(s);await Ta(s.parameters.dir||e.dir,{contextPivot:!!s.flags.contextPivot,mergeSentinel:!!s.flags.mergeSentinel})});ie.command("search-config","Search for configuration values",{parameters:["[key]"],flags:{dir:{type:String,alias:"d",default:"."},kind:{type:String,description:"Filter by config kind"}}}).on("search-config",async s=>{let e=be(s);await Ha(s.parameters.key,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("search-concept","Search for files by concept/intent (Semantic)",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-concept",async s=>{let e=be(s);await Oa(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("search-symbol","Search for specific code symbols",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-symbol",async s=>{let e=be(s);await Fa(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("search-fuzzy",'Fuzzy search for symbols (e.g., "usc" finds "UserServiceClient")',{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-fuzzy",async s=>{let e=be(s);await Wa(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async s=>{await za([s.parameters.action,s.parameters.path])});ie.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async s=>{await Xa([s.parameters.action,...s.parameters.args])});ie.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async s=>{await bc([s.parameters.action,...s.parameters.args])});ie.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async s=>{await _c([s.parameters.mode,...s.parameters.args])});ie.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=be(s);await wc(s.parameters.dir||e.dir)});ie.command("chronicle","Generate a repository-wide narrative feed (ADRs/Epics)",{parameters:["[dir]"],flags:{format:{type:String,alias:"f",description:"Output format (markdown|json)",default:"markdown"},limit:{type:Number,alias:"l",description:"Limit number of entries",default:10},offset:{type:Number,description:"Pagination offset",default:0},since:{type:String,description:"Show entries since date (YYYY-MM-DD)"},until:{type:String,description:"Show entries until date (YYYY-MM-DD)"}}}).on("chronicle",async s=>{let e=be(s);await xc(s.parameters.dir||e.dir,{...s.flags,format:s.flags.format,limit:s.flags.limit?parseInt(String(s.flags.limit),10):void 0,offset:s.flags.offset?parseInt(String(s.flags.offset),10):void 0,since:s.flags.since?Math.floor(new Date(String(s.flags.since)).getTime()/1e3):void 0,until:s.flags.until?Math.floor(new Date(String(s.flags.until)).getTime()/1e3):void 0})});ie.command("init","Initialize Liquid Shadow skills and configuration",{flags:{force:{type:Boolean,alias:"f",description:"Force overwrite existing skills and MCP server entries",default:!1},yes:{type:Boolean,alias:"y",description:"Skip interactive confirmation (unsafe)",default:!1},mcpCommand:{type:String,description:"Override MCP command used in generated client configs",default:"liquid-shadow-mcp"},mcpArgs:{type:String,description:'Optional MCP args (JSON array recommended, e.g. ["--flag","value"] or quoted string)'}}}).on("init",async s=>{let e;try{e=kc(s.flags.mcpArgs)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Invalid --mcp-args: ${n}`),process.exit(1);return}await Cc(s.flags.force,s.flags.yes,s.flags.mcpCommand,e)});ie.command("skills","Manage Liquid Shadow reasoning skills",{parameters:["<action>"]}).on("skills",async s=>{let e=s.parameters.action;e==="update"?await Tc():(console.error(`Unknown skills action: ${e}. Available: update`),process.exit(1))});ie.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async s=>{await Sc(s.parameters.shell||"")});if(process.argv.length<=2){let s=Vi(process.cwd(),{});cs(s.dir)}else ie.parse();
|
|
1437
|
+
`}async function el(s=!1,e=!1,t=mr,n=[]){_e.intro("\u{1F311} Liquid Shadow: Tactical Onboarding");let i=om.homedir(),r=0,o=cm(t),a=Array.isArray(n)?n:[],c=e||await _e.confirm({message:"Deploy Autonomous Reasoning Skills? (Injects /onboard, /understand, etc.)",initialValue:!0});if(_e.isCancel(c)){_e.outro("Onboarding aborted.");return}let l=e||await _e.confirm({message:"Connect to MCP Reasoning Engines? (Claude Code, Claude Desktop, Gemini CLI, Codex)",initialValue:!0});if(_e.isCancel(l)){_e.outro("Onboarding aborted.");return}if(!c&&!l){_e.outro("No actions selected. Operational state unchanged.");return}let p=_e.spinner();p.start("Establishing intelligence assets..."),c&&(r=dr(!0)),l&&(dm(i,o,a,!0),mm(i,o,a,!0)),p.stop("Intelligence layer established."),r>0?_e.note(`Successfully deployed ${r} tactical skills.`,"Manifest"):_e.note("No new skills deployed (up to date or scope skipped).","Manifest"),_e.outro("\u{1F311} Liquid Shadow is operational.")}function dm(s,e,t,n){let i=[{name:"Claude Code",path:mn.join(s,".claude.json"),extraFields:{type:"stdio"},createIfMissing:!1},{name:"Claude Desktop",path:mn.join(s,"Library","Application Support","Claude","claude_desktop_config.json"),createIfMissing:!1},{name:"Gemini CLI",path:mn.join(s,".gemini","settings.json"),createIfMissing:!0},{name:"Antigravity IDE",path:mn.join(s,".gemini","antigravity","mcp_config.json"),createIfMissing:!1}];for(let r of i){if(!At.existsSync(r.path))if(r.createIfMissing)At.mkdirSync(mn.dirname(r.path),{recursive:!0}),At.writeFileSync(r.path,"{}");else{ft.debug(`${r.name} config not found at ${r.path}, skipping.`);continue}try{let o=JSON.parse(At.readFileSync(r.path,"utf8"));if(o.mcpServers||(o.mcpServers={}),o.mcpServers[Vt]){if(!n){ft.info(`${r.name}: ${Vt} already configured.`);continue}ft.info(`${r.name}: updating existing ${Vt} configuration.`)}o.mcpServers[Vt]={command:e,args:t,env:{},...r.extraFields??{}},At.writeFileSync(r.path,JSON.stringify(o,null,2)),ft.info(`Updated ${r.name} config at ${r.path}`)}catch(o){ft.error(`Failed to update ${r.name} config at ${r.path}: ${o}`)}}}function mm(s,e,t,n){let i=mn.join(s,".codex","config.toml");if(!At.existsSync(i)){ft.debug(`Codex config not found at ${i}, skipping.`);return}try{let r=At.readFileSync(i,"utf8"),o=`[mcp_servers.${Vt}]`,a=pm(e,t);if(r.includes(o)&&!n){ft.info(`Codex: ${Vt} already configured.`);return}let c=um(r,o,a);At.writeFileSync(i,c),ft.info(`Updated Codex config at ${i}`)}catch(r){ft.error(`Failed to update Codex config at ${i}: ${r}`)}}Nt();import{readFileSync as hm}from"node:fs";var hn={name:"@precisionutilityguild/liquid-shadow",version:"0.0.0",license:"UNLICENSED",description:"Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem"};function tl(){let s=JSON.parse(hm(Le("package.json"),"utf8"));return{name:typeof s.name=="string"&&s.name.trim().length>0?s.name:hn.name,version:typeof s.version=="string"&&s.version.trim().length>0?s.version:hn.version,license:typeof s.license=="string"&&s.license.trim().length>0?s.license:hn.license,description:typeof s.description=="string"&&s.description.trim().length>0?s.description:hn.description}}function ke(s){let e=process.cwd();return ls(e,s.flags)}process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),ne().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),ne().then(()=>process.exit(1))});var hr=hn;try{hr=tl()}catch(s){console.error("Failed to parse package.json, using defaults",s)}var le=fm().name("liquid-shadow").version(hr.version).description(hr.description).scriptName("liquid-shadow");le.command("index","Index the repository for AI analysis",{parameters:["[dir]"],flags:{output:{type:String,alias:"o",description:"Export to JSON file instead of indexing"},level:{type:String,alias:"l",description:"Detail level",default:"detailed"},subPath:{type:String,description:"Only process files within this subpath"},force:{type:Boolean,description:"Force re-indexing of all files",default:!1},deep:{type:Boolean,description:"Perform deep semantic indexing (headings + symbol embeddings)",default:!0}}}).on("index",async s=>{let e=ke(s),t={...s.flags,dir:s.flags.dir??e.dir,level:s.flags.level??e.level,deep:s.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await Na(s.parameters.dir||e.dir,t)});le.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=ke(s);await ao(s.parameters.dir||e.dir)});le.command("dashboard","Operational intelligence dashboard (TUI)",{parameters:["[dir]"]}).on("dashboard",async s=>{let e=ke(s);await vs(s.parameters.dir||e.dir)});le.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=ke(s);await go(s.parameters.dir||e.dir)});le.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=ke(s);await Oa(s.parameters.dir||e.dir)});le.command("tree","Visualize repository structure as a tree",{parameters:["[dir]"],flags:{subPath:{type:String,description:"Subpath to visualize"},depth:{type:String,alias:"d",description:"Max depth",default:"3"}}}).on("tree",async s=>{let e=ke(s);await Aa(s.parameters.dir||e.dir,{...s.flags,dir:s.flags.dir??e.dir})});le.command("recon","Repository reconnaissance and architecture analysis",{parameters:["<mode>","[dir]"],flags:{subPath:{type:String,description:"Subpath to focus on"}}}).on("recon",async s=>{let e=ke(s);await Xa(s.parameters.mode,s.parameters.dir||e.dir,{...s.flags})});le.command("trace","Trace execution flow for a given file/symbol",{parameters:["<file>","[symbolName]"],flags:{dir:{type:String,alias:"d",default:"."}}}).on("trace",async s=>{let e=ke(s);await qa(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});le.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"],flags:{contextPivot:{type:Boolean,default:!1,description:"Opt in to suspend other-branch missions and resume current-branch missions"},mergeSentinel:{type:Boolean,default:!1,description:"Opt in to auto-complete missions from merged branches"}}}).on("sync",async s=>{let e=ke(s);await Ka(s.parameters.dir||e.dir,{contextPivot:!!s.flags.contextPivot,mergeSentinel:!!s.flags.mergeSentinel})});le.command("search-config","Search for configuration values",{parameters:["[key]"],flags:{dir:{type:String,alias:"d",default:"."},kind:{type:String,description:"Filter by config kind"}}}).on("search-config",async s=>{let e=ke(s);await uc(s.parameters.key,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-concept","Search for files by concept/intent (Semantic)",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-concept",async s=>{let e=ke(s);await cc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-symbol","Search for specific code symbols",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-symbol",async s=>{let e=ke(s);await lc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-fuzzy",'Fuzzy search for symbols (e.g., "usc" finds "UserServiceClient")',{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-fuzzy",async s=>{let e=ke(s);await pc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async s=>{await dc([s.parameters.action,s.parameters.path])});le.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async s=>{await xc([s.parameters.action,...s.parameters.args])});le.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async s=>{await jc([s.parameters.action,...s.parameters.args])});le.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async s=>{await Gc([s.parameters.mode,...s.parameters.args])});le.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=ke(s);await Jc(s.parameters.dir||e.dir)});le.command("chronicle","Generate a repository-wide narrative feed (ADRs/Epics)",{parameters:["[dir]"],flags:{format:{type:String,alias:"f",description:"Output format (markdown|json)",default:"markdown"},limit:{type:Number,alias:"l",description:"Limit number of entries",default:10},offset:{type:Number,description:"Pagination offset",default:0},since:{type:String,description:"Show entries since date (YYYY-MM-DD)"},until:{type:String,description:"Show entries until date (YYYY-MM-DD)"}}}).on("chronicle",async s=>{let e=ke(s);await Yc(s.parameters.dir||e.dir,{...s.flags,format:s.flags.format,limit:s.flags.limit?parseInt(String(s.flags.limit),10):void 0,offset:s.flags.offset?parseInt(String(s.flags.offset),10):void 0,since:s.flags.since?Math.floor(new Date(String(s.flags.since)).getTime()/1e3):void 0,until:s.flags.until?Math.floor(new Date(String(s.flags.until)).getTime()/1e3):void 0})});le.command("init","Initialize Liquid Shadow skills and configuration",{flags:{force:{type:Boolean,alias:"f",description:"Force overwrite existing skills and MCP server entries",default:!1},yes:{type:Boolean,alias:"y",description:"Skip interactive confirmation (unsafe)",default:!1},mcpCommand:{type:String,description:"Override MCP command used in generated client configs",default:"liquid-shadow-mcp"},mcpArgs:{type:String,description:'Optional MCP args (JSON array recommended, e.g. ["--flag","value"] or quoted string)'}}}).on("init",async s=>{let e;try{e=Xc(s.flags.mcpArgs)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Invalid --mcp-args: ${n}`),process.exit(1);return}await el(s.flags.force,s.flags.yes,s.flags.mcpCommand,e)});le.command("skills","Manage Liquid Shadow reasoning skills",{parameters:["<action>"]}).on("skills",async s=>{let e=s.parameters.action;e==="update"?await Qc():(console.error(`Unknown skills action: ${e}. Available: update`),process.exit(1))});le.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async s=>{await Vc(s.parameters.shell||"")});if(process.argv.length<=2){let s=ls(process.cwd(),{});vs(s.dir)}else le.parse();
|