@precisionutilityguild/liquid-shadow 1.0.2 → 1.0.3
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 +69 -144
- package/dist/data/migrations/008_crystallization.sql +13 -0
- package/dist/data/migrations/009_intent_vectors.sql +8 -0
- package/dist/entry/cli/index.js +485 -200
- package/dist/entry/mcp/server.js +194 -166
- package/dist/index.js +60 -48
- package/dist/logic/domain/embeddings/worker.js +1 -1
- package/dist/logic/parser/index.js +36 -0
- package/dist/logic/parser/worker.js +1 -0
- package/dist/web-manifest.json +29 -23
- package/package.json +1 -1
package/dist/entry/cli/index.js
CHANGED
|
@@ -1,26 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var pa=Object.create;var us=Object.defineProperty;var da=Object.getOwnPropertyDescriptor;var ua=Object.getOwnPropertyNames;var ma=Object.getPrototypeOf,ha=Object.prototype.hasOwnProperty;var fa=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var K=(i,e)=>()=>(i&&(e=i(i=0)),e);var ga=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),ms=(i,e)=>{for(var t in e)us(i,t,{get:e[t],enumerable:!0})},ya=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ua(e))!ha.call(i,s)&&s!==t&&us(i,s,{get:()=>e[s],enumerable:!(n=da(e,s))||n.enumerable});return i};var ba=(i,e,t)=>(t=i!=null?pa(ma(i)):{},ya(e||!i||!i.__esModule?us(t,"default",{value:i,enumerable:!0}):t,i));import _a from"pino";var Ea,Sa,S,W=K(()=>{"use strict";Ea={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},Sa=_a({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(i,e){return{level:i,severity:Ea[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),S=Sa});import Nt from"fs";import fs from"path";import{fileURLToPath as va}from"url";function ka(i){i.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 Ia(i){ka(i);let e=i.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function Ca(){let i=Ra;if(!Nt.readdirSync(i).some(r=>r.match(/^\d{3}_.*\.sql$/))){let r=fs.resolve(i,"../../data/migrations");Nt.existsSync(r)&&Nt.readdirSync(r).some(c=>c.match(/^\d{3}_.*\.sql$/))&&(i=r)}let n=Nt.readdirSync(i).filter(r=>r.match(/^\d{3}_.*\.sql$/)).sort(),s=[];for(let r of n){let o=r.match(/^(\d{3})_(.+)\.sql$/);if(!o)continue;let c=parseInt(o[1],10),a=o[2],p=Nt.readFileSync(fs.join(i,r),"utf-8").split(/^-- DOWN$/m),u=p[0].trim(),d=p[1]?.trim();s.push({version:c,name:a,up:u,down:d})}return s}function La(i,e){At.info({version:e.version,name:e.name},"Applying migration"),i.transaction(()=>{i.exec(e.up),i.prepare("INSERT INTO schema_migrations (version, name) VALUES (?, ?)").run(e.version,e.name)})(),At.info({version:e.version},"Migration applied successfully")}function ii(i){let e=Ia(i),n=Ca().filter(s=>!e.has(s.version));if(n.length===0){At.debug("No pending migrations");return}At.info({count:n.length},"Running pending migrations");for(let s of n)La(i,s);At.info("All migrations complete")}var At,Ta,Ra,ri=K(()=>{"use strict";W();At=S.child({module:"migrations"}),Ta=va(import.meta.url),Ra=fs.dirname(Ta)});import $a from"better-sqlite3";import on from"path";import gs from"fs";import oi from"crypto";import Na from"os";function cn(i){let e=Na.homedir(),t=on.join(e,".mcp-liquid-shadow"),n=on.join(t,"dbs");gs.existsSync(n)||gs.mkdirSync(n,{recursive:!0});let s=oi.createHash("sha256").update(i).digest("hex").substring(0,12),o=`${on.basename(i).replace(/[^a-zA-Z0-9-_]/g,"_")}_${s}.db`;return on.join(n,o)}function Aa(i,e){let t=e||cn(i);Fe.debug({repoPath:i,dbPath:t},"Initializing database");let n=new $a(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),ii(n),an.set(i,t),Ge.set(t,n),Fe.debug({repoPath:i,dbPath:t},"Database initialized successfully"),n}function mt(i){return oi.createHash("sha256").update(i,"utf8").digest("hex")}function ai(i,e){return e?mt(i)!==e:!0}function We(i){let e=an.get(i)||cn(i),t=Ge.get(e);if(t){if(t.open)return t;Ge.delete(e)}let n=Aa(i);return Ge.set(e,n),n}function He(i){let e=cn(i);if(!gs.existsSync(e))return!1;try{let t=We(i);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
|
|
12
|
-
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
13
|
-
VALUES ('index_completed', 'true', unixepoch())
|
|
14
|
-
`).run(),t.prepare(`
|
|
15
|
-
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
16
|
-
VALUES ('last_indexed_at', ?, unixepoch())
|
|
17
|
-
`).run(Date.now().toString()),e&&t.prepare(`
|
|
18
|
-
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
19
|
-
VALUES ('last_indexed_commit', ?, unixepoch())
|
|
20
|
-
`).run(e),$e.info({repoPath:i,commitSha:e},"Repository marked as indexed")}function xt(i){try{return ke(i).prepare(`
|
|
11
|
+
`).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return Fe.debug({repoPath:i,error:t},"Error checking index status"),!1}}function ys(i,e){let t=We(i),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)})(),Fe.debug({repoPath:i,commitSha:e},"Repository marked as indexed")}function Pt(i){try{return We(i).prepare(`
|
|
21
12
|
SELECT value FROM index_metadata
|
|
22
13
|
WHERE key = 'last_indexed_commit'
|
|
23
|
-
`).get()?.value||null}catch(e){return
|
|
14
|
+
`).get()?.value||null}catch(e){return Fe.debug({repoPath:i,error:e},"Error getting last indexed commit"),null}}function ln(i){let e=an.get(i)||cn(i),t=Ge.get(e);t&&(t.open&&(Fe.debug({repoPath:i,dbPath:e},"Closing database connection"),t.close()),Ge.delete(e)),an.delete(i)}function ci(){for(let[i,e]of Ge.entries())try{e.open&&(Fe.debug({dbPath:i},"Closing database connection"),e.close())}catch(t){Fe.error({dbPath:i,err:t},"Error closing database execution")}Ge.clear()}var Fe,Ge,an,li,qe=K(()=>{"use strict";W();ri();Fe=S.child({module:"db"});Ge=new Map,an=new Map;process.on("exit",()=>ci());li=i=>{Fe.debug({signal:i},"Received termination signal, closing databases"),ci(),process.exit(0)};process.on("SIGINT",()=>li("SIGINT"));process.on("SIGTERM",()=>li("SIGTERM"))});var te,Le=K(()=>{"use strict";te=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)()}}});import Pa from"path";var pn,pi=K(()=>{"use strict";Le();pn=class extends te{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=Pa.resolve(e,t),s=n.endsWith("/")?n:n+"/";return this.all(`
|
|
24
15
|
SELECT * FROM files
|
|
25
16
|
WHERE (path LIKE ? OR path = ?)
|
|
26
17
|
ORDER BY path ASC
|
|
@@ -57,14 +48,14 @@ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDe
|
|
|
57
48
|
OR m.id IN (${e.length>0?e.join(","):"-1"})
|
|
58
49
|
)
|
|
59
50
|
AND ws.file_path IS NOT NULL
|
|
60
|
-
`,r=[];t&&r.push(t);let o=this.all(s,...r);for(let l of o){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.file_path].score+=p;let
|
|
51
|
+
`,r=[];t&&r.push(t);let o=this.all(s,...r);for(let l of o){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.file_path].score+=p;let u=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.file_path].reasons.push(`${u}: ${l.mission_name}`)}let c=Math.floor(Date.now()/1e3)-86400,a=this.all(`
|
|
61
52
|
SELECT file_path, type, mission_id
|
|
62
53
|
FROM intent_logs
|
|
63
54
|
WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
|
|
64
55
|
AND file_path IS NOT NULL
|
|
65
56
|
ORDER BY created_at DESC
|
|
66
57
|
LIMIT 100
|
|
67
|
-
`,c);for(let l of a){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.mission_id?e.includes(l.mission_id):!1,
|
|
58
|
+
`,c);for(let l of a){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.mission_id?e.includes(l.mission_id):!1,u=p?.1:.2;n[l.file_path].score<5&&(n[l.file_path].score+=u);let d=p?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.file_path].reasons.includes(d)&&n[l.file_path].reasons.length<5&&n[l.file_path].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
|
|
68
59
|
SELECT
|
|
69
60
|
SUBSTR(path, LENGTH(?) + 2,
|
|
70
61
|
INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
|
|
@@ -87,8 +78,8 @@ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDe
|
|
|
87
78
|
SUBSTR(path, LENGTH(?) + 2) as relPath
|
|
88
79
|
FROM files
|
|
89
80
|
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(s=>{for(let r of s)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,s){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),c=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),a=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("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
|
|
91
|
-
INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
|
|
81
|
+
`,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(s=>{for(let r of s)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,s){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),c=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),a=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("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),u=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),h=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),g=this.db.prepare(`
|
|
82
|
+
INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
|
|
92
83
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
93
84
|
ON CONFLICT(path) DO UPDATE SET
|
|
94
85
|
mtime=excluded.mtime,
|
|
@@ -97,7 +88,7 @@ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDe
|
|
|
97
88
|
summary=excluded.summary,
|
|
98
89
|
embedding=excluded.embedding,
|
|
99
90
|
content_hash=excluded.content_hash
|
|
100
|
-
`)
|
|
91
|
+
`),_=this.db.transaction(y=>{for(let E of y){let{meta:w,exports:x,imports:v,configs:k,events:N,content:O,classification:T,summary:I,embedding:U,contentHash:H}=E;r.run(w.path),o.run(w.path),c.run(w.path),a.run(w.path),l.run(w.path);let P=H??(O&&n?n(O):null);if(g.run(w.path,w.mtime,Date.now(),T||"Unknown",I||"",U?JSON.stringify(U):null,P),x){let R=(A,D,$)=>{for(let L of D){let Y=L.embedding?JSON.stringify(L.embedding):null,he=p.run(A,L.name,L.kind,L.signature,L.doc||"",L.line,L.endLine||L.line,L.classification||"Other",L.capabilities||"[]",$,Y);L.members&&L.members.length>0&&R(A,L.members,he.lastInsertRowid)}};R(w.path,x,null)}if(v)for(let R of v){let A=R.resolved_path!==void 0?R.resolved_path:s?.(R.module,w.path,t)??"";u.run(w.path,R.module,R.name,A)}if(k)for(let R of k)d.run(w.path,R.key,R.value,R.kind);if(O!==void 0&&m.run(w.path,O),N)for(let R of N)h.run(w.path,R.type,R.name,R.direction,R.line,R.snippet)}}),b=500;for(let y=0;y<e.length;y+=b)_(e.slice(y,y+b))}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}}});var dn,di=K(()=>{"use strict";Le();dn=class extends te{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
92
|
SELECT * FROM exports
|
|
102
93
|
WHERE file_path = ? AND start_line <= ? AND end_line >= ?
|
|
103
94
|
ORDER BY (end_line - start_line) ASC -- Get innermost symbol
|
|
@@ -188,7 +179,7 @@ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDe
|
|
|
188
179
|
SELECT * FROM exports
|
|
189
180
|
WHERE lower(name) LIKE ?
|
|
190
181
|
LIMIT ?
|
|
191
|
-
`,`%${e.toLowerCase()}%`,t)}getAllNames(e=5e3){return this.all("SELECT DISTINCT name FROM exports WHERE parent_id IS NULL LIMIT ?",e).map(n=>n.name)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM exports WHERE file_path = ?",e)?.count||0}findDeadExports(e={}){let{limit:t=50,includeTests:n=!1,includeMigrations:s=!1,includeFixtures:r=!1,excludePatterns:o=[],confidenceThreshold:c="all"}=e,a=[];n||(a.push("e.file_path NOT LIKE '%/test/%'"),a.push("e.file_path NOT LIKE '%/tests/%'"),a.push("e.file_path NOT LIKE '%/__tests__/%'"),a.push("e.file_path NOT LIKE '%.spec.%'"),a.push("e.file_path NOT LIKE '%.test.%'")),s||(a.push("e.file_path NOT LIKE '%/migrations/%'"),a.push("e.file_path NOT LIKE '%/migration/%'"),a.push("e.file_path NOT LIKE '%Migration.%'")),r||(a.push("e.file_path NOT LIKE '%/__fixtures__/%'"),a.push("e.file_path NOT LIKE '%/__mocks__/%'"),a.push("e.file_path NOT LIKE '%/fixtures/%'"),a.push("e.file_path NOT LIKE '%/mocks/%'"),a.push("e.file_path NOT LIKE '%.fixture.%'"),a.push("e.file_path NOT LIKE '%.mock.%'"));for(let m of o){let
|
|
182
|
+
`,`%${e.toLowerCase()}%`,t)}getAllNames(e=5e3){return this.all("SELECT DISTINCT name FROM exports WHERE parent_id IS NULL LIMIT ?",e).map(n=>n.name)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM exports WHERE file_path = ?",e)?.count||0}findDeadExports(e={}){let{limit:t=50,includeTests:n=!1,includeMigrations:s=!1,includeFixtures:r=!1,excludePatterns:o=[],confidenceThreshold:c="all"}=e,a=[];n||(a.push("e.file_path NOT LIKE '%/test/%'"),a.push("e.file_path NOT LIKE '%/tests/%'"),a.push("e.file_path NOT LIKE '%/__tests__/%'"),a.push("e.file_path NOT LIKE '%.spec.%'"),a.push("e.file_path NOT LIKE '%.test.%'")),s||(a.push("e.file_path NOT LIKE '%/migrations/%'"),a.push("e.file_path NOT LIKE '%/migration/%'"),a.push("e.file_path NOT LIKE '%Migration.%'")),r||(a.push("e.file_path NOT LIKE '%/__fixtures__/%'"),a.push("e.file_path NOT LIKE '%/__mocks__/%'"),a.push("e.file_path NOT LIKE '%/fixtures/%'"),a.push("e.file_path NOT LIKE '%/mocks/%'"),a.push("e.file_path NOT LIKE '%.fixture.%'"),a.push("e.file_path NOT LIKE '%.mock.%'"));for(let m of o){let h=m.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");a.push(`e.file_path NOT LIKE '${h}'`)}let l=a.length>0?`AND ${a.join(" AND ")}`:"",u=this.all(`
|
|
192
183
|
SELECT e.name, e.kind, e.file_path, e.start_line
|
|
193
184
|
FROM exports e
|
|
194
185
|
WHERE e.kind IN (
|
|
@@ -202,7 +193,7 @@ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDe
|
|
|
202
193
|
AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
|
|
203
194
|
ORDER BY e.file_path, e.start_line
|
|
204
195
|
LIMIT ?
|
|
205
|
-
`,t*2).map(m=>{let{confidence:
|
|
196
|
+
`,t*2).map(m=>{let{confidence:h,reason:g}=this.scoreDeadExportConfidence(m);return{...m,confidence:h,reason:g}}),d=u;return c==="high"?d=u.filter(m=>m.confidence==="high"):c==="medium"&&(d=u.filter(m=>m.confidence==="high"||m.confidence==="medium")),d.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"}: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"}}getGravityMap(e=[],t){let n={},s=`
|
|
206
197
|
SELECT ws.symbol_id, m.name as mission_name, m.status
|
|
207
198
|
FROM working_set ws
|
|
208
199
|
JOIN missions m ON ws.mission_id = m.id
|
|
@@ -211,14 +202,14 @@ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDe
|
|
|
211
202
|
OR m.id IN (${e.length>0?e.join(","):"-1"})
|
|
212
203
|
)
|
|
213
204
|
AND ws.symbol_id IS NOT NULL
|
|
214
|
-
`,r=[];t&&r.push(t);let o=this.all(s,...r);for(let l of o){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let p=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.symbol_id].score+=p;let
|
|
205
|
+
`,r=[];t&&r.push(t);let o=this.all(s,...r);for(let l of o){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let p=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.symbol_id].score+=p;let u=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.symbol_id].reasons.push(`${u}: ${l.mission_name}`)}let c=Math.floor(Date.now()/1e3)-86400,a=this.all(`
|
|
215
206
|
SELECT symbol_id, type, mission_id
|
|
216
207
|
FROM intent_logs
|
|
217
208
|
WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
|
|
218
209
|
AND symbol_id IS NOT NULL
|
|
219
210
|
ORDER BY created_at DESC
|
|
220
211
|
LIMIT 200
|
|
221
|
-
`,c);for(let l of a){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let p=l.mission_id?e.includes(l.mission_id):!1,
|
|
212
|
+
`,c);for(let l of a){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let p=l.mission_id?e.includes(l.mission_id):!1,u=p?.1:.2;n[l.symbol_id].score<5&&(n[l.symbol_id].score+=u);let d=p?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.symbol_id].reasons.includes(d)&&n[l.symbol_id].reasons.length<5&&n[l.symbol_id].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
|
|
222
213
|
SELECT kind, COUNT(*) as c
|
|
223
214
|
FROM exports
|
|
224
215
|
WHERE kind IS NOT NULL AND kind != ''
|
|
@@ -231,7 +222,7 @@ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDe
|
|
|
231
222
|
OR name LIKE ?
|
|
232
223
|
OR name LIKE ?
|
|
233
224
|
LIMIT 10
|
|
234
|
-
`,e,`%.${e}`,`%::${e}`)}}});var
|
|
225
|
+
`,e,`%.${e}`,`%::${e}`)}}});var ui,mi=K(()=>{"use strict";ui=`
|
|
235
226
|
WITH RECURSIVE dependency_chain AS (
|
|
236
227
|
-- Base case: Direct dependents of the target symbol
|
|
237
228
|
-- Meaning: Files that import the file where the symbol is defined
|
|
@@ -282,7 +273,7 @@ SELECT DISTINCT
|
|
|
282
273
|
dc.imported_symbols
|
|
283
274
|
FROM dependency_chain dc
|
|
284
275
|
ORDER BY dc.depth, dc.consumer_path;
|
|
285
|
-
`});var
|
|
276
|
+
`});var un,hi=K(()=>{"use strict";Le();mi();un=class extends te{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(`
|
|
286
277
|
SELECT * FROM imports
|
|
287
278
|
WHERE resolved_path IS NOT NULL AND resolved_path != ''
|
|
288
279
|
`)}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(`
|
|
@@ -308,7 +299,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
308
299
|
SELECT COUNT(*) as count FROM imports
|
|
309
300
|
WHERE resolved_path IN (${n})
|
|
310
301
|
AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
|
|
311
|
-
`,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(
|
|
302
|
+
`,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(ui,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});var mn,fi=K(()=>{"use strict";Le();mn=class extends te{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
|
|
312
303
|
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
313
304
|
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
|
|
314
305
|
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
@@ -338,7 +329,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
338
329
|
SELECT AVG(updated_at - created_at) AS avg_duration
|
|
339
330
|
FROM missions
|
|
340
331
|
WHERE status = 'completed' AND updated_at > created_at
|
|
341
|
-
`),s=n?.avg_duration!=null?Math.round(n.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,o=Math.floor(Date.now()/1e3)-720*3600,c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),a=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),l=c?.n??0,p=a?.n??0,
|
|
332
|
+
`),s=n?.avg_duration!=null?Math.round(n.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,o=Math.floor(Date.now()/1e3)-720*3600,c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),a=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),l=c?.n??0,p=a?.n??0,u=`${l} completed in last 7 days, ${p} in last 30 days.`;if(s!=null){let d=Math.round(s/60);u+=` Avg mission duration: ${d} min.`}return{completionRate:t,averageDurationSeconds:s,completedLast7Days:l,completedLast30Days:p,velocityNote:u}}suspendByBranch(e){this.run(`UPDATE missions
|
|
342
333
|
SET status = 'suspended', updated_at = unixepoch()
|
|
343
334
|
WHERE git_branch = ? AND status IN ('in-progress', 'planned', 'verifying')`,e)}resumeByBranch(e){this.run(`UPDATE missions
|
|
344
335
|
SET status = 'in-progress', updated_at = unixepoch()
|
|
@@ -363,7 +354,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
363
354
|
SELECT linked_repo_path, linked_mission_id, relationship, direction
|
|
364
355
|
FROM cross_repo_links
|
|
365
356
|
WHERE mission_id = ?
|
|
366
|
-
`,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")}}});var
|
|
357
|
+
`,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")}}});import{fileURLToPath as Ma}from"node:url";import{dirname as bs,join as yi,resolve as Da}from"node:path";import{existsSync as Oa}from"node:fs";function Wa(){let i=gi;for(;i!==bs(i);){if(Oa(yi(i,"package.json")))return i;i=bs(i)}return Da(gi,"..","..")}function ht(...i){return yi(Wa(),...i)}var Fa,gi,hn=K(()=>{"use strict";Fa=Ma(import.meta.url),gi=bs(Fa)});import{Worker as Ha}from"node:worker_threads";import{cpus as Ua}from"node:os";import{fileURLToPath as ja}from"node:url";import{dirname as za,join as bi}from"node:path";import{existsSync as _i}from"node:fs";function Ba(){if(Si.endsWith(".ts")){let e=bi(Ei,"worker.ts");if(_i(e))return e}let i=bi(Ei,"worker.js");return _i(i)?i:ht("dist/logic/domain/embeddings/worker.js")}function it(i){return ft||(ft=new gt(i)),ft}async function Mt(){ft&&(await ft.shutdown(),ft=null)}var Si,Ei,gt,ft,wi=K(()=>{"use strict";W();hn();Si=ja(import.meta.url),Ei=za(Si);gt=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(4,Ua().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{S.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((n,s)=>{e=setTimeout(()=>s(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,S.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,S.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=Ba();S.debug({workerPath:e},"Resolved worker path");let t=[];for(let n=0;n<this.numWorkers;n++)n>0&&await new Promise(s=>setTimeout(s,25)),t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,s)=>{let r=setTimeout(()=>{s(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new Ha(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),c={worker:o,busy:!1,currentTaskId:null};o.on("message",a=>{if(a.type==="ready"){if(clearTimeout(r),this.shutdownRequested){S.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(c),S.debug({workerIndex:t},"Worker ready"),n()}else a.type==="result"&&a.id?this.handleTaskComplete(c,a.id,a.embeddings||[]):a.type==="error"&&a.id&&this.handleTaskError(c,a.id,new Error(a.error||"Unknown error"))}),o.on("error",a=>{if(clearTimeout(r),S.error({err:a,workerIndex:t},"Worker error"),c.currentTaskId&&this.handleTaskError(c,c.currentTaskId,a),!this.initialized){s(a);return}let l=this.workers.indexOf(c);l!==-1&&this.workers.splice(l,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{S.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",a=>{a!==0&&!this.shutdownRequested&&S.warn({workerIndex:t,code:a},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.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 s=[];for(let l=0;l<e.length;l+=t)s.push(e.slice(l,l+t));let r=new Array(s.length),o=0,c=s.map((l,p)=>new Promise((u,d)=>{let h={id:`task_${++this.taskIdCounter}`,texts:l,resolve:g=>{if(r[p]=g,o++,n){let _=Math.min(o*t,e.length);n(_,e.length)}u()},reject:g=>{if(r[p]=new Array(l.length).fill(null),o++,S.warn({err:g,chunkIndex:p},"Chunk embedding failed"),n){let _=Math.min(o*t,e.length);n(_,e.length)}u()}};this.taskQueue.push(h),this.processQueue()}));await Promise.all(c);let a=[];for(let l of r)a.push(...l);return S.info({total:e.length,successful:a.filter(l=>l!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),a}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}S.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,S.info("Embedding worker pool shutdown complete")}},ft=null});var Ss={};ms(Ss,{EmbeddingPriorityQueue:()=>fn,EmbeddingWorkerPool:()=>gt,cosineSimilarity:()=>Ft,generateEmbedding:()=>gn,generateEmbeddingsBatch:()=>yn,getDefaultPool:()=>it,setUseWorkerThreads:()=>Ot,shutdownDefaultPool:()=>Mt});async function Ga(){return Dt||(Dt=await import("@xenova/transformers"),Dt.env.cacheDir="./.cache",Dt.env.allowLocalModels=!0),Dt}function Ot(i){Es=i,S.info({useWorkerThreads:i},"Worker thread mode updated")}async function vi(){return _s||(_s=(async()=>{S.info("Loading embedding model (all-MiniLM-L6-v2)...");let{pipeline:i}=await Ga();return await i("feature-extraction","Xenova/all-MiniLM-L6-v2")})()),_s}async function gn(i){try{let t=await(await vi())(i,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return S.error({err:e},"Failed to generate embedding"),null}}async function yn(i,e=xi,t){return i.length===0?[]:Es?it().generateEmbeddings(i,e,t):Ti(i,e,t)}async function Ti(i,e,t){let n=new Array(i.length).fill(null),s=await vi();for(let r=0;r<i.length;r+=e){let o=Math.min(r+e,i.length),c=i.slice(r,o);try{let a=await s(c,{pooling:"mean",normalize:!0}),[l,p]=a.dims;for(let u=0;u<l;u++){let d=u*p,m=d+p;n[r+u]=Array.from(a.data.slice(d,m))}}catch(a){S.error({err:a,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let l=0;l<c.length;l++)try{let p=c[l];if(!p||p.trim().length===0)continue;let u=await s(p,{pooling:"mean",normalize:!0});n[r+l]=Array.from(u.data)}catch{n[r+l]=null}}t&&t(o,i.length)}return S.debug({total:i.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function Ft(i,e){let t=0,n=0,s=0;for(let r=0;r<i.length;r++)t+=i[r]*e[r],n+=i[r]*i[r],s+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(s))}var Dt,xi,Es,_s,fn,rt=K(()=>{"use strict";W();wi();Dt=null;xi=128,Es=!1;_s=null;fn=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=xi,t){if(this.processing)return S.warn("Queue processing already in progress"),this.results;this.processing=!0;let n=this.queue.length;try{Es?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 s=this.queue.splice(0,e),r=s.map(c=>c.text),o=await Ti(r,r.length);if(s.forEach((c,a)=>{this.results.set(c.id,o[a])}),n){let c=t-this.queue.length;n(c,t)}}}async processQueueParallel(e,t,n){let s=this.queue.splice(0),r=s.map(a=>a.text),c=await it().generateEmbeddings(r,e,(a,l)=>{n&&n(a,l)});s.forEach((a,l)=>{this.results.set(a.id,c[l])})}clear(){this.queue=[],this.results.clear()}}});var bn,Ri=K(()=>{"use strict";Le();W();bn=class i extends te{findByMission(e,t=50){return this.all(`
|
|
367
358
|
SELECT * FROM intent_logs
|
|
368
359
|
WHERE mission_id = ?
|
|
369
360
|
ORDER BY created_at DESC
|
|
@@ -373,10 +364,10 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
373
364
|
WHERE type IN ('decision', 'system', 'fix', 'heritage', 'adr')
|
|
374
365
|
ORDER BY created_at DESC
|
|
375
366
|
LIMIT ?
|
|
376
|
-
`,e)}create(e){
|
|
367
|
+
`,e)}create(e){let t=this.insert(`
|
|
377
368
|
INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
|
|
378
369
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
379
|
-
`,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha)}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 s=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${s} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
|
|
370
|
+
`,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha);return i.EMBEDDABLE_TYPES.has(e.type)&&this.generateAndStoreEmbedding(Number(t),e).catch(n=>{S.debug({err:n,intentLogId:t},"Failed to generate intent log embedding")}),t}static EMBEDDABLE_TYPES=new Set(["decision","discovery","fix","blocker","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(()=>(rt(),Ss)),s=i.buildEmbeddingText(t),r=await n(s);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')")}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 s=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${s} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
|
|
380
371
|
SELECT id, file_path, symbol_name, signature
|
|
381
372
|
FROM intent_logs
|
|
382
373
|
WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
|
|
@@ -401,31 +392,50 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
401
392
|
`,e)}importHeritage(e,t,n,s){this.run(`
|
|
402
393
|
INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
|
|
403
394
|
VALUES ('heritage', ?, ?, ?, ?, 0)
|
|
404
|
-
`,e,t,n,s)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}
|
|
395
|
+
`,e,t,n,s)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}findRawByMission(e){return this.all(`SELECT * FROM intent_logs
|
|
396
|
+
WHERE mission_id = ? AND is_crystallized = 0
|
|
397
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
398
|
+
ORDER BY created_at ASC`,e)}findCrystalByMission(e){return this.get(`SELECT * FROM intent_logs
|
|
399
|
+
WHERE mission_id = ? AND type = 'crystal'
|
|
400
|
+
ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t){return this.transaction(()=>{let n=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
|
|
401
|
+
VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
|
|
402
|
+
SET is_crystallized = 1, crystal_id = ?
|
|
403
|
+
WHERE mission_id = ? AND is_crystallized = 0 AND id != ?
|
|
404
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),n})}countByMissions(e){if(e.length===0)return{};let t=e.map(()=>"?").join(","),n=this.all(`SELECT mission_id, COUNT(*) as cnt
|
|
405
|
+
FROM intent_logs
|
|
406
|
+
WHERE mission_id IN (${t})
|
|
407
|
+
AND type NOT IN ('system', 'adr', 'lapsed')
|
|
408
|
+
GROUP BY mission_id`,...e),s={};for(let r of n)s[r.mission_id]=r.cnt;return s}findMissionsWithBlockers(e){if(e.length===0)return new Set;let t=e.map(()=>"?").join(","),n=this.all(`SELECT DISTINCT mission_id
|
|
409
|
+
FROM intent_logs
|
|
410
|
+
WHERE mission_id IN (${t})
|
|
411
|
+
AND type = 'blocker'`,...e);return new Set(n.map(s=>s.mission_id))}findByMissionPreferCrystal(e,t=50){let n=this.findCrystalByMission(e);if(n){let s=this.all(`SELECT * FROM intent_logs
|
|
412
|
+
WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
413
|
+
AND created_at > ?
|
|
414
|
+
ORDER BY created_at DESC LIMIT ?`,e,n.created_at,t-1);return[n,...s]}return this.findByMission(e,t)}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:n}=await Promise.resolve().then(()=>(rt(),Ss)),s=[...i.EMBEDDABLE_TYPES].map(p=>`'${p}'`).join(","),r=this.all(`SELECT * FROM intent_logs WHERE embedding IS NULL AND type IN (${s})`);if(r.length===0)return 0;let o=r.map(p=>i.buildEmbeddingText(p)),c=await n(o,e,t),a=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),l=0;return this.transaction(()=>{for(let p=0;p<r.length;p++)c[p]&&(a.run(JSON.stringify(c[p]),r[p].id),l++)}),S.info({total:r.length,embedded:l},"Intent log embedding backfill complete"),l}}});var _n,ki=K(()=>{"use strict";Le();_n=class extends te{findByKey(e,t=20){return this.all(`
|
|
405
415
|
SELECT file_path, key, value, kind
|
|
406
416
|
FROM configs
|
|
407
417
|
WHERE key LIKE ? OR value LIKE ?
|
|
408
418
|
LIMIT ?
|
|
409
|
-
`,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",s=[];return e&&(n+=" WHERE kind = ?",s.push(e)),n+=" LIMIT ?",s.push(t),this.all(n,...s)}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
|
|
419
|
+
`,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",s=[];return e&&(n+=" WHERE kind = ?",s.push(e)),n+=" LIMIT ?",s.push(t),this.all(n,...s)}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 En,Ii=K(()=>{"use strict";Le();En=class extends te{search(e,t=10){return this.all(`
|
|
410
420
|
SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
|
|
411
421
|
FROM content_fts
|
|
412
422
|
WHERE content_fts MATCH ?
|
|
413
423
|
LIMIT ?
|
|
414
|
-
`,e,t)}}});var
|
|
415
|
-
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)<=
|
|
424
|
+
`,e,t)}}});var Ci,Sn,Li=K(()=>{"use strict";Le();Ci=500,Sn=class extends te{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
|
|
425
|
+
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)<=Ci||this.run(`DELETE FROM search_history WHERE id NOT IN (
|
|
416
426
|
SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
|
|
417
|
-
)`,
|
|
427
|
+
)`,Ci)}}});var wn,$i=K(()=>{"use strict";Le();wn=class extends te{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(`
|
|
418
428
|
INSERT INTO hologram_snapshot (section, data, updated_at)
|
|
419
429
|
VALUES (?, ?, unixepoch())
|
|
420
430
|
ON CONFLICT(section) DO UPDATE SET
|
|
421
431
|
data = excluded.data,
|
|
422
432
|
updated_at = excluded.updated_at
|
|
423
|
-
`,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 C,U=Q(()=>{"use strict";Qe();Ys();Vs();Xs();Zs();ei();ti();ni();ii();ri();C=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=ke(e),o=t.files?.database,c=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!c)return t;this.repositoryCache.delete(e)}let n=ke(e),s={files:new Vt(n),exports:new Qt(n),imports:new Kt(n),missions:new Xt(n),intentLogs:new Zt(n),configs:new en(n),content:new tn(n),searchHistory:new nn(n),hologram:new sn(n)};return this.repositoryCache.set(e,s),s}static closeInstance(e){this.repositoryCache.delete(e),Yt(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var ci=qo((yp,es)=>{var on=process||{},oi=on.argv||[],rn=on.env||{},ua=!(rn.NO_COLOR||oi.includes("--no-color"))&&(!!rn.FORCE_COLOR||oi.includes("--color")||on.platform==="win32"||(on.stdout||{}).isTTY&&rn.TERM!=="dumb"||!!rn.CI),da=(i,e,t=i)=>n=>{let s=""+n,r=s.indexOf(e,i.length);return~r?i+ma(s,e,t,r)+e:i+s+e},ma=(i,e,t,n)=>{let s="",r=0;do s+=i.substring(r,n)+t,r=n+e.length,n=i.indexOf(e,r);while(~n);return s+i.substring(r)},ai=(i=ua)=>{let e=i?da:()=>String;return{isColorSupported:i,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")}};es.exports=ai();es.exports.createColors=ai});var mr,hr,fr,gr,yr,br,Er,Sr,_r,xr,Tr,Rr,vr,wr,Ts,Ir,Cr,$r,kr=Q(()=>{"use strict";mr=[/\/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],hr=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],fr=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],gr=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],yr=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],br=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],Er=[/\/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],Sr=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],_r=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],xr=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],Tr=[/\/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],Rr=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],vr=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],wr=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],Ts=[/\.(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)$/],Ir=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],Cr=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],$r=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var Lr,Nr,Ar,Mr,Pr=Q(()=>{"use strict";Lr=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],Nr=[/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],Ar=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],Mr=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var Dr,Or,Fr,Hr,Wr=Q(()=>{"use strict";Dr=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],Or=[/\/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],Fr=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],Hr=["laravel","symfony","slim","cakephp","codeigniter"]});import jr from"path";function Dt(i,e,t){let n=[],s="Unknown",r=0;t||(t=bc(i,e));let{inDegree:o,outDegree:c}=t,a=(u,m,f,h)=>{for(let b of u)if(b.test(i))return n.push(`${h}: ${b.source}`),s=m,r+=f,!0;return!1},l=!1;if(l||(l=a(mr,"Entry",45,"Next.js entry")),l||(l=a(yr,"Entry",40,"MCP handler")),l||(l=a(Er,"Entry",40,"CLI command")),l||(l=a(Ts,"Data",45,"Data layer/Repository")),l||(l=a(Tr,"Data",35,"State management")),l||(l=a(fr,"Logic",40,"React component")),l||(l=a(gr,"Logic",35,"Logic pattern")),l||(l=a(Sr,"Logic",35,"Parser/AST")),l||(l=a(_r,"Logic",35,"Core module")),l||(l=a(xr,"Logic",30,"UI layer")),l||(l=a(wr,"Types",35,"Type definition")),l||(l=a(Lr,"Entry",40,"Python Entry")),l||(l=a(Ar,"Data",40,"Python Data")),l||(l=a(Nr,"Logic",35,"Python Logic")),l||(l=a(Dr,"Entry",40,"PHP Entry")),l||(l=a(Fr,"Data",40,"PHP Data")),l||(l=a(Or,"Logic",35,"PHP Logic")),l||(l=a(Rr,"Logic",35,"Hook/Context")),!l){for(let u of br)if(u.test(i)){n.push(`MCP utility: ${u.source}`),/schemas?/i.test(i)?s="Types":/resources?/i.test(i)?s="Data":s="Utility",r+=35,l=!0;break}}l||a(vr,"Data",35,"Schema definition")&&(l=!0),l||(a(Ts,"Data",30,"Path matches data pattern")||a(Ir,"Utility",25,"Path matches utility pattern")||a(hr,"Entry",30,"Path matches entry pattern"))&&(l=!0);for(let u of fc)if(u.test(i)){n.push(`Test file: ${u.source}`),s="Test",r=50,l=!0;break}l||a(gc,"Infrastructure",40,"Infrastructure")&&(l=!0);for(let u of yc)u.test(i)&&(n.push(`Monorepo component: ${u.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(i)&&(n.push("Monorepo App Entry"),s==="Unknown"&&(s="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(i)&&(r+=10));let d=e.imports.getImportsForFile(i).map(u=>u.module_specifier.toLowerCase());for(let u of $r)if(d.some(m=>m.includes(u))){n.push(`Imports JS data library: ${u}`),(s==="Unknown"||s==="Data")&&(s="Data",r+=25);break}for(let u of Mr)if(d.some(m=>m.includes(u))){n.push(`Imports Python framework: ${u}`),(s==="Unknown"||s==="Entry")&&(s="Entry",r+=20);break}for(let u of Hr)if(d.some(m=>m.includes(u))){n.push(`Imports PHP framework: ${u}`),(s==="Unknown"||s==="Entry")&&(s="Entry",r+=20);break}for(let u of Cr)if(d.some(m=>m.includes(u))){n.push(`Imports JS framework: ${u}`),(s==="Unknown"||s==="Entry")&&(s="Entry",r+=20);break}if(o===0&&c>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),s==="Unknown"?(s="Entry",r+=30):s==="Entry"&&(r+=15)),o>5&&c<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),s==="Unknown"?(s="Utility",r+=25):s==="Utility"&&(r+=10)),s==="Unknown"&&o>0&&c>0){let u=o/(o+c);u>.3&&u<.7&&(n.push(`Balanced traffic: in=${o}, out=${c} (likely Logic layer)`),s="Logic",r+=25)}return s==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:s,confidence:r,signals:n}}function bc(i,e){let t=e.imports.countDependents(i),n=e.imports.countByFile(i);return{inDegree:t,outDegree:n}}function je(i,e){let t=i.files.getAllPaths().map(f=>({path:f})),n=new Map,s={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let f of t){let h=Dt(f.path,i);n.set(f.path,h),s[h.layer].push({path:f.path,classification:h})}let r={Entry:We(s.Entry,e),Logic:We(s.Logic,e),Data:We(s.Data,e),Utility:We(s.Utility,e),Infrastructure:We(s.Infrastructure,e),Test:We(s.Test,e),Types:We(s.Types,e),Unknown:We(s.Unknown,e)},o={};t.forEach(f=>{let h=jr.extname(f.path).toLowerCase();h&&(o[h]=(o[h]||0)+1)});let c={".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"},a={};Object.entries(o).forEach(([f,h])=>{let b=c[f];b&&(a[b]=(a[b]||0)+h)});let l=Object.entries(a).sort((f,h)=>h[1]-f[1]),p=l.length>0?l[0][0]:"Unknown",{pattern:d,patternConfidence:u,insights:m}=Ec(r,t.length,i);return{pattern:d,patternConfidence:u,layers:r,insights:m,primaryStack:p}}function We(i,e){return i.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:i.length,topFiles:i.slice(0,5).map(t=>({path:jr.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function Ec(i,e,t){let n=[],s="Unknown",r=0,o=i.Entry.count/e*100,c=i.Logic.count/e*100,a=i.Data.count/e*100,l=i.Utility.count/e*100,p=i.Unknown.count/e*100;o>5&&c>10&&a>5&&p<40?(s="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${c.toFixed(1)}%), Data (${a.toFixed(1)}%)`)):l>20?(s="Modular",r=50+l/2,n.push(`High shared module usage: ${l.toFixed(1)}% utility files`)):p>60&&(s="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let d=t.configs.countByKind("Service");return d>3&&(s="Microservices",r=55+d*5,n.push(`Detected ${d} service definitions (likely microservices)`)),i.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),i.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:s,patternConfidence:Math.min(100,r),insights:n}}var fc,gc,yc,Ot=Q(()=>{"use strict";kr();Pr();Wr();fc=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],gc=[/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],yc=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});var Ur={};Os(Ur,{HologramService:()=>ue});var ye,ue,dt=Q(()=>{"use strict";U();Ot();P();ye=_.child({module:"hologram"}),ue=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=C.getInstance(e)}updateTopography(e){ye.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 c=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(c*10)/10,topFiles:o.topFiles.slice(0,3).map(a=>({path:a.path,confidence:a.confidence}))}}let s={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(s)),ye.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=je(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){ye.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)),ye.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){ye.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)),ye.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 s=JSON.parse(n.data);switch(n.section){case"topography":t.topography=s;break;case"gravity":t.gravity=s;break;case"ghosts":t.ghosts=s;break}}catch(s){ye.error({repoPath:this.repoPath,section:n.section,error:s},"Failed to parse 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 ye.error({repoPath:this.repoPath,section:e,error:n},"Failed to parse section"),null}}computeGravityZones(){ye.debug({repoPath:this.repoPath},"Computing gravity zones from import graph");let e=this.repos.files.getAllPaths(),t=new Map;for(let s of e){let r=Dt(s,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(s);if(o.length===0)continue;let c=this.repos.imports.countDependents(s),a=this.repos.imports.countByFile(s),l=c*2+a;if(l>0){let p=o.find(u=>u.kind!=="TsTypeAliasDeclaration"&&u.kind!=="TsInterfaceDeclaration")||o[0],d=`${s}::${p.name}`;t.set(d,{symbol:p.name,filePath:s,inDegree:c,outDegree:a,gravity:l})}}let n=Array.from(t.values()).sort((s,r)=>r.gravity-s.gravity).slice(0,50);return ye.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),ye.info({repoPath:this.repoPath},"Hologram cleared")}}});var Io={};Os(Io,{GraphExporterService:()=>Ps});var wo,Ps,Co=Q(()=>{"use strict";U();P();wo=_.child({module:"graph-exporter"}),Ps=class{constructor(e){this.repoPath=e;this.repos=C.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:s,depth:r=10,limit:o=100}=e;wo.info({focusMissionId:s,depth:r,format:n,includeCompleted:t},"Generating mission graph");let c=this.buildMissionTree(s,t,r,o);return n==="json"?JSON.stringify(c,null,2):this.generateMermaidDiagram(c)}buildMissionTree(e,t,n,s){let r;if(e){let a=this.repos.missions.findById(e);r=a?[a]:[]}else r=this.repos.missions.findAll().filter(l=>!l.parent_id),t||(r=r.filter(l=>l.status!=="completed"));let o=0,c=[];for(let a of r){if(o>=s)break;let l=this.buildNode(a,t,n,1,{count:o,max:s});l&&(c.push(l),o+=this.countNodes(l))}return c}buildNode(e,t,n,s,r){if(s>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){wo.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let c={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},a=this.repos.missions.findByParentId(e.id),l=t?a:a.filter(p=>p.status!=="completed");for(let p of l){if(r.count>=r.max)break;let d=this.buildNode(p,t,n,s+1,r);d&&(c.children.push(d),r.count++)}return c}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,s)=>({id:n.id||`step-${s}`,description:n.description||n.content||n.name||`Step ${s+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,s])=>({id:n,description:s.description||s.content||n,status:s.status,dependencies:s.dependencies||s.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(`
|
|
424
|
-
`)}addMermaidNode(e,t,n){let s=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),c=`${r} ${e.name}`;if(t.push(` ${s}["${this.escapeMermaid(c)}"]:::${o}`),n&&t.push(` ${n} --> ${s}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let a of e.steps){let l=`S${e.id}_${a.id}`,p=a.status||"pending",
|
|
425
|
-
`),s=
|
|
426
|
-
${
|
|
427
|
-
${
|
|
428
|
-
${
|
|
433
|
+
`,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 C,z=K(()=>{"use strict";qe();pi();di();hi();fi();Ri();ki();Ii();Li();$i();C=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=We(e),o=t.files?.database,c=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!c)return t;this.repositoryCache.delete(e)}let n=We(e),s={files:new pn(n),exports:new dn(n),imports:new un(n),missions:new mn(n),intentLogs:new bn(n),configs:new _n(n),content:new En(n),searchHistory:new Sn(n),hologram:new wn(n)};return this.repositoryCache.set(e,s),s}static closeInstance(e){this.repositoryCache.delete(e),ln(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var Pi=ga((yd,ws)=>{var vn=process||{},Ni=vn.argv||[],xn=vn.env||{},qa=!(xn.NO_COLOR||Ni.includes("--no-color"))&&(!!xn.FORCE_COLOR||Ni.includes("--color")||vn.platform==="win32"||(vn.stdout||{}).isTTY&&xn.TERM!=="dumb"||!!xn.CI),Ja=(i,e,t=i)=>n=>{let s=""+n,r=s.indexOf(e,i.length);return~r?i+Ya(s,e,t,r)+e:i+s+e},Ya=(i,e,t,n)=>{let s="",r=0;do s+=i.substring(r,n)+t,r=n+e.length,n=i.indexOf(e,r);while(~n);return s+i.substring(r)},Ai=(i=qa)=>{let e=i?Ja:()=>String;return{isColorSupported:i,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")}};ws.exports=Ai();ws.exports.createColors=Ai});var Mr,Dr,Or,Fr,Wr,Hr,Ur,jr,zr,Br,Gr,qr,Jr,Yr,Hs,Vr,Qr,Kr,Xr=K(()=>{"use strict";Mr=[/\/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],Dr=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],Or=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],Fr=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],Wr=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],Hr=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],Ur=[/\/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],jr=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],zr=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],Br=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],Gr=[/\/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],qr=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],Jr=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],Yr=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],Hs=[/\.(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)$/],Vr=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],Qr=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],Kr=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var Zr,eo,to,no,so=K(()=>{"use strict";Zr=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],eo=[/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],to=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],no=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var io,ro,oo,ao,co=K(()=>{"use strict";io=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],ro=[/\/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],oo=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],ao=["laravel","symfony","slim","cakephp","codeigniter"]});import lo from"path";function Qt(i,e,t){let n=[],s="Unknown",r=0;t||(t=el(i,e));let{inDegree:o,outDegree:c}=t,a=(d,m,h,g)=>{for(let _ of d)if(_.test(i))return n.push(`${g}: ${_.source}`),s=m,r+=h,!0;return!1},l=!1;if(l||(l=a(Mr,"Entry",45,"Next.js entry")),l||(l=a(Wr,"Entry",40,"MCP handler")),l||(l=a(Ur,"Entry",40,"CLI command")),l||(l=a(Hs,"Data",45,"Data layer/Repository")),l||(l=a(Gr,"Data",35,"State management")),l||(l=a(Or,"Logic",40,"React component")),l||(l=a(Fr,"Logic",35,"Logic pattern")),l||(l=a(jr,"Logic",35,"Parser/AST")),l||(l=a(zr,"Logic",35,"Core module")),l||(l=a(Br,"Logic",30,"UI layer")),l||(l=a(Yr,"Types",35,"Type definition")),l||(l=a(Zr,"Entry",40,"Python Entry")),l||(l=a(to,"Data",40,"Python Data")),l||(l=a(eo,"Logic",35,"Python Logic")),l||(l=a(io,"Entry",40,"PHP Entry")),l||(l=a(oo,"Data",40,"PHP Data")),l||(l=a(ro,"Logic",35,"PHP Logic")),l||(l=a(qr,"Logic",35,"Hook/Context")),!l){for(let d of Hr)if(d.test(i)){n.push(`MCP utility: ${d.source}`),/schemas?/i.test(i)?s="Types":/resources?/i.test(i)?s="Data":s="Utility",r+=35,l=!0;break}}l||a(Jr,"Data",35,"Schema definition")&&(l=!0),l||(a(Hs,"Data",30,"Path matches data pattern")||a(Vr,"Utility",25,"Path matches utility pattern")||a(Dr,"Entry",30,"Path matches entry pattern"))&&(l=!0);for(let d of Kc)if(d.test(i)){n.push(`Test file: ${d.source}`),s="Test",r=50,l=!0;break}l||a(Xc,"Infrastructure",40,"Infrastructure")&&(l=!0);for(let d of Zc)d.test(i)&&(n.push(`Monorepo component: ${d.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(i)&&(n.push("Monorepo App Entry"),s==="Unknown"&&(s="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(i)&&(r+=10));let u=e.imports.getImportsForFile(i).map(d=>d.module_specifier.toLowerCase());for(let d of Kr)if(u.some(m=>m.includes(d))){n.push(`Imports JS data library: ${d}`),(s==="Unknown"||s==="Data")&&(s="Data",r+=25);break}for(let d of no)if(u.some(m=>m.includes(d))){n.push(`Imports Python framework: ${d}`),(s==="Unknown"||s==="Entry")&&(s="Entry",r+=20);break}for(let d of ao)if(u.some(m=>m.includes(d))){n.push(`Imports PHP framework: ${d}`),(s==="Unknown"||s==="Entry")&&(s="Entry",r+=20);break}for(let d of Qr)if(u.some(m=>m.includes(d))){n.push(`Imports JS framework: ${d}`),(s==="Unknown"||s==="Entry")&&(s="Entry",r+=20);break}if(o===0&&c>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),s==="Unknown"?(s="Entry",r+=30):s==="Entry"&&(r+=15)),o>5&&c<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),s==="Unknown"?(s="Utility",r+=25):s==="Utility"&&(r+=10)),s==="Unknown"&&o>0&&c>0){let d=o/(o+c);d>.3&&d<.7&&(n.push(`Balanced traffic: in=${o}, out=${c} (likely Logic layer)`),s="Logic",r+=25)}return s==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:s,confidence:r,signals:n}}function el(i,e){let t=e.imports.countDependents(i),n=e.imports.countByFile(i);return{inDegree:t,outDegree:n}}function Ze(i,e){let t=i.files.getAllPaths().map(h=>({path:h})),n=new Map,s={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let h of t){let g=Qt(h.path,i);n.set(h.path,g),s[g.layer].push({path:h.path,classification:g})}let r={Entry:Xe(s.Entry,e),Logic:Xe(s.Logic,e),Data:Xe(s.Data,e),Utility:Xe(s.Utility,e),Infrastructure:Xe(s.Infrastructure,e),Test:Xe(s.Test,e),Types:Xe(s.Types,e),Unknown:Xe(s.Unknown,e)},o={};t.forEach(h=>{let g=lo.extname(h.path).toLowerCase();g&&(o[g]=(o[g]||0)+1)});let c={".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"},a={};Object.entries(o).forEach(([h,g])=>{let _=c[h];_&&(a[_]=(a[_]||0)+g)});let l=Object.entries(a).sort((h,g)=>g[1]-h[1]),p=l.length>0?l[0][0]:"Unknown",{pattern:u,patternConfidence:d,insights:m}=tl(r,t.length,i);return{pattern:u,patternConfidence:d,layers:r,insights:m,primaryStack:p}}function Xe(i,e){return i.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:i.length,topFiles:i.slice(0,5).map(t=>({path:lo.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function tl(i,e,t){let n=[],s="Unknown",r=0,o=i.Entry.count/e*100,c=i.Logic.count/e*100,a=i.Data.count/e*100,l=i.Utility.count/e*100,p=i.Unknown.count/e*100;o>5&&c>10&&a>5&&p<40?(s="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${c.toFixed(1)}%), Data (${a.toFixed(1)}%)`)):l>20?(s="Modular",r=50+l/2,n.push(`High shared module usage: ${l.toFixed(1)}% utility files`)):p>60&&(s="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&&(s="Microservices",r=55+u*5,n.push(`Detected ${u} service definitions (likely microservices)`)),i.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),i.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:s,patternConfidence:Math.min(100,r),insights:n}}var Kc,Xc,Zc,Kt=K(()=>{"use strict";Xr();so();co();Kc=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],Xc=[/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],Zc=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});var po={};ms(po,{HologramService:()=>ge});var Te,ge,Rt=K(()=>{"use strict";z();Kt();W();Te=S.child({module:"hologram"}),ge=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=C.getInstance(e)}updateTopography(e){Te.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 c=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(c*10)/10,topFiles:o.topFiles.slice(0,3).map(a=>({path:a.path,confidence:a.confidence}))}}let s={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(s)),Te.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=Ze(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){Te.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)),Te.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){Te.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)),Te.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 s=JSON.parse(n.data);switch(n.section){case"topography":t.topography=s;break;case"gravity":t.gravity=s;break;case"ghosts":t.ghosts=s;break}}catch(s){Te.error({repoPath:this.repoPath,section:n.section,error:s},"Failed to parse 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 Te.error({repoPath:this.repoPath,section:e,error:n},"Failed to parse section"),null}}computeGravityZones(){Te.debug({repoPath:this.repoPath},"Computing gravity zones from import graph");let e=this.repos.files.getAllPaths(),t=new Map;for(let s of e){let r=Qt(s,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(s);if(o.length===0)continue;let c=this.repos.imports.countDependents(s),a=this.repos.imports.countByFile(s),l=c*2+a;if(l>0){let p=o.find(d=>d.kind!=="TsTypeAliasDeclaration"&&d.kind!=="TsInterfaceDeclaration")||o[0],u=`${s}::${p.name}`;t.set(u,{symbol:p.name,filePath:s,inDegree:c,outDegree:a,gravity:l})}}let n=Array.from(t.values()).sort((s,r)=>r.gravity-s.gravity).slice(0,50);return Te.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),Te.info({repoPath:this.repoPath},"Hologram cleared")}}});var Qo={};ms(Qo,{GraphExporterService:()=>Xs});var Vo,Xs,Ko=K(()=>{"use strict";z();W();Vo=S.child({module:"graph-exporter"}),Xs=class{constructor(e){this.repoPath=e;this.repos=C.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:s,depth:r=10,limit:o=100}=e;Vo.info({focusMissionId:s,depth:r,format:n,includeCompleted:t},"Generating mission graph");let c=this.buildMissionTree(s,t,r,o);return n==="json"?JSON.stringify(c,null,2):this.generateMermaidDiagram(c)}buildMissionTree(e,t,n,s){let r;if(e){let a=this.repos.missions.findById(e);r=a?[a]:[]}else r=this.repos.missions.findAll().filter(l=>!l.parent_id),t||(r=r.filter(l=>l.status!=="completed"));let o=0,c=[];for(let a of r){if(o>=s)break;let l=this.buildNode(a,t,n,1,{count:o,max:s});l&&(c.push(l),o+=this.countNodes(l))}return c}buildNode(e,t,n,s,r){if(s>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){Vo.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let c={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},a=this.repos.missions.findByParentId(e.id),l=t?a:a.filter(p=>p.status!=="completed");for(let p of l){if(r.count>=r.max)break;let u=this.buildNode(p,t,n,s+1,r);u&&(c.children.push(u),r.count++)}return c}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,s)=>({id:n.id||`step-${s}`,description:n.description||n.content||n.name||`Step ${s+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,s])=>({id:n,description:s.description||s.content||n,status:s.status,dependencies:s.dependencies||s.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(`
|
|
434
|
+
`)}addMermaidNode(e,t,n){let s=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),c=`${r} ${e.name}`;if(t.push(` ${s}["${this.escapeMermaid(c)}"]:::${o}`),n&&t.push(` ${n} --> ${s}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let a of e.steps){let l=`S${e.id}_${a.id}`,p=a.status||"pending",u=this.getStatusIcon(p),d=this.getStatusClass(p),m=`${u} ${a.description}`;if(t.push(` ${l}["${this.escapeMermaid(m)}"]:::${d}`),t.push(` ${s} -.-> ${l}`),a.dependencies&&a.dependencies.length>0)for(let h of a.dependencies){let g=`S${e.id}_${h}`;t.push(` ${g} --> ${l}`)}}for(let a of e.children)this.addMermaidNode(a,t,s);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 ep}from"clerc";W();import ti from"fs";import wa from"path";import ni from"js-yaml";var si={ignore:[],include:[],maxDepth:10},xa=[{name:".liquid-shadow.yaml",parse:i=>ni.load(i)??{}},{name:".liquid-shadow.yml",parse:i=>ni.load(i)??{}},{name:".ls.json",parse:i=>JSON.parse(i)},{name:".liquid-shadow.json",parse:i=>JSON.parse(i)},{name:".ls.rc",parse:i=>JSON.parse(i)},{name:".liquid-shadow.rc",parse:i=>JSON.parse(i)}];function Oe(i){for(let{name:e,parse:t}of xa){let n=wa.join(i,e);if(ti.existsSync(n))try{let s=ti.readFileSync(n,"utf8"),r=t(s);return S.debug({repoPath:i,configFile:e},"Loaded repository configuration"),{...si,...r}}catch(s){S.error({repoPath:i,file:e,err:s},"Failed to parse configuration file")}}return si}function hs(i,e){let n=Oe(i).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}z();import Qa from"path";var re=ba(Pi(),1);import*as $e from"@clack/prompts";var q={red:re.default.red,green:re.default.green,yellow:re.default.yellow,blue:re.default.blue,magenta:re.default.magenta,cyan:re.default.cyan,white:re.default.white,gray:re.default.gray,bold:re.default.bold,dim:re.default.dim,italic:re.default.italic,underline:re.default.underline,inverse:re.default.inverse},Je=i=>i.replace(/\x1b\[[0-9;]*m/g,""),se=i=>$e.intro(re.default.bgCyan(re.default.black(re.default.bold(` ${i} `)))),Ee=i=>$e.outro(re.default.cyan(i)),X=(i,e,t="blue")=>{let n=e.split(`
|
|
435
|
+
`),s=Je(i),r=Math.max(s.length+4,...n.map(a=>Je(a).length))+2,o="\u2500".repeat(r),c=q[t];console.log(c(`\u250C${o}\u2510`)),console.log(c("\u2502 ")+q.bold(i).padEnd(r+(i.length-s.length)-1)+c("\u2502")),console.log(c(`\u251C${o}\u2524`)),n.forEach(a=>{let l=Je(a),p=" ".repeat(r-l.length-1);console.log(c("\u2502 ")+a+p+c("\u2502"))}),console.log(c(`\u2514${o}\u2518`))},Tn=(i,e)=>{let t=i.map((s,r)=>Math.max(Je(s).length,...e.map(o=>Je(o[r]||"").length))+2),n=q.cyan("\u2502");console.log(n),console.log(n+" "+i.map((s,r)=>q.bold(q.cyan(s)).padEnd(t[r]+(s.length-Je(s).length))).join(q.gray(" "))+" "),e.forEach(s=>{console.log(n+" "+s.map((r,o)=>(r||"").padEnd(t[o]+(r.length-Je(r).length))).join(q.gray(" "))+" ")}),console.log(n)},Mi=(i,e="\u2022")=>{i.forEach(t=>{console.log(`${q.cyan("\u2502")} ${q.cyan(e)} ${t}`)})},Rn=(i,e=40)=>{let t=Math.max(...i.map(s=>s.value)),n=Math.max(...i.map(s=>Je(s.label).length));console.log(q.cyan("\u2502")),i.forEach(s=>{let r=Math.round(s.value/t*e),o="\u2588".repeat(r)+q.dim("\u2591".repeat(e-r)),c=s.color?q[s.color]:q.cyan,a=s.label.padEnd(n);console.log(`${q.cyan("\u2502")} ${q.bold(a)} ${c(o)} ${q.white(s.value.toString())}`)}),console.log(q.cyan("\u2502"))},xs=(i,e="")=>{i.forEach((t,n)=>{let s=n===i.length-1,r=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?q[t.color]:t.children?q.blue:q.white,c=t.info?` ${q.gray(`(${t.info})`)}`:"";if(console.log(`${q.cyan("\u2502")} ${e}${q.gray(r)}${o(t.name)}${c}`),t.children&&t.children.length>0){let a=e+(s?" ":"\u2502 ");xs(t.children,a)}})},be=()=>$e.spinner();async function kn(i,e,t){if(e.length===0)return;let n=await $e.select({message:i,options:e.map(s=>({value:s.value,label:s.label,...s.hint!=null&&{hint:s.hint}})),...t?.limit!=null&&{maxItems:t.limit}});if(!$e.isCancel(n))return n}var Va=i=>{console.error("");let e=i instanceof Error?i.message:String(i);console.error(` ${q.red("\u2716")} ${q.bold("Error: ")} ${e}`),i instanceof Error&&"cause"in i&&console.error(` ${q.dim("Cause: "+String(i.cause))}`),console.error(""),process.exit(1)},B=async i=>{try{await i()}catch(e){Va(e)}},f=q;rt();qe();W();async function J(i){S.debug("Performing graceful shutdown...");try{await Mt()}catch(e){S.error({err:e},"Error shutting down worker pool")}try{i&&ln(i)}catch(e){S.error({err:e},"Error closing database")}S.debug("Shutdown complete")}async function Di(i){let e=Qa.resolve(i);try{await B(async()=>{se("\u{1F311} Liquid Shadow: Scouting Report");let t=C.getInstance(e),n=Oe(e),s=n.ignore&&n.ignore.length>0,r=t.files.getCount(),o=t.exports.getCount(),c=t.files.getLatestScanTime(),a=t.exports.getKindDistribution(5);X("Intelligence Summary",`${f.bold("\u{1F4E1} Topology")}: ${f.cyan(r.toString())} files mapped
|
|
436
|
+
${f.bold("\u{1F9E9} Symbols")}: ${f.cyan(o.toString())} exports detected
|
|
437
|
+
${f.bold("\u{1F552} Last Sync")}: ${c?f.yellow(new Date(c).toLocaleString()):f.red("Never")}
|
|
438
|
+
${f.bold("\u2699\uFE0F Config")}: ${s?f.green("Custom Intelligence"):f.gray("Standard Sieve")}`,"blue"),a.length>0&&(console.log(""),console.log(` ${f.bold("Symbol Distribution (Top 5)")}`),Rn(a.map(l=>({label:l.kind,value:l.c,color:"cyan"})),30)),console.log(""),console.log(` ${f.dim("Pro-tip: Try")} ${f.bold(f.cyan("liquid-shadow dashboard"))} ${f.dim("for the full tactical view.")}`),console.log(""),Ee("Scouting complete.")})}finally{await J(e)}}z();qe();import ji from"path";var vs=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,s)=>n+s,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}},Ye=new vs;function Oi(){Ye.recordIndexStart()}function Ts(){Ye.recordIndexCacheHit()}function Fi(i){Ye.recordIndexEnd(i)}function Wt(i,e){Ye.recordIndexPhase(i,e)}function Wi(){Ye.clearIndexPhases()}function In(){return Ye.recordQueryStart()}function yt(){Ye.recordSearchHistoryFailure()}function Cn(){return Ye.getSnapshot()}W();import ue from"fs";import ot from"path";var bt=S.child({module:"git-hooks"}),Ln={"post-merge":`#!/bin/sh
|
|
429
439
|
# Liquid Shadow: Auto-refresh index after merge/pull
|
|
430
440
|
# Generated by liquid-shadow
|
|
431
441
|
|
|
@@ -459,22 +469,30 @@ REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
|
459
469
|
nohup npx @precisionutilityguild/liquid-shadow sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
460
470
|
|
|
461
471
|
exit 0
|
|
462
|
-
`};function
|
|
463
|
-
${
|
|
464
|
-
${
|
|
465
|
-
${
|
|
466
|
-
${
|
|
467
|
-
${
|
|
468
|
-
${
|
|
469
|
-
${
|
|
470
|
-
${
|
|
471
|
-
${
|
|
472
|
-
${
|
|
473
|
-
${
|
|
474
|
-
${
|
|
475
|
-
${
|
|
476
|
-
|
|
477
|
-
`)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function En(i,e,t){let n=i.toLowerCase(),s=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||s.startsWith("use")?"Hook":n.includes("models/")||s.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")||s.endsWith("service")||s.endsWith("controller")||s.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||s.endsWith("repository")||s.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function It(i){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(i)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(i)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(i)||/\.query\s*\(|\.execute\s*\(/i.test(i)&&/db|database|client|pool/i.test(i))&&e.push("Database"),(/\bfs\./i.test(i)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(i)||/import\s+.*\bfs\b/.test(i))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(i)||/\bdocument\.cookie\b/.test(i))&&e.push("Browser Storage"),e}function xe(i,e){if(!i)return"";let t=i.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,s=0,r=t.length;for(let o=0;o<t.length;o++){let c=t[o];if(c==="(")n++;else if(c===")")n--;else if(c==="<")s++;else if(c===">")s--;else if(c==="{"){if(n===0&&s===0){r=o;break}}else if(c==="; "&&n===0&&s===0){r=o;break}else if(c==="="&&t[o+1]===">"&&n===0&&s===0){r=o+2;break}}return t.substring(0,r).trim()}function Ai(i){let e=[];for(let t of i)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 Mi(i,e,t,n,s,r,o,c){let a=[];for(let l of i){if(l.type==="ExportDeclaration"){let p=l.declaration,d=p.type,u="";d==="VariableDeclaration"?u=p.declarations.map(g=>g.id.value).join("",""):u=p.id?.value||p.identifier?.value||"anonymous";let m=Y(l.span.start-e,t),f=Y(l.span.end-e,t),h=_e(m,r,n),b=c(l.span),y=[];if(l.type==="ExportDeclaration"&&(d==="ClassDeclaration"||d==="ClassExpression")){let g=p.body||[];for(let S of g)if(S.type==="ClassMethod"||S.type==="ClassProperty"){let R=S.key.value;if(!R)continue;let w=Y(S.span.start-e,t),T=Y(S.span.end-e,t),v=c(S.span),k=_e(w,r,n);y.push({name:R,kind:S.type,signature:xe(v,S.type),line:J(w,s),endLine:J(T,s),doc:k,classification:S.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(d==="FunctionDeclaration"&&p.body?.type==="BlockStatement")y=ms(p.body.stmts,e,t,n,s,r,c);else if(d==="VariableDeclaration"){for(let g of p.declarations)if(g.init&&(g.init.type==="ArrowFunctionExpression"||g.init.type==="FunctionExpression")&&g.init.body?.type==="BlockStatement"){y=ms(g.init.body.stmts,e,t,n,s,r,c);break}}a.push({name:u,kind:d,signature:xe(b,d),line:J(m,s),endLine:J(f,s),doc:h,classification:En(o,u,d),capabilities:JSON.stringify(It(b)),members:y})}if(l.type==="ExportNamedDeclaration"){for(let p of l.specifiers)if(p.type==="ExportSpecifier"){let d=Y(l.span.start-e,t),u=Y(l.span.end-e,t),m=_e(d,r,n);a.push({name:p.exported?.value||p.orig.value,kind:"ExportSpecifier",signature:`export { ${p.orig.value} }`,line:J(d,s),endLine:J(u,s),doc:m,classification:"Export mapping",capabilities:"[]"})}}if(l.type==="ExportDefaultDeclaration"){let p=Y(l.span.start-e,t),d=Y(l.span.end-e,t),u=_e(p,r,n),m=c(l.span),f=[];if(l.decl.type==="ClassExpression"||l.decl.type==="ClassDeclaration"){let h=l.decl.body||[];for(let b of h)if(b.type==="ClassMethod"||b.type==="ClassProperty"){let y=b.key.value;if(!y)continue;let g=Y(b.span.start-e,t),S=Y(b.span.end-e,t),R=c(b.span),w=_e(g,r,n);f.push({name:y,kind:b.type,signature:xe(R,b.type),line:J(g,s),endLine:J(S,s),doc:w,classification:b.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(l.decl.type==="FunctionExpression"||l.decl.type==="FunctionDeclaration"||l.decl.type==="ArrowFunctionExpression")&&l.decl.body?.type==="BlockStatement"&&(f=ms(l.decl.body.stmts,e,t,n,s,r,c));a.push({name:"default",kind:"DefaultExport",signature:xe(m,"DefaultExport"),line:J(p,s),endLine:J(d,s),doc:u,classification:"Default Export",capabilities:JSON.stringify(It(m)),members:f})}if(l.type==="ExportAllDeclaration"){let p=Y(l.span.start-e,t),d=Y(l.span.end-e,t),u=l.source.value,m=_e(p,r,n);a.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${u}"`,line:J(p,s),endLine:J(d,s),doc:m,classification:"Re-export",capabilities:"[]"})}}return a}function ms(i,e,t,n,s,r,o){let c=[];for(let a of i){if(a.type==="VariableDeclaration")for(let l of a.declarations){let p=[],d=u=>{if(u.type==="Identifier")p.push({name:u.value,span:u.span});else if(u.type==="ArrayPattern")for(let m of u.elements)m&&d(m);else if(u.type==="ObjectPattern")for(let m of u.properties)m.type==="AssignmentPatternProperty"?p.push({name:m.key.value,span:m.span}):m.type==="KeyValuePatternProperty"&&d(m.value)};d(l.id);for(let u of p){let m=Y(u.span.start-e,t),f=Y(u.span.end-e,t),h=o(u.span),b=_e(m,r,n);c.push({name:u.name,kind:"VariableDeclaration",signature:xe(h,"VariableDeclaration"),line:J(m,s),endLine:J(f,s),doc:b,classification:"Internal Variable",capabilities:"[]"})}}if(a.type==="FunctionDeclaration"){let l=a.identifier?.value||a.ident?.value||"anonymous",p=Y(a.span.start-e,t),d=Y(a.span.end-e,t),u=o(a.span),m=_e(p,r,n);c.push({name:l,kind:"FunctionDeclaration",signature:xe(u,"FunctionDeclaration"),line:J(p,s),endLine:J(d,s),doc:m,classification:"Internal Function",capabilities:"[]"})}if(a.type==="ReturnStatement"&&a.argument?.type==="ObjectExpression")for(let l of a.argument.properties){let p="",d=l.span||l.key?.span||l.ident?.span;if(l.type==="KeyValueProperty"){let u=l.key;p=u?.value||u?.raw||(u?.type==="Identifier"?u.value:"")}else l.type==="MethodProperty"?p=l.key?.value||l.key?.raw||"":l.type==="ShorthandProperty"?p=l.ident?.value||"":l.type==="Identifier"&&(p=l.value||"");if(p&&d){let u=Y(d.start-e,t),m=Y(d.end-e,t),f=o(d),h=_e(u,r,n);c.push({name:p,kind:"ReturnProperty",signature:xe(f,"ReturnProperty"),line:J(u,s),endLine:J(m,s),doc:h,classification:"Return Member",capabilities:"[]"})}}if(a.type==="ExpressionStatement"&&a.expression.type==="CallExpression"){let l=a.expression;if(l.callee.type==="MemberExpression"&&(l.callee.property?.value==="on"||l.callee.property?.value==="once")){let p=l.arguments[0]?.expression?.value,d=l.arguments[1]?.expression;if(p&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let u=Y(d.span.start-e,t),m=Y(d.span.end-e,t),f=o(d.span);c.push({name:`on:${p}`,kind:d.type,signature:xe(f,d.type),line:J(u,s),endLine:J(m,s),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(l.callee.type==="Identifier"&&l.callee.value==="addRoute"&&l.arguments.length>=3){let p=l.arguments[2].expression;if(p.type==="StringLiteral"){let d=p.value,u=Y(l.span.start-e,t),m=Y(l.span.end-e,t),f=o(l.span);c.push({name:d,kind:"HTTP Route",signature:xe(f,"HTTP Route"),line:J(u,s),endLine:J(m,s),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:d})})}}}}return c}function Pi(i,e,t,n,s){let r=[];function o(c){if(!(!c||typeof c!="object")){if(c.type==="CallExpression"){let a=Aa(c);if(a){let l=Y(c.span.start-e,t);r.push({...a,line:J(l,n),snippet:s(c.span)})}}for(let a of Object.keys(c)){if(a==="span")continue;let l=c[a];Array.isArray(l)?l.forEach(o):typeof l=="object"&&o(l)}}}return i.forEach(o),r}function Aa(i){let{callee:e,arguments:t}=i;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 Ct(i){let{classification:e,capabilities:t,exports:n,fileName:s}=i,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(f=>r[f]).filter(Boolean).join(" and "),a={Component:(f,h)=>{let b=h.find(g=>g.kind==="FunctionDeclaration"||g.kind==="ClassDeclaration")?.name,y=b?`React component: ${b}`:"React UI component";return f?`${y} with ${f}`:y},Hook:(f,h)=>{let b=h.find(g=>g.name.startsWith("use"))?.name,y=b?`Custom React hook: ${b}`:"Custom React hook";return f?`${y} for ${f}`:y},Service:(f,h)=>{let y=`Service layer: ${h[0]?.name||"Service"}`;return f?`${y} handling ${f}`:y},Repository:(f,h)=>`Data repository: ${h[0]?.name||"Repository"} for ${f||"data access"}`,"Type Definition":(f,h)=>`Type definitions: ${h.slice(0,3).map(y=>y.name).join("")}${h.length>3?"...":""}`,Model:(f,h)=>`Data model: ${h[0]?.name||"Model"}`,"HTTP Route":(f,h)=>{let b=h.filter(y=>y.classification==="Service Boundary");return b.length>0?`API endpoints: ${b.slice(0,3).map(y=>y.name).join("")}`:"API route handler"},"Micro IR (PHP)":(f,h)=>{let b=h.some(g=>g.classification==="Service Boundary"),y=h.find(g=>g.kind==="ClassDeclaration")?.name;return b?"PHP controller with API routes":y?`PHP class: ${y}`:"PHP module"},"Micro IR (Python)":(f,h)=>{let b=h.some(g=>g.classification==="Service Boundary"),y=h.find(g=>g.kind==="ClassDeclaration")?.name;return b?"Python API handler with routes":y?`Python class: ${y}`:"Python module"},"Micro IR (Go/TS) ":(f,h)=>{let b=h.some(g=>g.kind==="TypeDeclaration"),y=h.filter(g=>g.kind==="FunctionDeclaration");return b&&y.length>0?`Go package: types and ${y.length} function(s)`:b?"Go package: type definitions":y.length>0?`Go package: ${y[0].name} and ${y.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(f,h)=>{let b=h.find(S=>S.kind==="TraitDeclaration")?.name,y=h.find(S=>S.kind==="StructDeclaration")?.name,g=h.filter(S=>S.kind==="FunctionDeclaration");return b?f.includes("Rust trait")?`Rust module: trait ${b}`:`Rust module: ${b}`:y?`Rust module: struct ${y}`:g.length>0?`Rust module: ${g.length} function(s)`:"Rust module"}}[e];if(a)return a(o,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let l=n.filter(f=>f.kind==="FunctionDeclaration"),p=n.filter(f=>f.kind==="ClassDeclaration"),d=n.filter(f=>f.kind==="TsInterfaceDeclaration"||f.kind==="TsTypeAliasDeclaration"),u=[];if(p.length>0&&u.push(`Class: ${p[0].name}`),l.length>0){let f=l.slice(0,2).map(h=>h.name).join("");u.push(`Functions: ${f}`)}d.length>0&&u.push(`Types: ${d.length}`);let m=u.length>0?u.join(" | "):`Module with ${n.length} export(s)`;return o?`${m} \u2014 ${o}`:m}function Di(i){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&K(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&K(n,e);for(let s in n){if(s==="span"||s==="comments"||s==="interpreter")continue;let r=n[s];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return i.forEach(n=>t(n)),Array.from(e)}function K(i,e){if(i){if(i.type==="TsTypeAnnotation"){K(i.typeAnnotation,e);return}i.type==="TsTypeReference"&&(i.typeName?.type==="Identifier"&&e.add(i.typeName.value),i.typeName?.type==="TsQualifiedName"&&Oi(i.typeName,e),i.typeParams&&K(i.typeParams,e)),i.type==="TsArrayType"&&K(i.elementType,e),i.type==="TsUnionType"&&i.types?.forEach(t=>K(t,e)),i.type==="TsIntersectionType"&&i.types?.forEach(t=>K(t,e)),i.type==="TsTupleType"&&i.elemTypes?.forEach(t=>K(t.ty,e)),(i.type==="TsFunctionType"||i.type==="TsConstructorType")&&(i.params?.forEach(t=>K(t.typeAnnotation,e)),i.typeAnnotation&&K(i.typeAnnotation,e)),i.type==="TsTypeParameterDeclaration"&&i.params?.forEach(t=>{t.constraint&&K(t.constraint,e),t.default&&K(t.default,e)}),i.type==="TsTypeParameterInstantiation"&&i.params?.forEach(t=>K(t,e)),i.type==="TsMappedType"&&i.typeAnnotation&&K(i.typeAnnotation,e),i.type==="TsIndexedAccessType"&&(K(i.objectType,e),K(i.indexType,e)),i.type==="TsConditionalType"&&(K(i.checkType,e),K(i.extendsType,e),K(i.trueType,e),K(i.falseType,e)),i.type==="TsTypeLiteral"&&i.members?.forEach(t=>{t.typeAnnotation&&K(t.typeAnnotation,e)})}}function Oi(i,e){i.type==="TsQualifiedName"?(i.left&&Oi(i.left,e),i.right?.value&&e.add(i.right.value)):i.type==="Identifier"&&e.add(i.value)}import ji from"path";import hs from"path";P();import Hi from"path";import Ma from"fs";import{fileURLToPath as Pa}from"url";import*as Xe from"web-tree-sitter";var ku=Hi.dirname(Pa(import.meta.url)),Fi=_.child({module:"parser:tree-sitter"}),Sn=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=Xe.Parser||Xe;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=ln("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!Ma.existsSync(t))return Fi.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await Xe.Language.load(t);return this.languages.set(e,n),n}catch(n){return Fi.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`
|
|
472
|
+
`};function Hi(i){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=i,s=ot.join(e,".git","hooks"),r=[],o=[],c=[];if(!ue.existsSync(ot.join(e,".git")))return c.push("Not a git repository"),{installed:r,skipped:o,errors:c};ue.existsSync(s)||ue.mkdirSync(s,{recursive:!0});let a=[];t&&a.push("post-merge","post-checkout"),n&&a.push("post-commit");for(let l of a){let p=ot.join(s,l),u=Ln[l];if(!u){c.push(`No template found for hook: ${l}`);continue}try{if(ue.existsSync(p)){let d=ue.readFileSync(p,"utf-8");if(d.includes("liquid-shadow")||d.includes("mcp-liquid-shadow")){o.push(l),bt.info({hookName:l},"Hook already installed, skipping");continue}let m=`${p}.backup-${Date.now()}`;ue.copyFileSync(p,m),bt.info({hookName:l,backupPath:m},"Backed up existing hook")}ue.writeFileSync(p,u,{mode:493}),r.push(l),bt.info({hookName:l},"Installed git hook")}catch(d){c.push(`Failed to install ${l}: ${d}`),bt.error({hookName:l,err:d},"Failed to install hook")}}return{installed:r,skipped:o,errors:c}}function Ui(i){let e=ot.join(i,".git","hooks"),t=[],n=[];if(!ue.existsSync(e))return{removed:t,errors:n};let s=Object.keys(Ln);for(let r of s){let o=ot.join(e,r);try{if(ue.existsSync(o)){let c=ue.readFileSync(o,"utf-8");(c.includes("liquid-shadow")||c.includes("mcp-liquid-shadow"))&&(ue.unlinkSync(o),t.push(r),bt.info({hookName:r},"Removed git hook"))}}catch(c){n.push(`Failed to remove ${r}: ${c}`),bt.error({hookName:r,err:c},"Failed to remove hook")}}return{removed:t,errors:n}}function _t(i){let e=ot.join(i,".git","hooks"),t=[],n=[];if(!ue.existsSync(e))return{installed:t,notInstalled:Object.keys(Ln)};let s=Object.keys(Ln);for(let r of s){let o=ot.join(e,r);if(ue.existsSync(o)){let c=ue.readFileSync(o,"utf-8");c.includes("liquid-shadow")||c.includes("mcp-liquid-shadow")?t.push(r):n.push(r)}else n.push(r)}return{installed:t,notInstalled:n}}async function Rs(i){let e=ji.resolve(i);try{await B(async()=>{se("Liquid Shadow Intelligence Dashboard");let t=C.getInstance(e),n=Cn(),s=_t(e),r=t.files.getCount(),o=t.exports.getCount(),c=t.files.getLatestScanTime(),a=t.exports.getKindDistribution(5);if(X("Operational Core",`${f.bold("State")}: ${He(e)?f.green("IDENTIFIED (Stable)"):f.red("UNKNOWN (Needs Index)")}
|
|
473
|
+
${f.bold("Repository")}: ${f.cyan(ji.basename(e))}
|
|
474
|
+
${f.bold("Infrastructure")}: ${s.installed?f.green("Git-Hooked"):f.yellow("Standalone")}
|
|
475
|
+
${f.bold("Last Sync")}: ${c?f.yellow(new Date(c).toLocaleString()):f.red("Never")}`,"blue"),console.log(""),X("Intelligence Density",`${f.bold("Files Target")}: ${f.cyan(r.toString())}
|
|
476
|
+
${f.bold("Symbols Mapped")}: ${f.cyan(o.toString())}
|
|
477
|
+
${f.bold("Graph Edges")}: ${f.cyan(t.imports.getCount().toString())}
|
|
478
|
+
${f.bold("Hotspots")}: ${f.yellow(a.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";X("Reasoning Efficiency",`${f.bold("Query Count")}: ${f.cyan(n.query.count.toString())}
|
|
479
|
+
${f.bold("Avg Latency")}: ${f.yellow(`${n.query.avgLatencyMs?.toFixed(2)||0}ms`)}
|
|
480
|
+
${f.bold("Cache Hit Rate")}: ${f.green(`${l}%`)}`,"green")}a.length>0&&(console.log(""),console.log(` ${f.bold("Intelligence Landscape")}`),Rn(a.map(l=>({label:l.kind,value:l.c,color:"cyan"})),35)),console.log(""),Ee("Liquid Shadow is observing.")})}finally{await J(e)}}z();qe();import Ka from"path";async function zi(i){let e=Ka.resolve(i);try{await B(async()=>{let t=C.getInstance(e),n=_t(e),s=Cn(),r=Math.floor(s.uptimeMs/1e3),o=Math.floor(r/60),c=Math.floor(o/60),a=c>0?`${c}h ${o%60}m`:o>0?`${o}m ${r%60}s`:`${r}s`,l=s.index.lastCompletedAt?new Date(s.index.lastCompletedAt).toLocaleString():"Never",p=s.index.lastDurationMs?`${(s.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",u=s.query.avgLatencyMs?`${s.query.avgLatencyMs.toFixed(2)}ms`:"N/A",d=s.query.lastLatencyMs?`${s.query.lastLatencyMs.toFixed(2)}ms`:"N/A",m=s.index.runs>0?(s.index.cacheHits/s.index.runs*100).toFixed(1):"0.0";X("Performance Metrics",`${f.bold("Uptime")}: ${f.cyan(a)}
|
|
481
|
+
${f.bold("Indexed")}: ${He(e)?f.green("Yes"):f.red("No")}
|
|
482
|
+
${f.bold("Files")}: ${f.cyan(t.files.getCount().toString())}
|
|
483
|
+
${f.bold("Exports")}: ${f.cyan(t.exports.getCount().toString())}
|
|
484
|
+
${f.bold("Imports")}: ${f.cyan(t.imports.getCount().toString())}
|
|
485
|
+
${f.bold("Last Indexed Commit")}: ${Pt(e)?f.yellow(Pt(e).substring(0,7)):f.red("None")}
|
|
486
|
+
${f.bold("Git Hooks")}: ${n.installed?f.green("Installed"):f.yellow("Not Installed")}`,"blue"),console.log(""),X("Index Metrics",`${f.bold("Total Runs")}: ${f.cyan(s.index.runs.toString())}
|
|
487
|
+
${f.bold("Cache Hits")}: ${f.cyan(s.index.cacheHits.toString())}
|
|
488
|
+
${f.bold("Cache Hit Rate")}: ${f.cyan(`${m}%`)}
|
|
489
|
+
${f.bold("Last Duration")}: ${f.yellow(p)}
|
|
490
|
+
${f.bold("Last Completed")}: ${f.yellow(l)}`,"cyan"),s.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${f.bold("Last Index Run Phases:")}`),s.index.lastRunPhases.forEach(h=>{let g=`${(h.durationMs/1e3).toFixed(2)}s`;console.log(` ${f.gray(h.phase.padEnd(20))} ${f.cyan(g)}`)})),console.log(""),X("Query Metrics",`${f.bold("Total Queries")}: ${f.cyan(s.query.count.toString())}
|
|
491
|
+
${f.bold("Avg Latency")}: ${f.yellow(u)}
|
|
492
|
+
${f.bold("Last Latency")}: ${f.yellow(d)}
|
|
493
|
+
${f.bold("Search History Failures")}: ${s.query.searchHistoryFailures>0?f.red(s.query.searchHistoryFailures.toString()):f.green("0")}`,"green")})}finally{await J(e)}}import Oc from"path";import Xa from"fast-glob";import Gi from"fs";import Za from"ignore";import qi from"path";var $n=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],Bi=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],Et={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},me={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},ks={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},Nn={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function Is(i,e=[]){let t=Za(),n=qi.join(i,".gitignore");return Gi.existsSync(n)&&t.add(Gi.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await Xa(Bi,{cwd:i,absolute:!0,ignore:$n,stats:!0})).filter(o=>{let c=qi.relative(i,o.path);return!t.ignores(c)}).map(o=>({path:o.path,mtime:o.stats.mtimeMs}))}import $s from"@swc/core";import or from"fs";function Ji(i){let e=i.split(`
|
|
494
|
+
`),t=[],n=0;for(let s of e)t.push(n),n+=s.length+1;return t}function V(i,e){for(let t=0;t<e.length;t++)if(e[t+1]>i||t===e.length-1)return t+1;return 1}function An(i,e){return e.slice(0,i).toString("utf8").length}function Yi(i){if(i.toString("utf8").length===i.length)return n=>n;let t=new Map;return n=>{let s=t.get(n);return s===void 0&&(s=i.slice(0,n).toString("utf8").length,t.set(n,s)),s}}function Vi(i,e,t){let n=i.start-e,s=i.end-e;return n<0||s>t.length?"":t.slice(n,s).toString("utf8")}function Qi(i){let e=[],t=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=t.exec(i))!==null;)e.push({start:n.index,end:n.index+n[0].length,text:n[0]});return e}function Ne(i,e,t){for(let n of e){if(n.start===i)return n.text;if(n.start>i&&n.start<i+50){let s=t.substring(i,n.start);if(/^\s*$/.test(s))return n.text}if(n.end<=i&&n.end>i-50){let s=t.substring(n.end,i);if(/^\s*$/.test(s))return n.text}}return""}function Ki(i){if(!i)return"";let t=i.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
|
|
495
|
+
`)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function Pn(i,e,t){let n=i.toLowerCase(),s=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||s.startsWith("use")?"Hook":n.includes("models/")||s.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")||s.endsWith("service")||s.endsWith("controller")||s.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||s.endsWith("repository")||s.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function Ht(i){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(i)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(i)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(i)||/\.query\s*\(|\.execute\s*\(/i.test(i)&&/db|database|client|pool/i.test(i))&&e.push("Database"),(/\bfs\./i.test(i)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(i)||/import\s+.*\bfs\b/.test(i))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(i)||/\bdocument\.cookie\b/.test(i))&&e.push("Browser Storage"),e}function Ae(i,e){if(!i)return"";let t=i.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,s=0,r=t.length;for(let o=0;o<t.length;o++){let c=t[o];if(c==="(")n++;else if(c===")")n--;else if(c==="<")s++;else if(c===">")s--;else if(c==="{"){if(n===0&&s===0){r=o;break}}else if(c==="; "&&n===0&&s===0){r=o;break}else if(c==="="&&t[o+1]===">"&&n===0&&s===0){r=o+2;break}}return t.substring(0,r).trim()}function Xi(i){let e=[];for(let t of i)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 Zi(i,e,t,n,s,r,o,c,a){let l=a??(u=>An(u,t)),p=[];for(let u of i){if(u.type==="ExportDeclaration"){let d=u.declaration,m=d.type,h="";m==="VariableDeclaration"?h=d.declarations.map(w=>w.id.value).join("",""):h=d.id?.value||d.identifier?.value||"anonymous";let g=l(u.span.start-e),_=l(u.span.end-e),b=Ne(g,r,n),y=c(u.span),E=[];if(u.type==="ExportDeclaration"&&(m==="ClassDeclaration"||m==="ClassExpression")){let w=d.body||[];for(let x of w)if(x.type==="ClassMethod"||x.type==="ClassProperty"){let v=x.key.value;if(!v)continue;let k=l(x.span.start-e),N=l(x.span.end-e),O=c(x.span),T=Ne(k,r,n);E.push({name:v,kind:x.type,signature:Ae(O,x.type),line:V(k,s),endLine:V(N,s),doc:T,classification:x.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(m==="FunctionDeclaration"&&d.body?.type==="BlockStatement")E=Cs(d.body.stmts,e,t,n,s,r,c,l);else if(m==="VariableDeclaration"){for(let w of d.declarations)if(w.init&&(w.init.type==="ArrowFunctionExpression"||w.init.type==="FunctionExpression")&&w.init.body?.type==="BlockStatement"){E=Cs(w.init.body.stmts,e,t,n,s,r,c,l);break}}p.push({name:h,kind:m,signature:Ae(y,m),line:V(g,s),endLine:V(_,s),doc:b,classification:Pn(o,h,m),capabilities:JSON.stringify(Ht(y)),members:E})}if(u.type==="ExportNamedDeclaration"){for(let d of u.specifiers)if(d.type==="ExportSpecifier"){let m=l(u.span.start-e),h=l(u.span.end-e),g=Ne(m,r,n);p.push({name:d.exported?.value||d.orig.value,kind:"ExportSpecifier",signature:`export { ${d.orig.value} }`,line:V(m,s),endLine:V(h,s),doc:g,classification:"Export mapping",capabilities:"[]"})}}if(u.type==="ExportDefaultDeclaration"){let d=l(u.span.start-e),m=l(u.span.end-e),h=Ne(d,r,n),g=c(u.span),_=[];if(u.decl.type==="ClassExpression"||u.decl.type==="ClassDeclaration"){let b=u.decl.body||[];for(let y of b)if(y.type==="ClassMethod"||y.type==="ClassProperty"){let E=y.key.value;if(!E)continue;let w=l(y.span.start-e),x=l(y.span.end-e),v=c(y.span),k=Ne(w,r,n);_.push({name:E,kind:y.type,signature:Ae(v,y.type),line:V(w,s),endLine:V(x,s),doc:k,classification:y.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(u.decl.type==="FunctionExpression"||u.decl.type==="FunctionDeclaration"||u.decl.type==="ArrowFunctionExpression")&&u.decl.body?.type==="BlockStatement"&&(_=Cs(u.decl.body.stmts,e,t,n,s,r,c,l));p.push({name:"default",kind:"DefaultExport",signature:Ae(g,"DefaultExport"),line:V(d,s),endLine:V(m,s),doc:h,classification:"Default Export",capabilities:JSON.stringify(Ht(g)),members:_})}if(u.type==="ExportAllDeclaration"){let d=l(u.span.start-e),m=l(u.span.end-e),h=u.source.value,g=Ne(d,r,n);p.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${h}"`,line:V(d,s),endLine:V(m,s),doc:g,classification:"Re-export",capabilities:"[]"})}}return p}function Cs(i,e,t,n,s,r,o,c){let a=[];for(let l of i){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 h of m.elements)h&&d(h);else if(m.type==="ObjectPattern")for(let h of m.properties)h.type==="AssignmentPatternProperty"?u.push({name:h.key.value,span:h.span}):h.type==="KeyValuePatternProperty"&&d(h.value)};d(p.id);for(let m of u){let h=c(m.span.start-e),g=c(m.span.end-e),_=o(m.span),b=Ne(h,r,n);a.push({name:m.name,kind:"VariableDeclaration",signature:Ae(_,"VariableDeclaration"),line:V(h,s),endLine:V(g,s),doc:b,classification:"Internal Variable",capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let p=l.identifier?.value||l.ident?.value||"anonymous",u=c(l.span.start-e),d=c(l.span.end-e),m=o(l.span),h=Ne(u,r,n);a.push({name:p,kind:"FunctionDeclaration",signature:Ae(m,"FunctionDeclaration"),line:V(u,s),endLine:V(d,s),doc:h,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 m=p.key;u=m?.value||m?.raw||(m?.type==="Identifier"?m.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 m=c(d.start-e),h=c(d.end-e),g=o(d),_=Ne(m,r,n);a.push({name:u,kind:"ReturnProperty",signature:Ae(g,"ReturnProperty"),line:V(m,s),endLine:V(h,s),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 m=c(d.span.start-e),h=c(d.span.end-e),g=o(d.span);a.push({name:`on:${u}`,kind:d.type,signature:Ae(g,d.type),line:V(m,s),endLine:V(h,s),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,m=c(p.span.start-e),h=c(p.span.end-e),g=o(p.span);a.push({name:d,kind:"HTTP Route",signature:Ae(g,"HTTP Route"),line:V(m,s),endLine:V(h,s),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:d})})}}}}return a}function er(i,e,t,n,s,r){let o=r??(l=>An(l,t)),c=[];function a(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let p=ec(l);if(p){let u=o(l.span.start-e);c.push({...p,line:V(u,n),snippet:s(l.span)})}}for(let p of Object.keys(l)){if(p==="span")continue;let u=l[p];Array.isArray(u)?u.forEach(a):typeof u=="object"&&a(u)}}}return i.forEach(a),c}function ec(i){let{callee:e,arguments:t}=i;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 Ut(i){let{classification:e,capabilities:t,exports:n,fileName:s}=i,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(h=>r[h]).filter(Boolean).join(" and "),a={Component:(h,g)=>{let _=g.find(y=>y.kind==="FunctionDeclaration"||y.kind==="ClassDeclaration")?.name,b=_?`React component: ${_}`:"React UI component";return h?`${b} with ${h}`:b},Hook:(h,g)=>{let _=g.find(y=>y.name.startsWith("use"))?.name,b=_?`Custom React hook: ${_}`:"Custom React hook";return h?`${b} for ${h}`:b},Service:(h,g)=>{let b=`Service layer: ${g[0]?.name||"Service"}`;return h?`${b} handling ${h}`:b},Repository:(h,g)=>`Data repository: ${g[0]?.name||"Repository"} for ${h||"data access"}`,"Type Definition":(h,g)=>`Type definitions: ${g.slice(0,3).map(b=>b.name).join("")}${g.length>3?"...":""}`,Model:(h,g)=>`Data model: ${g[0]?.name||"Model"}`,"HTTP Route":(h,g)=>{let _=g.filter(b=>b.classification==="Service Boundary");return _.length>0?`API endpoints: ${_.slice(0,3).map(b=>b.name).join("")}`:"API route handler"},"Micro IR (PHP)":(h,g)=>{let _=g.some(y=>y.classification==="Service Boundary"),b=g.find(y=>y.kind==="ClassDeclaration")?.name;return _?"PHP controller with API routes":b?`PHP class: ${b}`:"PHP module"},"Micro IR (Python)":(h,g)=>{let _=g.some(y=>y.classification==="Service Boundary"),b=g.find(y=>y.kind==="ClassDeclaration")?.name;return _?"Python API handler with routes":b?`Python class: ${b}`:"Python module"},"Micro IR (Go/TS) ":(h,g)=>{let _=g.some(y=>y.kind==="TypeDeclaration"),b=g.filter(y=>y.kind==="FunctionDeclaration");return _&&b.length>0?`Go package: types and ${b.length} function(s)`:_?"Go package: type definitions":b.length>0?`Go package: ${b[0].name} and ${b.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(h,g)=>{let _=g.find(E=>E.kind==="TraitDeclaration")?.name,b=g.find(E=>E.kind==="StructDeclaration")?.name,y=g.filter(E=>E.kind==="FunctionDeclaration");return _?h.includes("Rust trait")?`Rust module: trait ${_}`:`Rust module: ${_}`:b?`Rust module: struct ${b}`:y.length>0?`Rust module: ${y.length} function(s)`:"Rust module"}}[e];if(a)return a(o,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let l=n.filter(h=>h.kind==="FunctionDeclaration"),p=n.filter(h=>h.kind==="ClassDeclaration"),u=n.filter(h=>h.kind==="TsInterfaceDeclaration"||h.kind==="TsTypeAliasDeclaration"),d=[];if(p.length>0&&d.push(`Class: ${p[0].name}`),l.length>0){let h=l.slice(0,2).map(g=>g.name).join("");d.push(`Functions: ${h}`)}u.length>0&&d.push(`Types: ${u.length}`);let m=d.length>0?d.join(" | "):`Module with ${n.length} export(s)`;return o?`${m} \u2014 ${o}`:m}function tr(i){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&ee(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&ee(n,e);for(let s in n){if(s==="span"||s==="comments"||s==="interpreter")continue;let r=n[s];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return i.forEach(n=>t(n)),Array.from(e)}function ee(i,e){if(i){if(i.type==="TsTypeAnnotation"){ee(i.typeAnnotation,e);return}i.type==="TsTypeReference"&&(i.typeName?.type==="Identifier"&&e.add(i.typeName.value),i.typeName?.type==="TsQualifiedName"&&nr(i.typeName,e),i.typeParams&&ee(i.typeParams,e)),i.type==="TsArrayType"&&ee(i.elementType,e),i.type==="TsUnionType"&&i.types?.forEach(t=>ee(t,e)),i.type==="TsIntersectionType"&&i.types?.forEach(t=>ee(t,e)),i.type==="TsTupleType"&&i.elemTypes?.forEach(t=>ee(t.ty,e)),(i.type==="TsFunctionType"||i.type==="TsConstructorType")&&(i.params?.forEach(t=>ee(t.typeAnnotation,e)),i.typeAnnotation&&ee(i.typeAnnotation,e)),i.type==="TsTypeParameterDeclaration"&&i.params?.forEach(t=>{t.constraint&&ee(t.constraint,e),t.default&&ee(t.default,e)}),i.type==="TsTypeParameterInstantiation"&&i.params?.forEach(t=>ee(t,e)),i.type==="TsMappedType"&&i.typeAnnotation&&ee(i.typeAnnotation,e),i.type==="TsIndexedAccessType"&&(ee(i.objectType,e),ee(i.indexType,e)),i.type==="TsConditionalType"&&(ee(i.checkType,e),ee(i.extendsType,e),ee(i.trueType,e),ee(i.falseType,e)),i.type==="TsTypeLiteral"&&i.members?.forEach(t=>{t.typeAnnotation&&ee(t.typeAnnotation,e)})}}function nr(i,e){i.type==="TsQualifiedName"?(i.left&&nr(i.left,e),i.right?.value&&e.add(i.right.value)):i.type==="Identifier"&&e.add(i.value)}import ar from"path";import Ls from"path";W();hn();import ir from"path";import tc from"fs";import{fileURLToPath as nc}from"url";import*as at from"web-tree-sitter";var wu=ir.dirname(nc(import.meta.url)),sr=S.child({module:"parser:tree-sitter"}),Mn=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=at.Parser||at;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=ht("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!tc.existsSync(t))return sr.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await at.Language.load(t);return this.languages.set(e,n),n}catch(n){return sr.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`
|
|
478
496
|
(function_definition name: (name) @name) @func
|
|
479
497
|
(class_declaration name: (name) @name) @class
|
|
480
498
|
(interface_declaration name: (name) @name) @interface
|
|
@@ -498,191 +516,201 @@ ${E.bold("Search History Failures")}: ${s.query.searchHistoryFailures>0?E.red(s.
|
|
|
498
516
|
(trait_item name: (_type_identifier) @name) @trait
|
|
499
517
|
(type_item name: (_type_identifier) @name) @type
|
|
500
518
|
(use_declaration argument: (_) @name) @import
|
|
501
|
-
`;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=
|
|
502
|
-
`),c=this.getQueries(n);if(!c)return[];let l=new
|
|
503
|
-
`),o="",c="",a=0,l=0,p=-1,
|
|
504
|
-
`).trim(),capabilities:JSON.stringify(
|
|
505
|
-
`).trim(),capabilities:JSON.stringify({attributes:
|
|
506
|
-
`).trim(),capabilities:JSON.stringify({attributes:
|
|
507
|
-
`).trim();if(
|
|
508
|
-
`),r=[{indent:-1,name:"root",type:"root"}],o=[],c=/^class\s+([a-zA-Z0-9_]+)/,a=/^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
|
|
509
|
-
`).trim()),
|
|
510
|
-
`).length;s.push({name:p.name||"anonymous",kind:p.kind||"Unknown",classification:p.classification||"Other",signature:p.signature||l[0],line:
|
|
511
|
-
`);for(let n of t){let s=n.trim();if(s.startsWith("FROM "))e.push({key:"base_image",value:s.substring(5).trim(),kind:"Image"});else if(s.startsWith("EXPOSE "))e.push({key:"port",value:s.substring(7).trim(),kind:"Port"});else if(s.startsWith("ENV ")){let r=s.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],c=r.slice(1).join("= ").trim()||"undefined",a="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(a="Service"),e.push({key:o,value:c,kind:a})}}}}function
|
|
512
|
-
`);for(let n of t){let s=n.trim();if(s&&!s.startsWith("#")){let r=s.split("=");if(r[0]){let o=r[0].trim(),c=r.slice(1).join("=");c=c.trim().replace(/^['"](.*)['"]$/,"$1");let a="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(a="Service"),e.push({key:o,value:c,kind:a})}}}}function
|
|
513
|
-
`):[]}catch{return[]}}function
|
|
514
|
-
`).
|
|
515
|
-
|
|
516
|
-
`);let t=ar.now();try{await z(e,10,!0);let n=ar.now()-t,s=C.getInstance(e),r=s.files.getCount(),o=s.exports.getCount(),c=s.exports.getWithEmbeddingsCount();se("Benchmark Results",`${E.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
|
|
517
|
-
${
|
|
518
|
-
|
|
519
|
-
${
|
|
519
|
+
`;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=ir.extname(e).toLowerCase(),s=await this.getLanguage(n);if(!s||!this.parser)return[];this.parser.setLanguage(s);let r=this.parser.parse(t),o=t.split(`
|
|
520
|
+
`),c=this.getQueries(n);if(!c)return[];let l=new at.Query(s,c).matches(r.rootNode),p=[];for(let u of l){let d=u.captures.find(g=>g.name==="name")?.node,m=u.captures[0].node,h=u.captures[0].name;if(d){let g=m.startPosition.row+1,_=m.endPosition.row+1,b=o[m.startPosition.row].trim();p.push({name:d.text,kind:this.mapKind(h,n),classification:this.mapClassification(h),signature:b,line:g,endLine:_,doc:"",capabilities:"{}"})}}return p}};var Dn=class{parse(e,t=!1){let n=[],s=[],r=e.split(`
|
|
521
|
+
`),o="",c="",a=0,l=0,p=-1,u=-1,d=[],m=[],h=!1,g=t?"api":"",_="",b=/^namespace\s+([a-zA-Z0-9_\\]+);/,y=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,E=/^interface\s+([a-zA-Z0-9_]+)/,w=/^trait\s+([a-zA-Z0-9_]+)/,x=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,v=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,k=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,N=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,O=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let T=0;T<r.length;T++){let I=r[T].trim();if(!I)continue;let U=(I.match(/{/g)||[]).length,H=(I.match(/}/g)||[]).length,P=l;if(l+=U-H,c&&l<=u){let F=n.find(M=>M.name===c&&M.line===a);F&&(F.endLine=T+1),c="",u=-1}if(o&&l<=p){let F=n.find(M=>M.name===o&&(M.kind==="ClassDeclaration"||M.kind==="TraitDeclaration"||M.kind==="InterfaceDeclaration"));F&&(F.endLine=T+1),o="",p=-1}let R=I.match(O);if(R&&(g=R[1]),I.includes("});")&&(g=""),I.startsWith("/**")){h=!0,m=[];continue}if(h){I.endsWith("*/")?h=!1:m.push(I.replace(/^\*\s?/,""));continue}let A=I.match(k);if(A){d.push(A[1]);continue}let D=I.match(b);if(D){_=D[1]||"",d=[],m=[];continue}let $=I.match(y);if($){o=$[1],p=l-U;let F={attributes:d};_&&(F.namespace=_),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:T+1,endLine:T+1,doc:m.join(`
|
|
522
|
+
`).trim(),capabilities:JSON.stringify(F),members:[]}),d=[],m=[];continue}let L=I.match(E);if(L){let F=L[1];o=F,p=l-U,n.push({name:F,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${F}`,line:T+1,endLine:T+1,doc:m.join(`
|
|
523
|
+
`).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],m=[];continue}let Y=I.match(w);if(Y){let F=Y[1];o=F,p=l-U,n.push({name:F,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${F}`,line:T+1,endLine:T+1,doc:m.join(`
|
|
524
|
+
`).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],m=[];continue}let he=I.match(x);if(he){let F=he[1],M=!!o;c=F,a=T+1,u=l-U;let _e=!1,de={};for(let ie of d)ie.toLowerCase().includes("route")&&(_e=!0,de={type:"route",method:"GET",path:"/"});let Ce=m.join(`
|
|
525
|
+
`).trim();if(_e){let ie=de.path||"/";n.push({name:ie,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${F}`,line:T+1,endLine:T+1,doc:Ce,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${F}`:F,...de})}),s.push({type:"api_route",name:ie,direction:"consume",line:T+1,snippet:I})}n.push({name:F,kind:M?"MethodDeclaration":"FunctionDeclaration",classification:M?"Method":"Function",signature:`${M?o+":: ":""}${F}`,line:T+1,endLine:T+1,doc:Ce,capabilities:JSON.stringify({attributes:d})}),d=[],m=[];continue}let pe=I.match(v);if(pe){let F=pe[1]||"",M=pe[2]||F.split("\\").pop()||"";n.push({name:M,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${F}`,line:T+1,endLine:T+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:F})}),d=[],m=[];continue}let ae=I.match(N);if(ae){let F=ae[1].toUpperCase(),M=ae[2];if(I.includes("Route::")||I.includes("router->")||I.includes("action")||I.includes(",")&&!I.includes("view(")){if(g){let Be=g.startsWith("/")?g:`/${g}`,ds=M.startsWith("/")?M:`/${M}`;M=(Be+ds).replace(/\/+/g,"/")}let de=null,Ce=I.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(Ce)de=`${Ce[1]}@${Ce[2]}`;else if(I.includes("::class")){let Be=I.match(/([a-zA-Z0-9_]+)::class/);Be&&(de=Be[1])}let ie=I;!I.endsWith(");")&&T+1<r.length&&(ie+=" "+r[T+1].trim(),!ie.endsWith(");")&&T+2<r.length&&(ie+=" "+r[T+2].trim())),n.push({name:M,kind:"HTTP Route",classification:"Service Boundary",signature:ie,line:T+1,endLine:T+1,doc:"",capabilities:JSON.stringify({type:"route",method:F,path:M,handler:de})}),s.push({type:"api_route",name:M,direction:"consume",line:T+1,snippet:ie,method:F,url:M}),m=[];continue}}let ye=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,j=I.match(ye);if(j){let F=(j[1]||j[3]).toUpperCase(),M=(j[2]||j[4]).trim();(M.startsWith("'")&&M.endsWith("'")||M.startsWith('"')&&M.endsWith('"'))&&(M=M.substring(1,M.length-1)),s.push({type:"api_route",name:M,direction:"produce",line:T+1,snippet:I,method:F,url:M})}!I.startsWith("#[")&&!I.startsWith("//")&&!I.startsWith("*")&&!h&&(d=[],m=[])}return{nodes:n,events:s}}};var On=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],s=e.split(`
|
|
526
|
+
`),r=[{indent:-1,name:"root",type:"root"}],o=[],c=/^class\s+([a-zA-Z0-9_]+)/,a=/^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(b){return b.trim().split(/[.(]/)[0]?.trim()||b}function d(b){let y=b.decorators.map(w=>u(w.raw)),E={decorators:b.decorators,decoratorNames:y};return b.async===!0&&(E.async=!0),JSON.stringify(E)}let m=!1,h="",g=[],_=[];for(let b=0;b<s.length;b++){let y=s[b],E=y.trim();if(!E||E.startsWith("#"))continue;let w=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,x=E.match(w);if(x&&(this.currentRoutePrefix=x[2]),m){if(E.endsWith(h)||E.includes(h)){m=!1;let $=E.replace(h,"").trim();$&&g.push($);let L=r[r.length-1];L.node&&(L.node.doc=g.join(`
|
|
527
|
+
`).trim()),g=[]}else g.push(E);continue}let v=y.search(/\S/),k=y.trim(),N=k.match(/^(['"]{3})/);if(N){let $=N[1],L=r[r.length-1];if(L.node&&!L.node.doc){if(k.substring(3).includes($)){let Y=k.replace(new RegExp($,"g"),"").trim();L.node.doc=Y}else{m=!0,h=$;let Y=k.substring(3).trim();Y&&g.push(Y)}continue}}for(;r.length>1&&r[r.length-1].indent>=v;)r.pop();let O=r[r.length-1],T=k.match(p);if(T){o.push({raw:T[1].trim(),line:b+1});continue}let I=k.match(c);if(I){let $=I[1],L={name:$,kind:"ClassDeclaration",classification:"Class",signature:`class ${$}`,line:b+1,endLine:b+1,doc:"",capabilities:d({decorators:o}),members:[]};_.push(L),O.node?(O.node.members||(O.node.members=[]),O.node.members.push(L)):t.push(L),r.push({indent:v,name:$,type:"class",node:L}),o=[];continue}let U=k.match(a);if(U){let $=!!U[1],L=U[1]||U[2],Y=O.type==="class",he=!1,pe={};for(let M of o)if(M.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){he=!0;let de=["get","post","put","delete","patch"].find(Be=>M.raw.toLowerCase().includes(`.${Be}`))?.toUpperCase()||"GET",Ce=M.raw.match(/['"]([^'"]+)['"]/),ie=Ce?Ce[1]:"/";if(this.currentRoutePrefix){let Be=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,ds=ie.startsWith("/")?ie:`/${ie}`;ie=Be+ds}pe={type:"route",method:de,path:ie}}if(he){let M=pe.path||"",_e={name:M||L,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${L}`,line:b+1,endLine:b+1,doc:"",capabilities:JSON.stringify({handler:Y?`${O.name}.${L}`:L,async:$,...pe})};_.push(_e),t.push(_e),n.push({type:"api_route",name:M,direction:"consume",line:b+1,snippet:k})}let ae=o.some(M=>M.raw==="staticmethod"),ye=o.some(M=>M.raw==="classmethod"),j=`${$?"async ":""}${Y?(ae?"@staticmethod ":ye?"@classmethod ":"")+O.name+".":""}${L}`,F={name:L,kind:$&&Y?"AsyncMethodDeclaration":$?"AsyncFunctionDeclaration":Y?"MethodDeclaration":"FunctionDeclaration",classification:Y?ae||ye?"Static Method":"Method":"Function",signature:j,line:b+1,endLine:b+1,doc:"",capabilities:d({decorators:o,async:$}),members:[]};_.push(F),O.node?(O.node.members||(O.node.members=[]),O.node.members.push(F)):t.push(F),r.push({indent:v,name:L,type:"function",node:F}),o=[];continue}let H=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,P=k.match(H);if(P){let $=P[1].replace(/^\^/,""),L={name:$,kind:"HTTP Route",classification:"Service Boundary",signature:k.trim(),line:b+1,endLine:b+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:$})};_.push(L),t.push(L),n.push({type:"api_route",name:$,direction:"consume",line:b+1,snippet:k});continue}let R=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,A=k.match(R);if(A){let $=A[1].toUpperCase(),L=A[2].trim();(L.startsWith("'")&&L.endsWith("'")||L.startsWith('"')&&L.endsWith('"'))&&(L=L.substring(1,L.length-1)),n.push({type:"api_route",name:L,direction:"produce",line:b+1,snippet:k,method:$,url:L})}let D=k.match(l);if(D){let $=D[1]||D[2],L={name:$,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${$}`,line:b+1,endLine:b+1,doc:"",capabilities:JSON.stringify({type:"import",module:$})};_.push(L),t.push(L),o=[];continue}o=[],O.node&&(O.node.endLine=b+1)}return{nodes:_,events:n}}};var rr=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function",signature:i[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:i=>({name:i[1],kind:"MethodDeclaration",classification:"Method",signature:i[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:i=>({name:i[1],kind:"ImportSpecifier",classification:"Dependency",signature:i[0],meta:{type:"import",path:i[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function",signature:i[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"StructDeclaration",classification:"Class",signature:i[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"EnumDeclaration",classification:"Class",signature:i[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"TraitDeclaration",classification:"Class",signature:i[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:i=>({name:i[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:i[0],meta:{type:"import",path:i[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:i=>({name:i[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:i=>({name:i[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:i[1]}})}]}];function sc(i,e){let t=[];if(i===".go"&&e.some(n=>n.kind==="TypeDeclaration")&&t.push("Go type"),i===".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")),i===".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 Fn=class{phpParser=new Dn;pythonParser=new On;treeSitterParser=new Mn;supports(e){return rr.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=Ls.extname(e).toLowerCase(),s=[],r=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let a=this.pythonParser.parse(t);s=a.nodes,r=a.events}else if(n===".php"){let a=e.toLowerCase().endsWith("api.php"),l=this.phpParser.parse(t,a);s=l.nodes,r=l.events}else try{s=await this.treeSitterParser.parse(e,t)}catch{}if(s.length>0){let a=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",l=s.filter(m=>m.classification!=="Dependency"),p=s.filter(m=>m.classification==="Dependency"),u=sc(n,s),d=Ut({classification:a,capabilities:u,exports:l.map(m=>({name:m.name,kind:m.kind,classification:m.classification})),fileName:Ls.basename(e)});return{exports:l,imports:p.map(m=>({module:m.name,name:m.name,kind:m.kind,classification:m.classification})),events:r,classification:a,summary:d||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=rr.find(a=>a.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};for(let a of o.rules){a.regex.lastIndex=0;let l;for(;(l=a.regex.exec(t))!==null;){let p=a.onMatch(l),u=t.substring(0,l.index).split(`
|
|
528
|
+
`).length;s.push({name:p.name||"anonymous",kind:p.kind||"Unknown",classification:p.classification||"Other",signature:p.signature||l[0],line:u,endLine:u,doc:"",capabilities:JSON.stringify(p.meta||{})})}}let c=Ut({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:s.map(a=>({name:a.name,kind:a.kind,classification:a.classification})),fileName:Ls.basename(e)});return{exports:s,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:c||"Module",parseStatus:s.length>0?"success":"partial"}}};W();var Ns=new Fn;async function jt(i){let e=ar.extname(i);if(Ns.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=await or.promises.readFile(i,"utf-8");return{...await Ns.parse(i,r),content:r}}catch(r){return S.error({filePath:i,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:r.message}}let t;try{t=await or.promises.readFile(i)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),s=Ji(n);try{let r=i.endsWith(".tsx"),o=i.endsWith(".d.ts")||i.endsWith(".d.tsx"),c,a={syntax:"typescript",tsx:r,decorators:!0,comments:!0};if(o)try{c=$s.parseSync(n,a)}catch{c=$s.parseSync(n,{...a,isModule:!1})}else c=$s.parseSync(n,a);let l=c.span.start,p=Yi(t),u=Qi(n),d=w=>Vi(w,l,t),m=Xi(c.body),h=tr(c.body);h.length>0&&S.debug({filePath:i,count:h.length},"Extracted type references"),h.forEach(w=>{m.push({module:"__type_reference__",name:w})});let g=Zi(c.body,l,t,n,s,u,i,d,p),_=er(c.body,l,t,s,d,p),b=Pn(i,"","Module"),y=u.length>0&&u[0].start===0?u[0].text:g.find(w=>w.doc)?.doc||"",E=Ki(y);if(!E&&g.length>0){let w=Ht(n);E=Ut({classification:b,capabilities:w,exports:g.map(x=>({name:x.name,kind:x.kind,classification:x.classification})),fileName:ar.basename(i)})}return{exports:g,imports:m,events:_,classification:b,summary:E,content:n,parseStatus:"success"}}catch(r){S.warn({filePath:i,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=await Ns.parse(i,n);return{...o,content:n,classification:o.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return S.error({filePath:i,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}import Wn from"path";var ic=50;function zt(i,e,t,n){let s={name:Wn.basename(e)||e,type:"directory",path:e,children:[]};return i.forEach(r=>{let c=Wn.relative(e,r.path).split(Wn.sep),a=s;for(let l=0;l<c.length;l++){let p=c[l];if(n!==void 0&&l>=n)return;let u=l===c.length-1;if(n===1&&l===0&&u)return;let d=n!==void 0&&l===n-1&&!u,m=Wn.join(e,...c.slice(0,l+1)),h=a.children?.find(g=>g.name===p);if(!h){if(a.children&&a.children.length>=ic){a.children.find(b=>b.type==="truncated")||a.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}h={name:p,type:u?"file":"directory",path:m,children:u||d?void 0:[],summary:u?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},h.summary&&(t==="structure"||t==="signatures")&&(delete h.summary.chunks,delete h.summary.imports),a.children?.push(h)}a=h}}),s}W();import Ms from"p-limit";qe();import Ds from"path";import Nc from"fs";import Ac from"os";import we from"path";import wt from"fs";import{loadConfig as oc,createMatchPath as ac}from"tsconfig-paths";import Ve from"path";import Bt from"fs";var Qe=class extends Error{constructor(t,n,s){super(n);this.code=t;this.cause=s;this.name="FileSystemError"}};function cr(i){let e;try{e=Bt.statSync(i).isDirectory()?i:Ve.dirname(i)}catch(t){throw t.code==="ENOENT"?new Qe("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new Qe("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new Qe("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==Ve.dirname(e);){let t=Ve.join(e,"tsconfig.json");if(Bt.existsSync(t))return e;e=Ve.dirname(e)}return null}function lr(i){let e;try{e=Bt.statSync(i).isDirectory()?i:Ve.dirname(i)}catch(t){throw t.code==="ENOENT"?new Qe("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new Qe("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new Qe("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==Ve.dirname(e);){let t=Ve.join(e,"package.json");if(Bt.existsSync(t))try{if(JSON.parse(Bt.readFileSync(t,"utf8")).workspaces)return e}catch{}e=Ve.dirname(e)}return null}import St from"path";import ct from"fs";function pr(i,e){let t=new Map,n=e.workspaces||[];for(let s of n){let r=s.replace("/*",""),o=St.join(i,r);if(!ct.existsSync(o))continue;let c=ct.readdirSync(o);for(let a of c){let l=St.join(o,a,"package.json");if(ct.existsSync(l))try{let p=JSON.parse(ct.readFileSync(l,"utf8"));p.name&&t.set(p.name,{name:p.name,path:St.dirname(l),main:p.main||"dist/index.js"})}catch{}}}return t}function dr(i){let e=new Map;try{let t=JSON.parse(ct.readFileSync(i,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[s,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),c=St.dirname(i),a=St.resolve(c,o),l=St.join(a,"package.json");if(ct.existsSync(l))try{let p=JSON.parse(ct.readFileSync(l,"utf8"));e.set(s,{name:s,path:a,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import ur from"path";import Se from"fs";var rc=[".ts",".tsx",".d.ts",".js",".jsx"];function Ke(i){let e=ur.extname(i);if(e===".js"||e===".jsx"){let t=i.slice(0,-e.length),n=e===".jsx"?[".tsx",".ts"]:[".ts",".tsx"];for(let s of n){let r=t+s;if(Se.existsSync(r)&&Se.statSync(r).isFile())return r}if(Se.existsSync(i)&&Se.statSync(i).isFile())return i}if(Se.existsSync(i)&&Se.statSync(i).isFile())return i;for(let t of rc){let n=i+t;if(Se.existsSync(n)&&Se.statSync(n).isFile())return n}if(Se.existsSync(i)&&Se.statSync(i).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=ur.join(i,"index"+t);if(Se.existsSync(n))return n}return""}var Un=new Map;function Hn(i){let e=cr(i);if(!e)return null;if(Un.has(e))return Un.get(e)||null;let t=oc(e);if(t.resultType==="failed")return Un.set(e,null),null;let n=t,s=n.absoluteBaseUrl;!s&&n.paths&&Object.keys(n.paths).length>0&&(s=n.configFileAbsolutePath?we.dirname(n.configFileAbsolutePath):e);let r=ac(s,n.paths,n.mainFields,n.addMatchAll),o=lr(e),c=new Map;if(o){let u=we.join(o,"package.json");if(wt.existsSync(u))try{let d=JSON.parse(wt.readFileSync(u,"utf8"));c=pr(o,d)}catch{}}let a=we.join(e,"package.json");wt.existsSync(a)&&dr(a).forEach((d,m)=>c.set(m,d));let l={baseUrl:s||"",paths:n.paths,matchPath:r,workspacePackages:c,imports:new Map},p=we.join(e,"package.json");if(wt.existsSync(p))try{let u=JSON.parse(wt.readFileSync(p,"utf8"));if(u.imports){for(let[d,m]of Object.entries(u.imports))if(typeof m=="string"||typeof m=="object"&&m!==null){let h=m;Array.isArray(m)&&(h=m[0]),typeof h=="object"&&(h=h.default||h.node),typeof h=="string"&&l.imports.set(d,h)}}}catch{}return Un.set(e,l),l}function lt(i,e,t){if(!i)return"";if(i.includes(".")&&!i.startsWith(".")&&!i.startsWith("/")&&!i.endsWith(".js")&&!i.endsWith(".ts")&&!i.endsWith(".json")){let s=i.split(".")[0];if(s&&s!==i){let r=lt(s,e,t);if(r)return r}}if(i.startsWith(".")){let s=we.dirname(e),r=we.resolve(s,i);return Ke(r)}let n=Hn(e);if(n){let s=n.matchPath(i);if(s)return Ke(s);if(!i.startsWith("@")||i.startsWith("@/")){let o=we.resolve(n.baseUrl,i),c=Ke(o);if(c)return c}for(let[o,c]of n.imports.entries())if(o.includes("*")){let a="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",l=new RegExp(a),p=i.match(l);if(p){let u=p[1],d=c.replace("*",u),m=we.resolve(n.baseUrl,d);return Ke(m)}}else if(o===i){let a=we.resolve(n.baseUrl,c);return Ke(a)}let r=n.workspacePackages.get(i);if(r){let o=we.join(r.path,"src/index.ts");if(wt.existsSync(o))return o;let c=we.join(r.path,r.main),a=Ke(c);if(a)return a}}return""}import cc from"fs";import lc from"path";import hr from"js-yaml";function mr(i){let e=lc.basename(i),t=cc.readFileSync(i,"utf8"),n=[];if(e.endsWith(".prisma"))return{...mc(t,i),content:t};if(e.endsWith(".graphql")||e.endsWith(".gql"))return{...hc(t,i),content:t};let s="Configuration";return e==="lerna.json"?{...gc(t,i),content:t}:e==="turbo.json"?{...yc(t,i),content:t}:e==="pnpm-workspace.yaml"?{...bc(t,i),content:t}:(e.includes("Dockerfile")?(s="Infrastructure (Docker) ",pc(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(s="Infrastructure (YAML) ",dc(t,n)):e.startsWith(".env")?(s="Configuration (Env) ",uc(t,n)):e==="package.json"&&(s="Project Manifest",fc(t,n)),{configs:n,classification:s,content:t})}function pc(i,e){let t=i.split(`
|
|
529
|
+
`);for(let n of t){let s=n.trim();if(s.startsWith("FROM "))e.push({key:"base_image",value:s.substring(5).trim(),kind:"Image"});else if(s.startsWith("EXPOSE "))e.push({key:"port",value:s.substring(7).trim(),kind:"Port"});else if(s.startsWith("ENV ")){let r=s.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],c=r.slice(1).join("= ").trim()||"undefined",a="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(a="Service"),e.push({key:o,value:c,kind:a})}}}}function dc(i,e){try{let t=hr.load(i);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[s,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${s}`,value:s,kind:"Service"}),o.image&&e.push({key:`service:${s}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(c=>{e.push({key:`service:${s}:port`,value:String(c),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(c=>{let[a,...l]=c.split("= ");a&&l.length>0&&e.push({key:`service:${s}:env:${a}`,value:l.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[c,a]of Object.entries(o.environment))e.push({key:`service:${s}:env:${c}`,value:String(a),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(c=>{e.push({key:`service:${s}:depends_on`,value:c,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let c of Object.keys(o.depends_on))e.push({key:`service:${s}:depends_on`,value:c,kind:"Dependency"})}let n=(s,r="")=>{if(!(!s||typeof s!="object"||Array.isArray(s)))for(let[o,c]of Object.entries(s)){let a=r?`${r}.${o}`:o;if(t.services&&(a.startsWith("services.")||a==="services")){c&&typeof c=="object"&&!Array.isArray(c)&&n(c,a);continue}if(c&&typeof c=="object"&&!Array.isArray(c))n(c,a);else{let l=String(c),p="Env";o.toLowerCase().includes("image")&&(p="Image"),o.toLowerCase().includes("port")&&(p="Port"),o.toLowerCase().includes("service")&&(p="Service"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(p="Service"),e.push({key:a,value:l.length>100?l.substring(0,97)+"...":l,kind:p})}}};n(t)}catch{let n=i.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(s=>{let r=s.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function uc(i,e){let t=i.split(`
|
|
530
|
+
`);for(let n of t){let s=n.trim();if(s&&!s.startsWith("#")){let r=s.split("=");if(r[0]){let o=r[0].trim(),c=r.slice(1).join("=");c=c.trim().replace(/^['"](.*)['"]$/,"$1");let a="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(a="Service"),e.push({key:o,value:c,kind:a})}}}}function mc(i,e){let t=[],n="Contract (Prisma) ",s=/^model\s+(\w+)/gm,r;for(;(r=s.exec(i))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(i))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let c=/provider\s*=\s*"([^"]+)"/,a=i.match(c);return a&&t.push({key:"datasource_provider",value:a[1],kind:"Database Config"}),{classification:n,configs:t,content:i}}function hc(i,e){let t=[],n="Contract (GraphQL) ",s=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=s.exec(i))!==null;){let o=r[0],c="GraphQL Type";o.startsWith("input")&&(c="GraphQL Input"),o.startsWith("interface")&&(c="GraphQL Interface"),o.startsWith("enum")&&(c="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:c})}return{classification:n,configs:t,content:i}}function fc(i,e){try{let t=JSON.parse(i);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"Service"}),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(c=>o.includes(c))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},s=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(s.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Service"})}}catch{}}function gc(i,e){let t=[],n="Monorepo (Lerna) ";try{let s=JSON.parse(i);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),s.version&&t.push({key:"lerna_version",value:s.version,kind:"Monorepo"}),s.packages&&(Array.isArray(s.packages)?s.packages:[s.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),s.npmClient&&t.push({key:"npm_client",value:s.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:i}}function yc(i,e){let t=[],n="Monorepo (Turborepo) ";try{let s=JSON.parse(i);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),s.pipeline)for(let r of Object.keys(s.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=s.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(s.tasks)for(let r of Object.keys(s.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:i}}function bc(i,e){let t=[],n="Monorepo (pnpm) ";try{let s=hr.load(i);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),s&&s.packages&&(Array.isArray(s.packages)?s.packages:[s.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n,content:i}}z();rt();import{execSync as pt}from"child_process";import Gt from"path";import As from"fs";function ce(i){try{if(!As.existsSync(Gt.join(i,".git")))return null;let e=pt("git rev-parse --abbrev-ref HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return e==="HEAD"?pt("git rev-parse --short HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():e.replace(/[\/\\:*"<>|?]/g,"-")}catch{return null}}function xe(i){try{return As.existsSync(Gt.join(i,".git"))?pt("git rev-parse HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function gr(i,e=50){try{let t=pt(`git rev-list --max-count=${e} HEAD`,{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return t?t.split(`
|
|
531
|
+
`):[]}catch{return[]}}function yr(i,e,t){try{return pt(`git merge-tree --write-tree ${e} ${t}`,{cwd:i,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}var _c=new Set([".ts",".tsx",".yaml",".yml",".php",".py",".go",".prisma",".graphql",".gql"]),Ec=new Set(["package.json","lerna.json","turbo.json","pnpm-workspace.yaml"]),Sc=new Set(["node_modules",".git","dist","build","vendor",".next",".cache","coverage"]);function fr(i){let e=i.split("/");for(let s of e)if(Sc.has(s))return!1;if(i.endsWith(".min.js"))return!1;let t=Gt.basename(i);if(t.startsWith("Dockerfile")||t.startsWith(".env")||Ec.has(t))return!0;let n=Gt.extname(t).toLowerCase();return _c.has(n)}function wc(i){let e=i.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 br(i,e){try{if(!As.existsSync(Gt.join(i,".git")))return!0;let t=xe(i);if(!t)return!0;if(e&&e!==t){let s=pt(`git diff --name-only ${e} ${t}`,{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(s&&s.split(`
|
|
532
|
+
`).some(r=>r&&fr(r)))return!0}let n=pt("git status --porcelain",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return n?n.split(`
|
|
533
|
+
`).some(s=>s?fr(wc(s)):!1):!1}catch{return!0}}z();W();import{execSync as _r}from"child_process";var dt=S.child({module:"nano-repair"}),Pe=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:s}=C.getInstance(e);this.intentLogs=t,this.exports=n,this.missions=s,this.repoPath=e}detectAndRepairShifts(){let e=this.intentLogs.findRepairableOrphans();if(e.length===0)return{repaired:0,failed:0};dt.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let s of e){let r=this.exports.findByNameAndFile(s.symbol_name,s.file_path);if(r.length>0){let c=r.find(a=>a.signature===s.signature)||r[0];this.intentLogs.update(s.id,{symbol_id:c.id}),dt.info({logId:s.id,symbol:s.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(s.symbol_name);if(o.length>0){let c=o.filter(a=>a.file_path!==s.file_path);if(c.length>0){let a=c.find(l=>l.signature===s.signature)||c[0];this.intentLogs.update(s.id,{symbol_id:a.id,file_path:a.file_path}),dt.info({logId:s.id,symbol:s.symbol_name,oldPath:s.file_path,newPath:a.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&dt.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(){let e="HEAD";try{e=_r("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}}if(!e)return{suspended:0,resumed:0,completed:0};let t=this.missions.findActive(),n=0;for(let o of t)o.git_branch&&o.git_branch!==e&&(this.missions.updateStatus(o.id,"suspended"),dt.info({missionId:o.id,branch:o.git_branch,current:e},"Context Pivot: Suspended mission"),n++);this.missions.resumeByBranch(e);let s=[];try{s=_r(`git branch --merged "${e}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
534
|
+
`).map(c=>c.trim().replace(/^\* /,"")).filter(c=>c&&c!==e)}catch{}let r=0;if(s.length>0){let o=this.missions.findMergedMissions(e,s);for(let c of o)this.missions.updateStatus(c.id,"completed"),dt.info({missionId:c.id,branch:c.git_branch},"Merge Sentinel: Auto-completed mission"),r++}return(n>0||r>0)&&dt.info({suspended:n,completed:r},"Git-Native Lifecycle Sync complete"),{suspended:n,resumed:-1,completed:r}}};W();hn();import{Worker as xc}from"node:worker_threads";import{cpus as vc}from"node:os";import{fileURLToPath as Tc}from"node:url";import{dirname as Rc,join as kc}from"node:path";import{existsSync as Ic}from"node:fs";var Er=Tc(import.meta.url),Cc=Rc(Er),Lc=Er.endsWith(".ts");function $c(){if(Lc)return null;let i=kc(Cc,"worker.js");return Ic(i)?i:ht("dist/logic/parser/worker.js")}var Ps=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,vc().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{S.info({numWorkers:this.numWorkers},"Initializing parser worker pool");let t=new Promise((n,s)=>{e=setTimeout(()=>s(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,S.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=$c();if(!e)throw new Error("Parser worker pool not available in development mode (tsx). Use main-thread fallback.");S.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,s)=>{let r=setTimeout(()=>{s(new Error(`Parser worker ${t} initialization timed out`))},this.initTimeout),o=new xc(e,{execArgv:process.execArgv}),c={worker:o,busy:!1,currentTaskId:null};o.on("message",a=>{if(a.type==="ready"){if(clearTimeout(r),this.shutdownRequested){o.terminate().catch(()=>{}),n();return}this.workers.push(c),S.debug({workerIndex:t},"Parser worker ready"),n()}else a.type==="result"&&a.id?this.handleTaskComplete(c,a.id,a.result):a.type==="error"&&a.id&&this.handleTaskError(c,a.id,new Error(a.error||"Unknown error"))}),o.on("error",a=>{if(clearTimeout(r),S.error({err:a,workerIndex:t},"Parser worker error"),c.currentTaskId&&this.handleTaskError(c,c.currentTaskId,a),!this.initialized){s(a);return}let l=this.workers.indexOf(c);l!==-1&&this.workers.splice(l,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{S.error({err:p},"Failed to replace crashed parser worker")})}),o.on("exit",a=>{a!==0&&!this.shutdownRequested&&S.warn({workerIndex:t,code:a},"Parser worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.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}S.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,S.info("Parser worker pool shutdown complete")}},xt=null;function Sr(i){return xt||(xt=new Ps(i)),xt}async function wr(){xt&&(await xt.shutdown(),xt=null)}var Pc=Ac.cpus().length||4,Mc=Nn.DEFAULT_CONCURRENCY;async function G(i,e=Mc,t=!1,n=!0,s){let r=C.getInstance(i),o=r.files.database,c=Oe(i),a=c.concurrency??e;if(Oi(),!t&&He(i)){let b=Pt(i),y=xe(i);if(b&&!br(i,b))return Ts(),S.debug({repoPath:i,commit:y},"Index is current, skipping re-index (fast-path)"),o}Hn(i);let l=r.files.findAll(),p=new Map(l.map(b=>[b.path,{mtime:b.mtime,hash:b.content_hash}])),u=Date.now();s?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let d=await Is(i,c.ignore),m=new Map(d.map(b=>[b.path,b.mtime])),h=l.filter(b=>!m.has(b.path)).map(b=>b.path),g=l.length===0,_=[];if(t||g)_.push(...d);else{let b=d.filter(x=>{let v=p.get(x.path);return!v||v.mtime!==x.mtime}),y=Ms(a*4),E=b.map(x=>y(async()=>{let v=p.get(x.path);if(!v||!v.hash)return x;try{let k=await Nc.promises.readFile(x.path,"utf8");return ai(k,v.hash)?x:(r.files.updateMtime(x.path,x.mtime),null)}catch{return null}})),w=await Promise.all(E);_.push(...w.filter(x=>x!==null))}if(h.length===0&&_.length===0){Ts();let b=xe(i);return ys(i,b||void 0),o}if(g?S.info({totalFiles:d.length},"Starting initial repository indexing..."):S.info({toDelete:h.length,toProcess:_.length},"Syncing repository updates..."),h.length>0&&r.files.deletePaths(h),_.length>0){Wi(),n?(Ot(!0),it().initialize().catch(()=>{})):Ot(!1);let b=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,y=[],E=[];for(let R of _)b.test(Ds.basename(R.path))?y.push(R):E.push(R);let w=0,x=_.length,v=!1,k=Sr();try{await k.initialize(),v=!0,S.info({workers:k.workerCount},"Parser worker pool active")}catch(R){S.warn({err:R},"Parser worker pool failed to initialize, falling back to main-thread parsing"),v=!1}let N=(R,A)=>{let D=A.imports?.map(L=>({...L,resolved_path:lt(L.module,R.path,i)})),$=A.content?mt(A.content):null;return w++,(w%50===0||w===x)&&S.info({completed:w,total:x},"Parsing files..."),s?.({phase:"parse",current:w,total:x,message:`Parsing ${Ds.basename(R.path)}`}),{meta:R,...A,imports:D,embedding:null,kind:"code",contentHash:$}},O;if(v)O=y.map(R=>k.parseFile(R.path).then(A=>N(R,A),A=>(w++,S.error({path:R.path,error:A},"Worker parse failed"),{meta:R,exports:[],imports:[],content:"",kind:"error"})));else{let R=g?Math.max(a,Math.min(Pc-1,16)):a,A=Ms(R);O=y.map(D=>A(async()=>{try{let $=await jt(D.path);return N(D,$)}catch($){return w++,S.error({path:D.path,error:$},"Failed to parse file"),{meta:D,exports:[],imports:[],content:"",kind:"error"}}}))}let T=Ms(a),I=E.map(R=>T(async()=>{try{let A=mr(R.path),D=A.content?mt(A.content):null;return w++,(w%50===0||w===x)&&S.info({completed:w,total:x},"Parsing configs..."),s?.({phase:"parse",current:w,total:x,message:`Parsing config ${Ds.basename(R.path)}`}),{meta:R,...A,embedding:null,kind:"config",contentHash:D}}catch(A){return w++,S.error({path:R.path,error:A},"Failed to parse config"),{meta:R,exports:[],imports:[],content:"",kind:"error"}}}));S.info({total:x,codeFiles:y.length,configFiles:E.length,useParserPool:v},"Phase 1: Parsing all files...");let U=Date.now(),H=(await Promise.all([...O,...I])).filter(Boolean),P=Date.now()-U;if(Wt("parse",P),S.info({count:H.length,time:`${(P/1e3).toFixed(1)}s`},"Phase 1 complete"),v&&wr().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let R=[];H.forEach((ae,ye)=>{"summary"in ae&&ae.summary&&R.push({fileIdx:ye,text:ae.summary})}),S.info("Phase 2+3: Generating embeddings + persisting in parallel..."),s?.({phase:"embed",current:0,total:H.length,message:"Generating embeddings..."});let A=Date.now(),D=(async()=>{if(R.length>0){S.info({count:R.length}," \u2192 Generating file summary embeddings...");let ae=R.map(j=>j.text),ye=await yn(ae,256);return S.info({count:R.length}," \u2713 File summaries complete"),ye}return[]})();s?.({phase:"persist",current:0,total:H.length,message:"Saving to database..."});let $=Date.now();r.files.batchSaveIndexResults(H,i,mt,lt);let L=Date.now()-$;Wt("persist",L),S.info({time:`${(L/1e3).toFixed(1)}s`},"Structural persist complete");let Y=await D,he=Date.now()-A;if(Wt("embed",he),S.info({time:`${(he/1e3).toFixed(1)}s`},"Embeddings complete"),Y.length>0){let ae=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),ye=o.transaction(F=>{for(let M of F)ae.run(M.embedding?JSON.stringify(M.embedding):null,M.path)}),j=R.map((F,M)=>({path:H[F.fileIdx].meta.path,embedding:Y[M]}));ye(j),S.info({count:j.length},"Embedding column updated")}let pe=await r.intentLogs.backfillEmbeddings(64);pe>0&&S.info({count:pe}," \u2713 Intent log embeddings backfilled")}else{s?.({phase:"persist",current:0,total:H.length,message:"Saving to database..."});let R=Date.now();r.files.batchSaveIndexResults(H,i,mt,lt),Wt("persist",Date.now()-R)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(g||_.length>0){let b=xe(i);ys(i,b||void 0)}return(_.length>0||h.length>0)&&new Pe(i).detectAndRepairShifts(),Fi(Date.now()-u),s?.({phase:"complete",current:_.length,total:_.length,message:"Indexing complete"}),o}W();import xr from"path";import Dc from"ignore";import vr from"fs";z();async function qt(i,e=Nn.DEFAULT_CONCURRENCY,t="detailed",n,s){S.info({repo:i,level:t,subPath:n},"Ensuring cache is up-to-date..."),await G(i,e);let{files:r,exports:o,imports:c}=C.getInstance(i),a=n?r.findInSubPath(i,n):r.findAll(),l=Oe(i),p=Dc(),u=xr.join(i,".gitignore");if(vr.existsSync(u)&&p.add(vr.readFileSync(u,"utf8")),l.ignore&&l.ignore.length>0&&p.add(l.ignore),p.add($n),a=a.filter(y=>{let E=xr.relative(i,y.path);return!p.ignores(E)}),S.info({count:a.length},"Fetching data from DB..."),t==="lite"){let y=a.map(E=>({path:E.path,mtime:E.mtime}));return zt(y,i,t,s)}if(t==="summaries"){let y=a.map(E=>({path:E.path,mtime:E.mtime,classification:E.classification||void 0,summary:E.summary||void 0}));return zt(y,i,t,s)}let d=a.map(y=>y.path),m=o.findByFiles(d),h=t==="detailed"?c.findByFiles(d):[],g=new Map;for(let y of m){let E=g.get(y.file_path)||[];E.push(y),g.set(y.file_path,E)}let _=new Map;for(let y of h){let E=_.get(y.file_path)||[];E.push(y),_.set(y.file_path,E)}let b=a.map(y=>{let w=(g.get(y.path)||[]).map(v=>({name:v.name,kind:v.kind,signature:v.signature,line:v.start_line}));t==="structure"?w=w.map(v=>({name:v.name,kind:v.kind,line:v.line})):t==="signatures"&&(w=w.map(v=>({name:v.name,kind:v.kind,signature:v.signature,line:v.line})));let x=[];return t==="detailed"&&(x=(_.get(y.path)||[]).map(k=>({module:k.module_specifier,resolved_path:k.resolved_path}))),{path:y.path,mtime:y.mtime,classification:y.classification||void 0,summary:y.summary||void 0,exports:w,imports:x.length>0?x:void 0,chunks:[]}});return S.info({count:b.length},"Building hierarchical project tree..."),zt(b,i,t,s)}rt();async function Tr(i,e){let t=Oc.resolve(i);try{await B(async()=>{se("\u{1F311} Liquid Shadow: Topological Mapping");let n=parseInt(e.depth,10),s=await qt(t,n,"detailed",e.subPath);console.log(` ${f.bold("Root")}: ${f.cyan(t)}`),e.subPath&&console.log(` ${f.bold("Subpath")}: ${f.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)});xs([r(s)]),console.log(""),Ee("Mapping concluded.")})}finally{await J(t)}}import kr from"path";import Fc from"fs";W();import ne from"path";import Os from"fs";var jn=S.child({module:"path-resolver"}),Jt=class{repoPath;constructor(e){this.repoPath=ne.isAbsolute(e)?ne.normalize(e):ne.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw jn.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(ne.isAbsolute(e)?t=ne.normalize(e):t=ne.join(this.repoPath,e),t=ne.normalize(t),!this.isWithinRoot(t))throw jn.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 Os.existsSync(t)?t:(jn.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return jn.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=ne.resolve(e),n=ne.resolve(this.repoPath),s=ne.relative(n,t);if(s.startsWith("..")||ne.isAbsolute(s))return!1;if(Os.existsSync(t)){let o=Os.realpathSync(t),c=ne.relative(n,o);if(c.startsWith("..")||ne.isAbsolute(c))return!1}return!0}catch{return!1}}getRelative(e){let t=ne.normalize(e);return ne.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return ne.normalize(e)}static isPathWithinRoot(e,t){let n=ne.resolve(e),s=ne.resolve(t),r=ne.relative(n,s);return r===""||!r.startsWith("..")&&!ne.isAbsolute(r)}};function Rr(i){return new Jt(i)}async function Ir(i,e){let t=kr.resolve(i);await B(async()=>{if(se("\u{1F311} Liquid Shadow: Intelligence Deployment"),console.log(` ${f.bold("Target")}: ${f.cyan(t)}`),console.log(` ${f.bold("Objective")}: ${e.output?f.magenta("Data Extraction"):f.green("Semantic Mapping")}`),console.log(""),!e.output){let s=be();s.start("Engaging intelligence engines...");let r="",o=c=>{if(c.phase!==r){r=c.phase;let a={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"}[c.phase]||c.phase;s.message(`${a}...`)}if(c.total>0&&c.current>0){let a=Math.round(c.current/c.total*100);s.message(`${r==="parse"?"Parsing":"Processing"}: ${c.current}/${c.total} (${a}%)`)}};try{await G(t,void 0,e.force,e.deep??!0,o),s.message("\u{1FA79} Running Nano-Repair healing...");let a=new Pe(t).detectAndRepairShifts();s.stop("Intelligence mapping successfully concluded."),console.log(""),console.log(` ${f.bold("Next Steps:")}`),console.log(` ${f.dim("view your repo stats")} -> ${f.bold(f.cyan("liquid-shadow dashboard"))}`),console.log(` ${f.dim("start a chat search")} -> ${f.bold(f.cyan('liquid-shadow search-concept "your query"'))}`),console.log(""),Ee("Liquid Shadow is online.")}catch(c){throw s.stop(`Operation failed: ${c.message}`),c}finally{await J(t)}return}let n=be();n.start("Engaging intelligence engines...");try{let s=await qt(t,5,e.level,e.subPath),r=kr.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!Jt.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");Fc.writeFileSync(r,JSON.stringify(s,null,2)),n.stop(`Data extraction saved: ${f.bold(f.cyan(r))}`),Ee("Extraction complete.")}catch(s){throw n.stop(`Extraction failed: ${s.message}`),s}finally{await J(t)}})}import{performance as Cr}from"perf_hooks";import Wc from"path";z();async function Lr(i){let e=Wc.resolve(i);await B(async()=>{console.log(`
|
|
535
|
+
${f.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${f.gray("Repository: ")} ${e}`),console.log(` ${f.yellow("Starting fresh index (DB deleted)...")}
|
|
536
|
+
`);let t=Cr.now();try{await G(e,10,!0);let n=Cr.now()-t,s=C.getInstance(e),r=s.files.getCount(),o=s.exports.getCount(),c=s.exports.getWithEmbeddingsCount();X("Benchmark Results",`${f.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
|
|
537
|
+
${f.bold("Files Processed")}: ${f.cyan(r.toString())}
|
|
538
|
+
${f.bold("Symbols Extracted")}: ${f.cyan(o.toString())}
|
|
539
|
+
${f.bold("Symbols Embedded")}: ${f.cyan(c.toString())} (${(c/o*100).toFixed(1)}%)
|
|
520
540
|
`+"\u2500".repeat(40)+`
|
|
521
|
-
${
|
|
522
|
-
${
|
|
523
|
-
${
|
|
524
|
-
Benchmark failed during execution:`,n),n}finally{await q(e)}})}import $n from"path";import pe from"path";import xs from"fs";var ic=/[\x00-\x1f\x7f]/g,rc=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function _s(i){if(typeof i!="string")throw new Error("Invalid path: expected string");if(i.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(i.replace(ic,"").length!==i.length)throw new Error("Invalid path: control characters are not allowed");return i.trim()}function In(i,e=4096){if(typeof i!="string")return"";let t=i.replace(rc,"").trim();return t.length>e?t.slice(0,e):t}Qe();function oc(i){let e=pe.isAbsolute(i)?pe.normalize(i):pe.resolve(process.cwd(),i),t=pe.parse(e).root;for(;e!==t;){if(xs.existsSync(pe.join(e,".liquid-shadow.db"))||xs.existsSync(pe.join(e,".git"))||xs.existsSync(pe.join(e,"package.json")))return e;let n=pe.dirname(e);if(n===e)break;e=n}return null}function Re(i){let e=i?.repoPath?String(i.repoPath):void 0,t=i?.filePath?String(i.filePath):void 0;e&&(e=_s(e)),t&&(t=_s(t));let n;if(e)pe.isAbsolute(e)||(e=pe.resolve(process.cwd(),e)),n=e;else if(t){let o=pe.resolve(process.cwd(),t);n=oc(pe.dirname(o))||process.cwd()}else n=process.cwd();n=pe.normalize(n);let s=ir(n),r;return t&&(r=s.resolve(t)),{...i,repoPath:n,filePath:r,resolver:s}}U();P();import pr from"@swc/core";import Mt from"fs";import ge from"path";import{Visitor as ac}from"@swc/core/Visitor.js";var Cn=class extends ac{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),c=r.property.value||"?";return`${o}.${c}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},s=n(e.callee.object);if(s!=="?"&&t){if(this.calls.add(`${s}.${t}`),s==="axios"||s==="http"||this.axiosInstances.has(s)){let r=this.axiosInstances.get(s)||"";this.extractApiCall(t,e.arguments,r)}if((s.toLowerCase().includes("pubsub")||s==="pubSubClient"||s.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 c=o.expression;if(c.type==="ObjectExpression"){let a=c.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(a&&a.value?.type==="StringLiteral"){r=a.value.value;break}}if(c.type==="CallExpression"&&c.callee.type==="MemberExpression"&&c.callee.object.value==="JSON"&&c.callee.property.value==="stringify"&&c.arguments.length>0){let a=c.arguments[0].expression;if(a.type==="ObjectExpression"){let l=a.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 s=e.init.arguments[0]?.expression;if(s&&s.type==="ObjectExpression"){let r=s.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(s=>s.key.type==="Identifier"&&s.key.value==="url"||s.key.type==="StringLiteral"&&s.key.value==="url"),n=e.properties.find(s=>s.key.type==="Identifier"&&s.key.value==="method"||s.key.type==="StringLiteral"&&s.key.value==="method");if(t&&t.value){let s=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:s.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 s=t[0].expression,r=this.resolveUrlValue(s);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},pt=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,s;for(;(s=n.exec(e))!==null;){let r=s[1]||"",o=s[2],c=s[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=c.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),d=p?p[1]:c.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:d})}}}else if(t===".py"){let n=/(?:([a-zA-Z0-9_\.]+)\.)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,s;for(;(s=n.exec(e))!==null;){let r=s[1]||"",o=s[2],c=s[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=c.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),d=p?p[1]:c.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:d})}}}else if([".ts",".tsx",".js",".jsx"].includes(t)){let n=/import\s+[\s\S]*?from\s+['"](.*?)['"];?/g,s;for(;(s=n.exec(e))!==null;)this.imports.set("*",s[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let c=o[1],a=o[2];c?(this.calls.add(`${c}.${a}`),(c.toLowerCase().includes("pubsub")||c==="pubSubClient")&&a!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:a})):this.calls.add(a)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,s;for(;(s=n.exec(e))!==null;)this.calls.add(s[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,s;for(;(s=n.exec(e))!==null;){let r=s[1],o=r.split("\\"),c=s[2]||o[o.length-1];this.imports.set(c,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,s;for(;(s=n.exec(e))!==null;){let c=s[1];s[2].split(",").map(l=>l.trim()).forEach(l=>{this.imports.set(l,c)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let c=o[1],a=c.split("."),l=a[a.length-1];this.imports.set(l,c)}}}};var cc=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"]);function lr(i,e){let t=e,n=e.match(/\$\{([^}]+)\}/g);if(n)for(let p of n){let d=p.substring(2,p.length-1),u=i.configs.findEnvValue(d);u&&(t=t.replace(p,u))}let s=t.split("?")[0].split("#")[0];try{s.includes("://")&&(s=new URL(s).pathname)}catch{}s.length>1&&s.endsWith("/")&&(s=s.substring(0,s.length-1));let r=[],o=s.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),c=i.files.findSynapses({type:"api_route",name:o.includes("%")?o:s,direction:"consume",limit:10});for(let p of c){let d=p.name.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\*/g,"[^/]+");new RegExp(`^${d.replace(/\//g,"\\/")}$`).test(s.replace(/\*/g,"test-val"))&&r.push({file_path:p.file_path,start_line:p.line_number||0,signature:`[Synapse] ${p.name}`,score:1e3})}let a=s.split(/[^a-zA-Z0-9-_]/).filter(p=>p.length>=3&&!cc.has(p.toLowerCase())&&!/^\d+$/.test(p));if(a.length>0){let d=[...a].sort((m,f)=>f.length-m.length)[0],u=i.exports.findRoutesByToken(d,20);for(let m of u){let f=50,h=(m.signature||m.name||"").toLowerCase();(m.name||"").toLowerCase().includes(s.replace(/\*/g,"").toLowerCase())&&(f+=200);for(let y of a)h.includes(y.toLowerCase())&&(f+=20);r.push({file_path:m.file_path,start_line:m.start_line,signature:`[Boundary] ${m.signature||m.name}`,capabilities:m.capabilities||void 0,score:f})}}if(r.length<3){let p=a.map(d=>d.replace(/[^a-zA-Z0-9_]/g,"")).filter(d=>d.length>0).join(" AND ");if(p.length>0){let d=i.content.search(p);for(let u of d){let m=0,f=u.file_path.toLowerCase(),h=u.snippet.toLowerCase();(f.includes("route")||f.includes("controller"))&&(m+=10),(f.includes("src/api")||f.includes("services/api"))&&(m+=5),(h.includes("addroute")||h.includes("@get"))&&(m+=15),(h.includes("axios.")||h.includes("fetch("))&&(m-=10),(f.includes(".spec.")||f.includes(".test."))&&(m-=20),m>0&&r.push({file_path:u.file_path,start_line:0,signature:`[FTS Match] ${u.snippet.replace(/\n/g," ")}`,score:m})}}}let l=new Map;return r.sort((p,d)=>d.score-p.score).forEach(p=>{l.has(p.file_path)||l.set(p.file_path,p)}),Array.from(l.values()).slice(0,3)}var lc=4,Pt=50,pc=2,uc=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"]);async function ur(i){let{repoPath:e,filePath:t,symbolName:n}=Re(i);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let s=t;await z(e);let r=C.getInstance(e);if(!Mt.existsSync(s))return{isError:!0,content:[{type:"text",text:`File not found: ${s}`}]};let o,c=ge.basename(s),a;if(n){let u=r.exports.findByNameAndFile(n,s);if(u.length>0){let m=u[0];o={start:m.start_line,end:m.end_line},c=m.name,a=m.start_line}}let l={type:o?"function":"file",name:c,path:ge.relative(e,s),line:a,children:[]},p=new Set;p.add(s+(n?`:${n}`:""));let d={count:0,truncated:!1};return await ut(s,l,e,r,p,1,d,o),d.truncated&&l.children.push({type:"function",name:"\u26A0\uFE0F Output Truncated",details:`Trace limited to ${Pt} nodes. Use summarize_file on specific files for deeper analysis.`,children:[]}),{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}async function ut(i,e,t,n,s,r,o,c){if(!(r>lc)){if(o.count>=Pt){o.truncated=!0;return}try{let a=Mt.readFileSync(i,"utf8"),l=ge.extname(i).toLowerCase(),d=(a.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
|
|
541
|
+
${f.bold("Files/sec")}: ${f.green((r/(n/1e3)).toFixed(2))}
|
|
542
|
+
${f.bold("Symbols/sec")}: ${f.green((o/(n/1e3)).toFixed(2))}
|
|
543
|
+
${f.bold("ms per file")}: ${f.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
|
|
544
|
+
Benchmark failed during execution:`,n),n}finally{await J(e)}})}import Gn from"path";import fe from"path";import Ws from"fs";var Hc=/[\x00-\x1f\x7f]/g,Uc=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Fs(i){if(typeof i!="string")throw new Error("Invalid path: expected string");if(i.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(i.replace(Hc,"").length!==i.length)throw new Error("Invalid path: control characters are not allowed");return i.trim()}function zn(i,e=4096){if(typeof i!="string")return"";let t=i.replace(Uc,"").trim();return t.length>e?t.slice(0,e):t}qe();function jc(i){let e=fe.isAbsolute(i)?fe.normalize(i):fe.resolve(process.cwd(),i),t=fe.parse(e).root;for(;e!==t;){if(Ws.existsSync(fe.join(e,".liquid-shadow.db"))||Ws.existsSync(fe.join(e,".git"))||Ws.existsSync(fe.join(e,"package.json")))return e;let n=fe.dirname(e);if(n===e)break;e=n}return null}function Me(i){let e=i?.repoPath?String(i.repoPath):void 0,t=i?.filePath?String(i.filePath):void 0;e&&(e=Fs(e)),t&&(t=Fs(t));let n;if(e)fe.isAbsolute(e)||(e=fe.resolve(process.cwd(),e)),n=e;else if(t){let o=fe.resolve(process.cwd(),t);n=jc(fe.dirname(o))||process.cwd()}else n=process.cwd();n=fe.normalize(n);let s=Rr(n),r;return t&&(r=s.resolve(t)),{...i,repoPath:n,filePath:r,resolver:s}}z();W();import Nr from"@swc/core";import Yt from"fs";import ve from"path";import{Visitor as zc}from"@swc/core/Visitor.js";var Bn=class extends zc{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),c=r.property.value||"?";return`${o}.${c}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},s=n(e.callee.object);if(s!=="?"&&t){if(this.calls.add(`${s}.${t}`),s==="axios"||s==="http"||this.axiosInstances.has(s)){let r=this.axiosInstances.get(s)||"";this.extractApiCall(t,e.arguments,r)}if((s.toLowerCase().includes("pubsub")||s==="pubSubClient"||s.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 c=o.expression;if(c.type==="ObjectExpression"){let a=c.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(a&&a.value?.type==="StringLiteral"){r=a.value.value;break}}if(c.type==="CallExpression"&&c.callee.type==="MemberExpression"&&c.callee.object.value==="JSON"&&c.callee.property.value==="stringify"&&c.arguments.length>0){let a=c.arguments[0].expression;if(a.type==="ObjectExpression"){let l=a.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 s=e.init.arguments[0]?.expression;if(s&&s.type==="ObjectExpression"){let r=s.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(s=>s.key.type==="Identifier"&&s.key.value==="url"||s.key.type==="StringLiteral"&&s.key.value==="url"),n=e.properties.find(s=>s.key.type==="Identifier"&&s.key.value==="method"||s.key.type==="StringLiteral"&&s.key.value==="method");if(t&&t.value){let s=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:s.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 s=t[0].expression,r=this.resolveUrlValue(s);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},vt=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,s;for(;(s=n.exec(e))!==null;){let r=s[1]||"",o=s[2],c=s[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=c.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:c.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,s;for(;(s=n.exec(e))!==null;){let r=s[1]||"",o=s[2],c=s[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=c.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:c.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,s;for(;(s=n.exec(e))!==null;)this.imports.set("*",s[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let c=o[1],a=o[2];c?(this.calls.add(`${c}.${a}`),(c.toLowerCase().includes("pubsub")||c==="pubSubClient")&&a!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:a})):this.calls.add(a)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,s;for(;(s=n.exec(e))!==null;)this.calls.add(s[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,s;for(;(s=n.exec(e))!==null;){let r=s[1],o=r.split("\\"),c=s[2]||o[o.length-1];this.imports.set(c,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,s;for(;(s=n.exec(e))!==null;){let c=s[1];s[2].split(",").map(l=>l.trim()).forEach(l=>{this.imports.set(l,c)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let c=o[1],a=c.split("."),l=a[a.length-1];this.imports.set(l,c)}}}};var Bc=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"]);function $r(i,e){let t=e,n=e.match(/\$\{([^}]+)\}/g);if(n)for(let p of n){let u=p.substring(2,p.length-1),d=i.configs.findEnvValue(u);d&&(t=t.replace(p,d))}let s=t.split("?")[0].split("#")[0];try{s.includes("://")&&(s=new URL(s).pathname)}catch{}s.length>1&&s.endsWith("/")&&(s=s.substring(0,s.length-1));let r=[],o=s.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),c=i.files.findSynapses({type:"api_route",name:o.includes("%")?o:s,direction:"consume",limit:10});for(let p of c){let u=p.name.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\*/g,"[^/]+");new RegExp(`^${u.replace(/\//g,"\\/")}$`).test(s.replace(/\*/g,"test-val"))&&r.push({file_path:p.file_path,start_line:p.line_number||0,signature:`[Synapse] ${p.name}`,score:1e3})}let a=s.split(/[^a-zA-Z0-9-_]/).filter(p=>p.length>=3&&!Bc.has(p.toLowerCase())&&!/^\d+$/.test(p));if(a.length>0){let u=[...a].sort((m,h)=>h.length-m.length)[0],d=i.exports.findRoutesByToken(u,20);for(let m of d){let h=50,g=(m.signature||m.name||"").toLowerCase();(m.name||"").toLowerCase().includes(s.replace(/\*/g,"").toLowerCase())&&(h+=200);for(let b of a)g.includes(b.toLowerCase())&&(h+=20);r.push({file_path:m.file_path,start_line:m.start_line,signature:`[Boundary] ${m.signature||m.name}`,capabilities:m.capabilities||void 0,score:h})}}if(r.length<3){let p=a.map(u=>u.replace(/[^a-zA-Z0-9_]/g,"")).filter(u=>u.length>0).join(" AND ");if(p.length>0){let u=i.content.search(p);for(let d of u){let m=0,h=d.file_path.toLowerCase(),g=d.snippet.toLowerCase();(h.includes("route")||h.includes("controller"))&&(m+=10),(h.includes("src/api")||h.includes("services/api"))&&(m+=5),(g.includes("addroute")||g.includes("@get"))&&(m+=15),(g.includes("axios.")||g.includes("fetch("))&&(m-=10),(h.includes(".spec.")||h.includes(".test."))&&(m-=20),m>0&&r.push({file_path:d.file_path,start_line:0,signature:`[FTS Match] ${d.snippet.replace(/\n/g," ")}`,score:m})}}}let l=new Map;return r.sort((p,u)=>u.score-p.score).forEach(p=>{l.has(p.file_path)||l.set(p.file_path,p)}),Array.from(l.values()).slice(0,3)}var Gc=4,Vt=50,qc=2,Jc=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"]);async function Ar(i){let{repoPath:e,filePath:t,symbolName:n}=Me(i);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let s=t;await G(e);let r=C.getInstance(e);if(!Yt.existsSync(s))return{isError:!0,content:[{type:"text",text:`File not found: ${s}`}]};let o,c=ve.basename(s),a;if(n){let d=r.exports.findByNameAndFile(n,s);if(d.length>0){let m=d[0];o={start:m.start_line,end:m.end_line},c=m.name,a=m.start_line}}let l={type:o?"function":"file",name:c,path:ve.relative(e,s),line:a,children:[]},p=new Set;p.add(s+(n?`:${n}`:""));let u={count:0,truncated:!1};return await Tt(s,l,e,r,p,1,u,o),u.truncated&&l.children.push({type:"function",name:"\u26A0\uFE0F Output Truncated",details:`Trace limited to ${Vt} nodes. Use summarize_file on specific files for deeper analysis.`,children:[]}),{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}async function Tt(i,e,t,n,s,r,o,c){if(!(r>Gc)){if(o.count>=Vt){o.truncated=!0;return}try{let a=Yt.readFileSync(i,"utf8"),l=ve.extname(i).toLowerCase(),u=(a.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
|
|
525
545
|
`);c&&(a=a.split(`
|
|
526
546
|
`).slice(c.start-1,c.end).join(`
|
|
527
|
-
`));let
|
|
528
|
-
${a}`:a,
|
|
547
|
+
`));let d;if(l===".ts"||l===".tsx"||l===".js"||l===".jsx"){d=new Bn;let _={syntax:"typescript",tsx:i.endsWith(".tsx"),target:"es2020"};try{let b=c?`${u}
|
|
548
|
+
${a}`:a,y=await Nr.parse(b,_);d.visitModule(y)}catch{if(c)try{let y=`${u}
|
|
529
549
|
class TraceContext {
|
|
530
550
|
${a}
|
|
531
|
-
}`,
|
|
532
|
-
`).filter(o=>o.trim()!=="");if(r.length===0)return;
|
|
533
|
-
`);for(let s of n){let[r,o]=s.split(" ");if(o){let c=this.getNote(o);c&&e.set(o,c)}}}catch{}return e}removeNote(e){try{
|
|
534
|
-
\u269B\uFE0F Hologram: Refreshed architectural map (${
|
|
535
|
-
\u2728 Nano-Repair: Fixed ${s.repaired} links.`),c.missionsRecovered>0&&(
|
|
536
|
-
\u{1F9EC} Re-hydration: Recovered ${c.missionsRecovered} missions.`),{content:[{type:"text",text:
|
|
537
|
-
|
|
538
|
-
`;return o.length===0&&c.length===0?
|
|
539
|
-
`:(o.length>0&&(
|
|
540
|
-
`,o.forEach(u
|
|
541
|
-
`),
|
|
542
|
-
`),c.length>0&&(
|
|
543
|
-
`,c.forEach(u
|
|
544
|
-
`),
|
|
545
|
-
`)),{content:[{type:"text",text:
|
|
546
|
-
\u{1F3D7}\uFE0F Architecture Summary for ${
|
|
551
|
+
}`,E=await Nr.parse(y,_);d.visitModule(E)}catch{let E=new vt,w=l;E.visit(a,w),d.calls=E.calls,d.apiCalls=E.apiCalls,d.imports=E.imports}else{let y=new vt;y.visit(a,l),d.calls=y.calls,d.apiCalls=y.apiCalls,d.imports=y.imports}}}else d=new vt,d.visit(a,l);S.info({file:ve.basename(i),calls:d.calls.size,apiCalls:d.apiCalls.length,depth:r},"Analyzed file");let m=d.apiCalls.slice(0,10);for(let _ of m){if(o.count>=Vt)break;if(o.count++,_.method==="PUBSUB"){let w={type:"event_trigger",name:`PubSub Event: ${_.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(w);let x=n.exports.findByNameGlobal(_.url).concat(n.exports.findByMethodName(_.url));if(_.url.length>10){let k=_.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(k!==_.url){let N=n.exports.findByNameGlobal(k).concat(n.exports.findByMethodName(k));x.push(...N)}}let v=new Set;for(let k of x){if(v.has(k.file_path)||k.file_path===i)continue;if(v.add(k.file_path),o.count>=Vt)break;o.count++;let N={type:"subscriber",name:`${k.name} (${ve.basename(k.file_path)})`,path:ve.relative(t,k.file_path),line:k.start_line,details:"Potential Subscriber / Handler",children:[]};w.children.push(N),Yt.existsSync(k.file_path)&&!s.has(k.file_path)&&(s.add(k.file_path),await Tt(k.file_path,N,t,n,s,r+1,o))}continue}let b={type:"api_call",name:`${_.method} ${_.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(b);let E=$r(n,_.url).slice(0,qc);for(let w of E){if(o.count>=Vt)break;o.count++;let x={type:"route",name:w.signature||"Route Handler",path:w.file_path,line:w.start_line,children:[]};if(b.children.push(x),Yt.existsSync(w.file_path)&&!s.has(w.file_path)&&(s.add(w.file_path),await Tt(w.file_path,x,t,n,s,r+1,o)),w.capabilities)try{let v=JSON.parse(w.capabilities);if(v.handler){let[k,N]=v.handler.split("@");if(k){let T=k.split("\\").pop();if(T){let I=n.exports.findClassByName(T);if(I){let U=n.exports.findByNameAndFile(N||"",I.file_path),H,P=I.start_line;U.length>0&&(H={start:U[0].start_line,end:U[0].end_line},P=U[0].start_line);let R={type:"component",name:`${T}${N?" :: "+N:""}`,path:ve.relative(t,I.file_path),line:P,details:"Controller Logic (Macro IR)",children:[]};x.children.push(R),s.has(I.file_path+(N?`:${N}`:""))||(s.add(I.file_path+(N?`:${N}`:"")),await Tt(I.file_path,R,t,n,s,r+1,o,H))}}}}}catch{}}}let h=d.calls,g=Array.from(h).sort();for(let _ of g)if(d.imports.has(_)){let b=d.imports.get(_);if(!b.startsWith(".")){if(["react","react-dom"].includes(b))continue;e.children.push({type:"function",name:_,details:`External: ${b}`,children:[]});continue}let y=lt(b,i,t);if(y&&Yt.existsSync(y))if(s.has(y))e.children.push({type:"function",name:_,details:"Circular / Already Visited",path:ve.relative(t,y),children:[]});else{s.add(y);let E={type:"file",name:_,details:`Imported from ${ve.basename(y)}`,path:ve.relative(t,y),children:[]};e.children.push(E),await Tt(y,E,t,n,s,r+1,o)}}else if(!["log","info","error","warn","print"].includes(_)){let b=n.exports.findByNameGlobal(_);if(b.length===0){let y=_.split(/(?:\.|->|::)+/);if(y.length>1){let E=y[y.length-1];Jc.has(E)||(b=n.exports.findByMethodName(E))}}if(b.length>0){let y=b.find(w=>w.file_path===i),E=y||(b.length===1?b[0]:null);if(E){let w=`${E.file_path}:${E.name}`;if(!s.has(w)){s.add(w);let x={type:"component",name:_,details:`Resolved via global index${y?" (local)":""}`,path:ve.relative(t,E.file_path),line:E.start_line,children:[]};e.children.push(x),await Tt(E.file_path,x,t,n,s,r+1,o,{start:E.start_line,end:E.end_line})}}}}}catch(a){S.error({filePath:i,error:a.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:a.message,children:[]})}}}async function Pr(i,e){let t=Gn.resolve(e.dir),n=Gn.isAbsolute(i)?i:Gn.resolve(t,i);await B(async()=>{se("Execution Trace");let s=be();s.start(`Tracing ${f.cyan(e.symbolName||Gn.basename(n))}...`);try{let r=await Ar({repoPath:t,filePath:n,symbolName:e.symbolName});s.stop("Trace complete."),r.isError?console.error(f.red(r.content[0].text)):X("Flow Results",r.content[0].text,"magenta")}catch(r){throw s.stop(`Trace failed: ${r.message}`),r}finally{await J(t)}})}import sl from"path";z();Rt();W();import{execSync as uo}from"child_process";import nl from"path";var qn=S.child({module:"shadow-trace"}),kt=class{intentLogs;exports;repoPath;hologramService;constructor(e){let{intentLogs:t,exports:n}=C.getInstance(e);this.intentLogs=t,this.exports=n,this.repoPath=e,this.hologramService=new ge(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=uo(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
|
|
552
|
+
`).filter(o=>o.trim()!=="");if(r.length===0)return;qn.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let c=nl.join(this.repoPath,o),l=uo(`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(c,u);d&&(this.intentLogs.create({mission_id:0,file_path:c,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}),qn.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),qn.info("Shadow Trace complete.")}catch(s){qn.warn({err:s.message},"Shadow Trace failed: git diff error.")}}};z();import{execSync as It}from"child_process";var Jn=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{It(`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 It(`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=It(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
|
|
553
|
+
`);for(let s of n){let[r,o]=s.split(" ");if(o){let c=this.getNote(o);c&&e.set(o,c)}}}catch{}return e}removeNote(e){try{It(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{It(`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{It(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};W();var Ct=S.child({module:"persistence-service"}),Re=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new Jn(e)}async syncMissionToGitNotes(e){let{missions:t,intentLogs:n}=C.getInstance(this.repoPath),s=t.findById(e);if(!s)throw new Error(`Mission ${e} not found`);if(!s.commit_sha){Ct.warn({missionId:e},"Cannot sync mission without commit_sha");return}Ct.info({missionId:e,commitSha:s.commit_sha},"Syncing mission to Git Notes");let r=t.getArtifacts(e),o=n.findByMission(e,1e3),c=o.find(p=>p.type==="adr"),a=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:s.name,goal:s.goal,status:s.status,strategy_graph:s.strategy_graph,git_branch:s.git_branch,commit_sha:s.commit_sha,parent_id:s.parent_id,verification_context:s.verification_context,outcome_contract:s.outcome_contract,created_at:s.created_at,updated_at:s.updated_at},artifacts:r,adr:c?c.content:null,decisions:a};this.gitNotes.addNote(s.commit_sha,JSON.stringify(l,null,2))}async syncAllToGitNotes(){let{missions:e}=C.getInstance(this.repoPath),t=e.findActive(),n=e.findRecentCompleted(10),s=[...t,...n];for(let r of s)try{await this.syncMissionToGitNotes(r.id)}catch(o){Ct.error({missionId:r.id,error:o},"Failed to sync mission")}}async recoverFromGitNotes(){let e=this.gitNotes.listNotes(),{missions:t,intentLogs:n}=C.getInstance(this.repoPath),s=0,r=0;for(let[o,c]of e.entries())try{let a=JSON.parse(c);if(a.version!=="1.0")continue;if(t.findByCommitShas([o]).some(d=>d.name===a.mission.name)){Ct.debug({commitSha:o,missionName:a.mission.name},"Mission already exists, skipping recovery");continue}let u=t.create({name:a.mission.name,goal:a.mission.goal,status:a.mission.status,strategy_graph:a.mission.strategy_graph,git_branch:a.mission.git_branch,commit_sha:o,parent_id:a.mission.parent_id,verification_context:a.mission.verification_context,outcome_contract:a.mission.outcome_contract});if(s++,a.adr&&(n.create({mission_id:Number(u),symbol_id:null,file_path:null,type:"adr",content:a.adr,confidence:1,symbol_name:null,signature:null,commit_sha:o}),r++),a.decisions&&a.decisions.length>0)for(let d of a.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++;Ct.info({commitSha:o,missionName:a.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(a){Ct.error({commitSha:o,error:a},"Failed to parse Git Note for recovery")}return{missionsRecovered:s,logsRecovered:r}}};z();Kt();async function mo(i){let{repoPath:e}=i;try{await G(e),new kt(e).analyzeGhostChanges();let n=new Pe(e),s=n.detectAndRepairShifts(),r=n.syncLifecycle(),c=await new Re(e).recoverFromGitNotes(),{HologramService:a}=await Promise.resolve().then(()=>(Rt(),po)),l=new a(e),p=Ze(C.getInstance(e),e);l.updateTopography(p);let u=l.computeGravityZones();l.updateGravityZones(u);let d="Shadow Sync complete. Code changes indexed and intent logs updated.";return d+=`
|
|
554
|
+
\u269B\uFE0F Hologram: Refreshed architectural map (${u.length} hotspots).`,s.repaired>0&&(d+=`
|
|
555
|
+
\u2728 Nano-Repair: Fixed ${s.repaired} links.`),c.missionsRecovered>0&&(d+=`
|
|
556
|
+
\u{1F9EC} Re-hydration: Recovered ${c.missionsRecovered} missions.`),{content:[{type:"text",text:d}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}async function ho(i,e){let t=sl.resolve(i);await B(async()=>{se("Shadow Sync");let n=be();n.start("Synchronizing intelligence lifecycle...");try{let s=await mo({repoPath:t});n.stop("Sync complete."),s.isError?console.error(f.red(s.content[0].text)):(console.log(""),console.log(s.content[0].text),console.log(""))}catch(s){throw n.stop(`Sync failed: ${s.message}`),s}finally{await J(t)}})}Kt();z();W();Rt();import go from"path";z();Kt();Rt();import Ue from"path";async function fo(i){let{repoPath:e}=i;await G(e);let t=C.getInstance(e),n=Ze(t,e),r=new ge(e).getSnapshot(),o=[],c=[],a=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 a){let m=Ue.isAbsolute(d)?d:Ue.join(e,d),h=t.imports.findByFile(m);for(let g of h)g.resolved_path&&l.has(Ue.relative(e,g.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${Ue.relative(e,d)}\` directly imports Data layer \`${Ue.relative(e,g.resolved_path)}\`. Should go through Logic.`)}let p=r.gravity?.hotspots||[];for(let d of p){let m=Qt(d.filePath,t);(m.layer==="Utility"||m.layer==="Unknown")&&d.gravity>50&&c.push(`\u{1F6A8} GRAVITY ANOMALY: \`${Ue.relative(e,d.filePath)}\` has high gravity (${d.gravity.toFixed(0)}) but is classified as ${m.layer}. Consider promoting to Core Logic.`)}for(let d of a){let m=Ue.isAbsolute(d)?d:Ue.join(e,d),h=t.exports.findByFile(m);h.length>10&&c.push(`\u{1F388} ENTRY BLOAT: \`${Ue.relative(e,d)}\` exports ${h.length} symbols. Entry handlers should be thin interfaces.`)}let u=`# \u{1F575}\uFE0F Architectural Scout Report
|
|
557
|
+
|
|
558
|
+
`;return o.length===0&&c.length===0?u+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
|
|
559
|
+
`:(o.length>0&&(u+=`## \u274C Structural Violations
|
|
560
|
+
`,o.forEach(d=>u+=`- ${d}
|
|
561
|
+
`),u+=`
|
|
562
|
+
`),c.length>0&&(u+=`## \u26A0\uFE0F Architectural Warnings
|
|
563
|
+
`,c.forEach(d=>u+=`- ${d}
|
|
564
|
+
`),u+=`
|
|
565
|
+
`)),{content:[{type:"text",text:u}]}}async function yo(i,e,t){let n=e?go.resolve(process.cwd(),e):process.cwd();if(i==="init"){S.info('Running full initialization (same as "index --force")...'),await G(n,void 0,!0,!0);return}if(i==="tree"){S.info('For tree view, please use the "tree" command.');return}if(i==="topography"){await G(n);let s=C.getInstance(n),r=Ze(s,n);console.log(`
|
|
566
|
+
\u{1F3D7}\uFE0F Architecture Summary for ${go.basename(n)}
|
|
547
567
|
`),console.log(`Detected Pattern: **${r.pattern}** (Confidence: ${r.patternConfidence.toFixed(0)}%)`),r.insights.length>0&&(console.log(`
|
|
548
568
|
Insights:`),r.insights.forEach(l=>console.log(`- ${l}`))),console.log(`
|
|
549
|
-
Layer Distribution:`);let o=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],c=Object.values(r.layers).reduce((l,p)=>l+p.count,0),a=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],
|
|
569
|
+
Layer Distribution:`);let o=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],c=Object.values(r.layers).reduce((l,p)=>l+p.count,0),a=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=c>0?(p.count/c*100).toFixed(1):"0.0";console.log(`${a(l)} ${l.padEnd(14)} | ${p.count.toString().padStart(5)} files | ${u}%`)}),console.log(`
|
|
550
570
|
Top Files by Layer:`),o.forEach(l=>{let p=r.layers[l];p.count!==0&&(console.log(`
|
|
551
|
-
${a(l)} ${l}`),p.topFiles.forEach(
|
|
552
|
-
`),o=new Array(r.length).fill(0);for(let
|
|
553
|
-
`).trim();return c>0&&(
|
|
554
|
-
`+
|
|
555
|
-
...`),
|
|
571
|
+
${a(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(i==="scout"){let s=await fo({repoPath:n});console.log(s.content[0].text);return}if(i==="hologram"){let s=new ge(n);console.log(JSON.stringify(s.getSnapshot(),null,2));return}S.error(`Unknown recon mode: ${i}. Available: init, topography, scout, hologram`)}import nn from"path";z();var Xt=class{static extractSnippet(e,t,n=300){if(!e||!t)return"";let s=t.toLowerCase().split(/\s+/).filter(d=>d.length>2&&!["the","and","for","with","from"].includes(d));if(s.length===0)return e.slice(0,n)+"...";let r=e.split(`
|
|
572
|
+
`),o=new Array(r.length).fill(0);for(let d=0;d<r.length;d++){let m=r[d].toLowerCase(),h=0,g=0;for(let _ of s)m.includes(_)&&(h++,g++);(m.includes("export ")||m.includes("class ")||m.includes("function ")||m.includes("interface "))&&(h+=1),o[d]=g*10+h}let c=0,a=-1,l=5;for(let d=0;d<=r.length-l;d++){let m=0;for(let h=0;h<l;h++)m+=o[d+h];m>a&&(a=m,c=d)}if(a<=0)return e.slice(0,n).trim()+"...";let u=r.slice(c,c+l).join(`
|
|
573
|
+
`).trim();return c>0&&(u=`...
|
|
574
|
+
`+u),c+l<r.length&&(u=u+`
|
|
575
|
+
...`),u.length>n?u.slice(0,n)+"...":u}static calculateLexicalScore(e,t){if(!e||!t)return 0;let n=t.toLowerCase().split(/\s+/).filter(o=>o.length>2&&!["the","and","for","with","from"].includes(o));if(n.length===0)return 0;let s=0,r=e.toLowerCase();for(let o of n)if(r.includes(o)){s+=1;let c=new RegExp(`\\b${o}`,"gi"),a=r.match(c);a&&(s+=Math.min(a.length*.2,2)),new RegExp(`(class|function|export|interface|enum|type)\\s+${o}`,"i").test(e)&&(s+=1.5)}return s/n.length}};rt();z();W();var et=S.child({module:"clean-sweep"}),Us=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=C.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){et.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();et.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++,et.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,et.debug({logId:o.id},"Deleted orphaned log"));let s=this.intentLogs.findLogsForMissingFiles();for(let o of s)this.intentLogs.delete(o.id),e++;let r=this.intentLogs.findRecentDecisionActivity(1e3).length;return et.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},js=class{lambda;constructor(e=.01){this.lambda=e}calculateScore(e,t){let s=(Math.floor(Date.now()/1e3)-t)/(3600*24),r=Math.exp(-this.lambda*s);return e*r}scoreResults(e){return e.map(t=>({...t,decayed_score:this.calculateScore(t.score,t.created_at)}))}},zs=class{missions;constructor(e){let{missions:t}=C.getInstance(e);this.missions=t}findColdMissions(){let e=Math.floor(Date.now()/1e3)-604800,t=this.missions.findColdMissions(e,10);return et.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},Yn=class{pruner;scorer;compactor;constructor(e){this.pruner=new Us(e),this.scorer=new js,this.compactor=new zs(e)}runMaintenance(){et.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return et.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};z();W();var bo=S.child({module:"lineage-service"}),Zt=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=gr(this.repoPath,e);if(t.length===0)return[];let{missions:n}=C.getInstance(this.repoPath),r=n.findByCommitShas(t).map(o=>o.id);return r.length>0&&bo.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return bo.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var il={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},ke=class{static classify(e,t){let n=e.toLowerCase();if(t?.content){let s=t.content;if(s.includes("describe(")||s.includes("test(")||s.includes("it(")||s.includes("expect(")||s.includes('from "@jest/globals"')||s.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(s=>s.kind==="ClassDeclaration"||s.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 il[n]}};W();function rl(i,e){let t=[];for(let n=0;n<=e.length;n++)t[n]=[n];for(let n=0;n<=i.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=i.length;s++)e.charAt(n-1)===i.charAt(s-1)?t[n][s]=t[n-1][s-1]:t[n][s]=Math.min(t[n-1][s-1]+1,t[n][s-1]+1,t[n-1][s]+1);return t[e.length][i.length]}function ol(i,e){let t=rl(i.toLowerCase(),e.toLowerCase()),n=Math.max(i.length,e.length);return Math.round((n-t)/n*100)}function _o(i){let e=[],t="";for(let n=0;n<i.length;n++){let s=i[n],r=s>="A"&&s<="Z",o=s>="a"&&s<="z";r&&t.length>0?(e.push(t),t=s):o||r?t+=s:t.length>0&&(e.push(t),t="")}return t.length>0&&e.push(t),e}function al(i,e){let t=_o(e),n=i.toLowerCase();if(t.map(o=>o[0].toLowerCase()).join("")===n)return!0;let r=0;for(let o of t){if(r>=i.length)break;let c=o.toLowerCase();if(c.startsWith(n.slice(r))){r=i.length;break}c[0]===n[r]&&r++}return r===i.length}function cl(i,e){return _o(e).map(s=>s[0].toLowerCase()).join("")===i.toLowerCase()}function ll(i,e){let t=i.toLowerCase(),n=e.toLowerCase();if(i===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+i.length/e.length*8};if(n.endsWith(t))return{matchType:"suffix",score:80+i.length/e.length*8};if(n.includes(t)){let r=i.length/e.length,o=n.indexOf(t)/e.length;return{matchType:"substring",score:70+r*10-o*5}}return cl(i,e)?{matchType:"acronym",score:75}:al(i,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:ol(i,e)*.6}}function en(i,e,t=50,n=5){let s=[];for(let r of e){let{matchType:o,score:c}=ll(i,r);if(c>=t){let l={exact:1e3,"exact-case-insensitive":900,prefix:800,suffix:700,substring:600,acronym:550,"camel-case":500,levenshtein:100}[o]+c;s.push({match:r,score:c,matchType:o,rank:l})}}return s.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),s.slice(0,n)}Rt();var tt=class i{constructor(e){this.repoPath=e}get filesRepo(){return C.getInstance(this.repoPath).files}get exportsRepo(){return C.getInstance(this.repoPath).exports}get intentLogsRepo(){return C.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,s){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=s!=null?ke.mapClassificationToTier(s):ke.classify(e);if(t.layer!=null&&r!==t.layer||t.excludeLayers?.includes(r))return!1}return!0}async searchByPath(e,t,n,s,r,o=!1){let c=e.toLowerCase().split(/\s+/).filter(Boolean),a=this.filesRepo.findByPathKeywords(c,Math.min((t??50)*(r?me.FILTERED_QUERY_LIMIT_MULTIPLIER:1),Et.MAX_LIMIT));r&&(a=a.filter(u=>i.matchesFilters(u.path,s,u.mtime,u.classification)),a=a.slice(0,t??50));let l=u=>u.replace(this.repoPath,"").replace(/^\//,"");if(a.length===0)return{content:[{type:"text",text:`No indexed files match path/filename: "${e}".
|
|
556
576
|
|
|
557
|
-
If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};if(o){let
|
|
577
|
+
If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};if(o){let d=new ge(this.repoPath).getSection("gravity"),m=new Map;if(d?.hotspots)for(let _ of d.hotspots){let b=m.get(_.filePath)||0;m.set(_.filePath,b+_.gravity)}let h=a.map(_=>{let b=m.get(_.path)||0,y=_.classification?ke.mapClassificationToTier(_.classification):ke.classify(_.path);return{..._,gravity:b,layer:y}});return h.sort((_,b)=>b.gravity-_.gravity),{content:[{type:"text",text:`# Resolved paths: "${e}" (Ranked by Gravity)
|
|
558
578
|
|
|
559
|
-
${
|
|
579
|
+
${h.length} file(s):
|
|
560
580
|
|
|
561
|
-
`+
|
|
581
|
+
`+h.map((_,b)=>{let y=_.gravity>50?" \u269B\uFE0F":_.gravity>0?" \u2022":"",E=_.gravity>0?` [G:${Math.round(_.gravity)}]`:"";return`${b+1}. \`${l(_.path)}\` (${_.layer})${y}${E}`}).join(`
|
|
562
582
|
`)+`
|
|
563
583
|
|
|
564
584
|
> **Legend**: \u269B\uFE0F = High-gravity hotspot (>50), \u2022 = Has gravity, G = Gravity score`}]}}return{content:[{type:"text",text:`# Resolved paths: "${e}"
|
|
565
585
|
|
|
566
586
|
${a.length} file(s):
|
|
567
587
|
|
|
568
|
-
`+a.map((d
|
|
569
|
-
`)}]}}async searchByConcept(e,t,n,s,r,o=!1){
|
|
570
|
-
> **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",
|
|
571
|
-
> _Compact mode: snippets omitted_`:
|
|
588
|
+
`+a.map((u,d)=>`${d+1}. \`${l(u.path)}\`${u.classification?` (${u.classification})`:""}`).join(`
|
|
589
|
+
`)}]}}async searchByConcept(e,t,n,s,r,o=!1){S.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let c=await gn(e),a=y=>y.replace(this.repoPath,"").replace(/^\//,"");if(c){let y=await this.findConceptMatches(e,c,s,r,t*2,0),E=this.findIntentLogMatches(c,5);if(y.length>0||E.length>0){let w=y.length,x=y.slice(n,n+t),k=n+t<w?`
|
|
590
|
+
> **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",N=o?`
|
|
591
|
+
> _Compact mode: snippets omitted_`:w>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",O=`# Semantic Concept Search: "${e}"
|
|
572
592
|
|
|
573
|
-
Showing ${
|
|
593
|
+
Showing ${x.length} of ${w} relevant file(s) (offset: ${n}, limit: ${t})${k}${N}
|
|
574
594
|
|
|
575
|
-
`,
|
|
576
|
-
`):
|
|
577
|
-
> \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${
|
|
578
|
-
> **Rationale**: ${
|
|
595
|
+
`,I=new ge(this.repoPath).getSection("gravity"),U=new Map;if(I?.hotspots)for(let P of I.hotspots)U.set(P.filePath,P.gravity);let H=o?O+x.map((P,R)=>{let A=a(P.path),D=Math.round((P.decayedScore||0)*100),L=U.get(P.path)?" \u269B\uFE0F":"";return`${n+R+1}. \`${A}\`${L} (${D}%) - ${P.summary||"No summary"}`}).join(`
|
|
596
|
+
`):O+x.map((P,R)=>{let A=a(P.path),D=Math.round((P.decayedScore||0)*100),$=U.get(P.path),L=$?" \u269B\uFE0F **CORE**":"",Y=$&&$>50?`
|
|
597
|
+
> \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${$.toFixed(0)}). Modifications may have significant architectural impact.`:"";return`## ${n+R+1}. ${A}${L} (${D}% Match)
|
|
598
|
+
> **Rationale**: ${P.rationale}${Y}
|
|
579
599
|
|
|
580
|
-
`+(
|
|
600
|
+
`+(P.snippet?`**Matched Snippet**:
|
|
581
601
|
\`\`\`typescript
|
|
582
|
-
${
|
|
602
|
+
${P.snippet}
|
|
583
603
|
\`\`\`
|
|
584
604
|
|
|
585
|
-
`:"")+`**Summary**: ${
|
|
605
|
+
`:"")+`**Summary**: ${P.summary||"No summary available"}
|
|
586
606
|
`}).join(`
|
|
587
|
-
`)
|
|
607
|
+
`);return E.length>0&&(H+=`
|
|
608
|
+
|
|
609
|
+
---
|
|
610
|
+
## Intent Vectors (${E.length} matching decision(s))
|
|
588
611
|
|
|
589
|
-
|
|
612
|
+
`,H+=E.map((P,R)=>{let A=Math.round((P.score||0)*100),D=P.symbolName?` \`${P.symbolName}\``:"",$=P.missionId?` [Mission #${P.missionId}]`:"",L=P.content.length>200?P.content.slice(0,200)+"...":P.content;return o?`${R+1}. **[${P.type}]**${D}${$} (${A}%) - ${L}`:`### ${R+1}. [${P.type}]${D}${$} (${A}% Match)
|
|
613
|
+
> ${L}
|
|
614
|
+
`}).join(`
|
|
615
|
+
`)),{content:[{type:"text",text:H}]}}}let l=e.replace(/[^\w\s]/g," ").trim(),p=this.filesRepo.findFts(l,(t+n)*(r?me.FILTERED_QUERY_LIMIT_MULTIPLIER:1));r&&(p=p.filter(y=>i.matchesFilters(y.path,s,y.mtime,y.classification)));let u=p.slice(n,n+t);if(u.length===0&&n===0){let y=this.filesRepo.getStats(),E=e.toLowerCase().split(/\s+/),w=this.filesRepo.findByPathKeywords(E,t);return r&&(w=w.filter(x=>i.matchesFilters(x.path,s,x.mtime,x.classification))),w.length>0?{content:[{type:"text",text:`# Concept Search: "${e}"
|
|
590
616
|
|
|
591
|
-
|
|
617
|
+
\u26A0\uFE0F No semantic matches in file summaries (${y.withSummary}/${y.total} indexed).
|
|
592
618
|
|
|
593
|
-
|
|
619
|
+
Found ${w.length} file(s) with matching paths:
|
|
620
|
+
|
|
621
|
+
`+w.map((v,k)=>`${k+1}. \`${a(v.path)}\` (${v.classification||"Unknown"})`).join(`
|
|
594
622
|
`)}]}:{content:[{type:"text",text:`No files found matching concept: "${e}"
|
|
595
623
|
|
|
596
|
-
Summary Stats: ${
|
|
624
|
+
Summary Stats: ${y.withSummary}/${y.total} summaries.
|
|
597
625
|
|
|
598
|
-
Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}let
|
|
599
|
-
> Use \`offset: ${n+t}\` for more results.`:"",
|
|
600
|
-
> _Compact mode_`:
|
|
626
|
+
Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}let d=p.length,h=n+t<d?`
|
|
627
|
+
> Use \`offset: ${n+t}\` for more results.`:"",g=o?`
|
|
628
|
+
> _Compact mode_`:d>20&&!o?"\n> \u{1F4A1} Use `compact: true` to reduce output size.":"",_=`# Concept Search (FTS Fallback): "${e}"
|
|
601
629
|
|
|
602
|
-
Showing ${
|
|
630
|
+
Showing ${u.length} of ${d} relevant file(s)${h}${g}
|
|
603
631
|
|
|
604
|
-
`;return{content:[{type:"text",text:o?
|
|
605
|
-
`):
|
|
632
|
+
`;return{content:[{type:"text",text:o?_+u.map((y,E)=>`${n+E+1}. \`${a(y.path)}\``).join(`
|
|
633
|
+
`):_+u.map((y,E)=>`## ${n+E+1}. ${a(y.path)}
|
|
606
634
|
|
|
607
|
-
**Summary**: ${
|
|
635
|
+
**Summary**: ${y.summary||"No summary available"}
|
|
608
636
|
`).join(`
|
|
609
|
-
`)}]}}async searchBySymbol(e,t,n,s,r,o="any"){let c=e.toLowerCase(),a=
|
|
637
|
+
`)}]}}async searchBySymbol(e,t,n,s,r,o="any"){let c=e.toLowerCase(),a=T=>T.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 T=this.exportsRepo.getAllNames(5e3),I=e.trim().split(/\s+/).filter(H=>H.length>0);if(I.length>1){let H=new Map;for(let R of I){let A=en(R,T,40,20);for(let D of A){let $=H.get(D.match);$?($.terms.push(R),$.bestScore=Math.max($.bestScore,D.score)):H.set(D.match,{terms:[R],bestScore:D.score})}}let P=Array.from(H.entries()).sort((R,A)=>A[1].terms.length!==R[1].terms.length?A[1].terms.length-R[1].terms.length:A[1].bestScore-R[1].bestScore).slice(0,10);if(P.length>0){let R=P.map(([A,D])=>{let $=D.terms.join(", ");return` \u2022 \`${A}\` (matches: ${$}, ${Math.round(D.bestScore)}%)`}).join(`
|
|
610
638
|
`);return{content:[{type:"text",text:`No symbols found matching all terms: "${e}"
|
|
611
639
|
|
|
612
640
|
**Partial matches:**
|
|
613
|
-
${
|
|
641
|
+
${R}
|
|
614
642
|
|
|
615
|
-
\u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let
|
|
643
|
+
\u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let H=en(e,T,50,5);if(H.length>0){let P=H.map(R=>` \u2022 \`${R.match}\` (${Math.round(R.score)}% ${R.matchType} match)`).join(`
|
|
616
644
|
`);return{content:[{type:"text",text:`No symbols found matching: "${e}"
|
|
617
645
|
|
|
618
646
|
**Did you mean?**
|
|
619
|
-
${
|
|
647
|
+
${P}
|
|
620
648
|
|
|
621
649
|
\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}"
|
|
622
650
|
|
|
623
|
-
\u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(
|
|
624
|
-
`);
|
|
625
|
-
`).trim()}let
|
|
651
|
+
\u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(T=>{let I=this.filesRepo.findByPath(T.file_path);return i.matchesFilters(T.file_path,s,I?.mtime,I?.classification)}));let u=new Zt(this.repoPath),d=new ge(this.repoPath),m=u.getAncestorMissionIds(),h=ce(this.repoPath)||void 0,g=this.exportsRepo.getGravityMap(m,h),_=d.getSection("gravity"),b=new Map;if(_?.hotspots)for(let T of _.hotspots)b.set(`${T.filePath}::${T.symbol}`,T.gravity);let y="\u{1F525}",E="\u26A1",w="\u269B\uFE0F",x=p.map((T,I)=>{let U=g[T.id],H=b.get(`${T.file_path}::${T.name}`),P=this.filesRepo.findByPath(T.file_path),R=ke.getMultiplier(T.file_path,P?.classification),A=(me.SCORE_BASE-I)*R;U&&(A+=U.score*me.SCORE_BASE),H&&(A+=H*me.SCORE_BASE*me.GRAVITY_STRUCTURAL_WEIGHT),T.name.toLowerCase()===c&&(A+=me.EXACT_MATCH_BONUS*R);let D=P?.mtime;if(D!=null){let L=D>1e10?D/1e3:D,Y=(Date.now()/1e3-L)/ks.SECONDS_PER_DAY;Y<me.RECENT_FILE_THRESHOLD_DAYS?A+=me.RECENT_FILE_BOOST:Y<me.OLDER_FILE_THRESHOLD_DAYS&&(A+=me.OLDER_FILE_BOOST)}let $=[];return U&&$.push(...U.reasons),H&&$.push(`Structural Hotspot (Gravity: ${H.toFixed(1)})`),{...T,activeGravity:U,structuralGravity:H,sortScore:A,reasons:$}}).sort((T,I)=>I.sortScore-T.sortScore).slice(n,n+t),v=p.length,k=n+t<v,N=x.map((T,I)=>{let U=a(T.file_path),H=this.filesRepo.getContent(T.file_path),P="";if(H){let D=H.split(`
|
|
652
|
+
`);P=D.slice(Math.max(0,T.start_line-2),Math.min(D.length,T.start_line+3)).join(`
|
|
653
|
+
`).trim()}let R=[];T.activeGravity&&(T.activeGravity.reasons.some(D=>D.includes("Working Set"))?R.push(y):T.activeGravity.reasons.some(D=>D.includes("Recent Intent"))&&R.push(E)),T.structuralGravity&&R.push(w);let A=R.length>0?` ${R.join("")}`:"";return{relPath:U,name:T.name,kind:T.kind,signature:T.signature,line:T.start_line,snippet:P,badgeStr:A,gravityReasons:T.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
|
|
626
654
|
|
|
627
|
-
Showing ${
|
|
655
|
+
Showing ${N.length} matching symbol(s)${k?` (use offset=${n+t} for more)`:""}:
|
|
628
656
|
|
|
629
|
-
`+
|
|
630
|
-
**File**: \`${
|
|
631
|
-
`;return
|
|
632
|
-
`),
|
|
633
|
-
`),
|
|
657
|
+
`+N.map((T,I)=>{let U=`## ${n+I+1}. \`${T.name}\` (${T.kind})${T.badgeStr}
|
|
658
|
+
**File**: \`${T.relPath}:${T.line}\`
|
|
659
|
+
`;return T.gravityReasons&&(U+=`> *${T.gravityReasons.join(", ")}*
|
|
660
|
+
`),T.signature&&(U+=`**Signature**: \`${T.signature}\`
|
|
661
|
+
`),T.snippet&&(U+=`
|
|
634
662
|
\`\`\`typescript
|
|
635
|
-
${
|
|
663
|
+
${T.snippet}
|
|
636
664
|
\`\`\`
|
|
637
|
-
`),
|
|
638
|
-
`)}]}}async findConceptMatches(e,t,n,s,r,o=0){let c=
|
|
665
|
+
`),U}).join(`
|
|
666
|
+
`)}]}}async findConceptMatches(e,t,n,s,r,o=0){let c=ce(this.repoPath)||void 0;if(!t)return[];let a=this.filesRepo.findWithEmbeddings(),p=new Yn(this.repoPath).getScorer(),d=new Zt(this.repoPath).getAncestorMissionIds(),m=[];for(let g of a)try{let _=JSON.parse(g.embedding),b=Ft(t,_),y=this.filesRepo.getContent(g.path),E=me.ENABLE_LEXICAL_SCORING&&y?Xt.calculateLexicalScore(y,e):0,w=1;if(y){let v=/\b(class|function|const|let|var|enum)\s+\w+/.test(y);if(/export\s+/.test(y)&&!v){let N=y.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");/\b(class|function|const|let|var|enum)\s+\w+/.test(N)||(w=.1)}}let x=E>0?.1:.18;if(b>x){if(s&&!i.matchesFilters(g.path,n,g.mtime,g.classification))continue;let v=g.mtime>2e9?Math.floor(g.mtime/1e3):g.mtime,k=Math.floor(Date.now()/1e3)-ks.SECONDS_PER_YEAR,N=ke.getMultiplier(g.path,g.classification),O=p.calculateScore(b,v||k);O*=N;let I=this.filesRepo.getGravityMap(d,c)[g.path],U=g.classification?ke.mapClassificationToTier(g.classification):ke.classify(g.path,{content:y??void 0}),H=`Similarity: ${(b*100).toFixed(0)}%, Tier: ${U}${N!==1?` (${N}x)`:""}`;E>0&&(O+=E*me.LEXICAL_WEIGHT,H+=` | Lexical: +${E.toFixed(1)}`),I&&(O+=I.score,H+=` | \u{1F525} Gravity: +${I.score.toFixed(1)} (${I.reasons.join(", ")})`),w<1&&(O*=w,H+=` | \u{1F4C9} Barrel: x${w}`);let P=y?Xt.extractSnippet(y,e):void 0;m.push({path:g.path,summary:g.summary||"",score:b,decayedScore:O,rationale:H,snippet:P})}}catch{}let h=new Map;for(let g of m){let _=g.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();_&&_.length>3&&(h.has(_)||h.set(_,[]),h.get(_).push(g))}for(let[g,_]of h.entries())if(new Set(_.map(y=>y.path.split(".").pop())).size>1)for(let y of _)y.decayedScore=(y.decayedScore||0)+.15,y.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${g}')`;return m.sort((g,_)=>(_.decayedScore||0)-(g.decayedScore||0)),m}findIntentLogMatches(e,t){let n=this.intentLogsRepo.findWithEmbeddings(),s=[];for(let r of n)try{let o=JSON.parse(r.embedding),c=Ft(e,o);c>.25&&s.push({id:r.id,missionId:r.mission_id,type:r.type,content:r.content,symbolName:r.symbol_name,filePath:r.file_path,score:c,decayedScore:c,rationale:`Similarity: ${(c*100).toFixed(0)}%`,createdAt:r.created_at})}catch{}return s.sort((r,o)=>(o.decayedScore||0)-(r.decayedScore||0)),s.slice(0,t)}buildFtsQuery(e,t){let n=e.trim();if(!n.includes(" "))return`"${n}" OR ${n}*`;let s=n.split(/\s+/).filter(r=>r.length>0);switch(t){case"exact":return`"${n}"`;case"all":return s.map(r=>`${r}*`).join(" ");default:return s.map(r=>`${r}*`).join(" OR ")}}};W();z();function Vn(i){let{fileType:e,layer:t}=i,n={fileType:tt.normalizeFileType(e),layer:t},s=!!(n.fileType?.length||n.layer!=null);return{filters:n,hasFilters:s}}async function Eo(i){let e=zn(i.query??""),t={...i,query:e},n=In();try{let{repoPath:s}=Me(t),{query:r,limit:o=Et.DEFAULT_LIMIT,offset:c=0,compact:a=!1}=t;await G(s);let{filters:l,hasFilters:p}=Vn(t),d=await new tt(s).searchByConcept(r,o,c,l,p,a);return pl(s,r,"concept"),n(),d}catch(s){return S.error({error:s,args:i},"Concept Search failed"),n(),await yt(),{content:[{type:"text",text:`Concept Search failed: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}function pl(i,e,t){try{let n=C.getInstance(i),s=ce(i);n.searchHistory.record(e,t,s)}catch(n){let s=ce(i);S.error({module:"search",repoPath:i,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:s},"Failed to record search history"),yt()}}W();z();async function Bs(i){let e=zn(i.query??""),t={...i,query:e},n=In();try{let{repoPath:s}=Me(t),{query:r,limit:o=Et.DEFAULT_LIMIT,offset:c=0,matchMode:a="any"}=t;await G(s);let{filters:l,hasFilters:p}=Vn(t),d=await new tt(s).searchBySymbol(r,o,c,l,p,a);return dl(s,r,"symbol"),n(),d}catch(s){return S.error({error:s,args:i},"Symbol Search failed"),n(),await yt(),{content:[{type:"text",text:`Symbol Search failed: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}function dl(i,e,t){try{let n=C.getInstance(i),s=ce(i);n.searchHistory.record(e,t,s)}catch(n){let s=ce(i);S.error({module:"search",repoPath:i,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:s},"Failed to record search history"),yt()}}z();W();import tn from"path";function So(i,e){let t=i.findContentByToken(e,100);return{count:t.length,files:t}}async function wo(i){let{repoPath:e,query:t,key:n="",kind:s,limit:r=50,showUsage:o=!1}=i,c=n||t;if(!c&&!s)return{content:[{type:"text",text:'Error: Either "key" or "kind" parameter is required.'}]};await G(e);let a=C.getInstance(e),{configs:l,files:p}=a;if(c){S.info({repoPath:e,key:c},"Searching for config key in DB...");let h=l.findByKey(c,r);if(h.length===0)return{content:[{type:"text",text:`No configuration found for key: ${c}`}]};if(o){let b=h.map(x=>{let v=So(p,x.key),k=v.count===0?"\u26A0\uFE0F ORPHANED":`\u2713 ${v.count} usage(s)`;return{file:tn.relative(e,x.file_path),key:x.key,value:x.value,kind:x.kind,usageCount:v.count,usageFiles:v.files.slice(0,5).map(N=>tn.relative(e,N)),status:k}});b.sort((x,v)=>x.usageCount===0&&v.usageCount>0?-1:v.usageCount===0&&x.usageCount>0?1:x.usageCount-v.usageCount);let y=b.filter(x=>x.usageCount===0).length;return{content:[{type:"text",text:(y>0?`# Configuration Search: "${c}" (with Usage Analysis)
|
|
639
667
|
|
|
640
|
-
\u26A0\uFE0F **${
|
|
668
|
+
\u26A0\uFE0F **${y} orphaned var(s)** (defined but never used in code)
|
|
641
669
|
|
|
642
|
-
Found ${
|
|
670
|
+
Found ${h.length} match(es):
|
|
643
671
|
|
|
644
672
|
`:`# Configuration Search: "${c}" (with Usage Analysis)
|
|
645
673
|
|
|
646
|
-
Found ${
|
|
674
|
+
Found ${h.length} match(es), all in use:
|
|
647
675
|
|
|
648
|
-
`)+
|
|
649
|
-
**${
|
|
650
|
-
> Used in: ${
|
|
676
|
+
`)+b.map(x=>{let v=`## ${x.file} (${x.kind}) ${x.status}
|
|
677
|
+
**${x.key}**: \`${x.value}\``;return x.usageCount>0&&x.usageFiles.length>0&&(v+=`
|
|
678
|
+
> Used in: ${x.usageFiles.map(k=>`\`${k}\``).join(", ")}${x.usageCount>5?` (+${x.usageCount-5} more)`:""}`),v}).join(`
|
|
651
679
|
|
|
652
|
-
`)}]}}let h
|
|
680
|
+
`)}]}}let g=h.map(b=>({file:tn.relative(e,b.file_path),key:b.key,value:b.value,kind:b.kind}));return{content:[{type:"text",text:`# Configuration Search: "${c}"
|
|
653
681
|
|
|
654
|
-
Found ${
|
|
682
|
+
Found ${h.length} match(es):
|
|
655
683
|
|
|
656
|
-
`+
|
|
657
|
-
**${
|
|
684
|
+
`+g.map(b=>`## ${b.file} (${b.kind})
|
|
685
|
+
**${b.key}**: \`${b.value}\``).join(`
|
|
658
686
|
|
|
659
|
-
`)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let
|
|
687
|
+
`)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let u=l.findByKind(s||null,r);if(o){let h=u.map(y=>{let E=So(p,y.key);return{file:tn.relative(e,y.file_path),key:y.key,value:y.value,kind:y.kind,usageCount:E.count,status:E.count===0?"ORPHANED":"in-use"}});h.sort((y,E)=>y.usageCount===0&&E.usageCount>0?-1:E.usageCount===0&&y.usageCount>0?1:y.usageCount-E.usageCount);let g=h.filter(y=>y.usageCount===0).length,_=h.length,b=`# Config Discovery (${s||"all"}) with Usage Analysis
|
|
660
688
|
|
|
661
|
-
`;return
|
|
689
|
+
`;return b+=`**Summary**: ${_} config(s) found, ${g} orphaned
|
|
662
690
|
|
|
663
|
-
`,
|
|
664
|
-
`,
|
|
665
|
-
`),
|
|
691
|
+
`,g>0&&(b+=`## \u26A0\uFE0F Orphaned (${g})
|
|
692
|
+
`,b+=h.filter(y=>y.usageCount===0).map(y=>`- \`${y.key}\` in ${y.file}`).join(`
|
|
693
|
+
`),b+=`
|
|
666
694
|
|
|
667
|
-
`),
|
|
668
|
-
`,
|
|
669
|
-
`),
|
|
695
|
+
`),b+=`## \u2713 In Use (${_-g})
|
|
696
|
+
`,b+=h.filter(y=>y.usageCount>0).map(y=>`- \`${y.key}\` (${y.usageCount} usages)`).join(`
|
|
697
|
+
`),u.length===r&&(b+=`
|
|
670
698
|
|
|
671
|
-
> Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:
|
|
699
|
+
> Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:b}]}}let d=u.map(h=>({...h,file:tn.relative(e,h.file_path)})),m=JSON.stringify(d,null,2);return u.length===r&&(m=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
|
|
672
700
|
|
|
673
|
-
`+m),m+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:m}]}}
|
|
701
|
+
`+m),m+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:m}]}}z();import xo from"path";async function Qn(i){let{repoPath:e,filePath:t}=Me(i);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=i.detailLevel||"signatures";await G(e);let{files:s,exports:r}=C.getInstance(e),o=s.findByPath(t),c=xo.basename(t),a=/\.(ts|tsx|php|py|go)$/.test(c),l;a?l=await jt(t):l={exports:r.findByFile(t),imports:[]},n==="structure"?(l.exports=l.exports.map(m=>{let h={name:m.name,kind:m.kind,line:m.start_line,classification:m.classification};return m.members&&m.members.length>0?{...h,members:m.members.map(g=>({name:`${m.name}.${g.name}`,kind:g.kind,line:g.start_line}))}:h}),delete l.imports):n==="signatures"&&(l.exports=l.exports.map(m=>{let h={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?{...h,members:m.members.map(g=>({name:`${m.name}.${g.name}`,kind:g.kind,signature:g.signature,line:g.start_line}))}:h}),delete l.imports);let p=xo.relative(e,t),u=l.exports?.length||0,d="";return n==="structure"&&u>0?d=`
|
|
674
702
|
|
|
675
|
-
\u{1F4A1} Showing ${
|
|
703
|
+
\u{1F4A1} Showing ${u} symbol names. For full signatures: shadow_inspect_file({ filePath: "${p}", detailLevel: "signatures" })`:n==="signatures"&&u>0&&(d=`
|
|
676
704
|
|
|
677
|
-
\u{1F4A1} Showing ${
|
|
678
|
-
`),s=[],r=0;for(let
|
|
679
|
-
`),totalOriginalLines:n.length,foldedToLines:s.length,siblingsShown:a,siblingsFolded:c}}function
|
|
680
|
-
However, it likely exists inside: ${
|
|
681
|
-
Try: shadow_inspect_symbol({ symbolName: "${
|
|
705
|
+
\u{1F4A1} Showing ${u} 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||"Unknown"},null,2)+d}]}}z();import vo from"path";import ul from"fs";function ml(i,e,t){let n=i.split(`
|
|
706
|
+
`),s=[],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&&(s.push(...n.slice(0,r)),s.push(""));let o=[...t].sort((u,d)=>u.startLine-d.startLine),c=0,a=0;for(let u of o)if(u.isTarget){s.push(`// \u2501\u2501\u2501 REQUESTED: ${u.name} \u2501\u2501\u2501`);let d=n.slice(u.startLine-1,u.endLine);s.push(...d),s.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"),s.push(""),a++}else{let d=u.signature||hl(n,u.startLine-1,u.kind);d&&(s.push(`${d}`),s.push(` /* implementation: ${u.lineCount} lines */`),s.push(""),c++)}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==="};"){s.push(n[u]);break}else if(d&&!d.startsWith("//"))break}return{foldedSource:s.join(`
|
|
707
|
+
`),totalOriginalLines:n.length,foldedToLines:s.length,siblingsShown:a,siblingsFolded:c}}function hl(i,e,t){let n=i[e];if(t.includes("Function")||t.includes("Method")||t.includes("Arrow")){let s="";for(let r=e;r<Math.min(e+5,i.length);r++)if(s+=i[r],s.includes("{")||s.includes("=>")){let o=s.indexOf("{");o>0&&(s=s.substring(0,o).trim());break}return s.trim()}return n}async function Lt(i){let{repoPath:e,filePath:t,resolver:n}=Me(i),s=String(i.symbolName),r=i.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 G(e);let o=C.getInstance(e),c=[];if(s.includes(".")){let[v,k]=s.split(".");c=o.exports.findMemberCandidates(v,k,t)}else c=o.exports.findDefinitionCandidates(s,t);if(c.length===0){let v=o.exports.findPotentialParents(s);if(v.length>0){let T=v.map(I=>`\`${I.name}\` (in ${n.getRelative(I.file_path)})`).join(", ");return{content:[{type:"text",text:`Symbol "${s}" not found as a top-level export.
|
|
708
|
+
However, it likely exists inside: ${T}.
|
|
709
|
+
Try: shadow_inspect_symbol({ symbolName: "${v[0].name}", context: "full" }) to see the class body.`}]}}let N=o.exports.findFuzzyCandidates(s).map(T=>T.name),O=en(s,N,50,3);if(O.length>0){let T=O.map(I=>` \u2022 \`${I.match}\` (${I.score}% match)`).join(`
|
|
682
710
|
`);return{content:[{type:"text",text:`Error: Symbol "${s}" not found in the index.
|
|
683
711
|
|
|
684
712
|
Suggestions:
|
|
685
|
-
${
|
|
713
|
+
${T}
|
|
686
714
|
|
|
687
715
|
Next steps:
|
|
688
716
|
\u2022 Search semantically: shadow_search_concept({ query: "${s}" })
|
|
@@ -691,36 +719,36 @@ Next steps:
|
|
|
691
719
|
Next steps:
|
|
692
720
|
\u2022 Search for it: shadow_search_concept({ query: "${s}" })
|
|
693
721
|
\u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${s}", filePath: "..." })
|
|
694
|
-
`}]}}let a=c[0];if(a.kind==="ExportSpecifier"||a.kind==="ExportAllDeclaration"){let
|
|
695
|
-
`),
|
|
722
|
+
`}]}}let a=c[0];if(a.kind==="ExportSpecifier"||a.kind==="ExportAllDeclaration"){let v=o.imports.findImportSource(a.file_path,s);if(v&&v.resolved_path)return Lt({...i,filePath:v.resolved_path})}let l=ul.readFileSync(a.file_path,"utf8"),p=l.split(`
|
|
723
|
+
`),u=a.end_line-a.start_line+1,d=150,m,h=!1,g=null;if(r==="definition"&&u>d){let k=o.exports.findSiblings(a.file_path).map(N=>({name:N.name,kind:N.kind,signature:N.signature||"",startLine:N.start_line,endLine:N.end_line,lineCount:N.end_line-N.start_line+1,isTarget:N.name===a.name&&N.start_line===a.start_line,parentName:N.parent_name}));if(k.length>1){g=ml(l,{name:a.name,startLine:a.start_line,endLine:a.end_line},k);let N=n.getRelative(a.file_path);m=g.foldedSource+`
|
|
696
724
|
|
|
697
725
|
\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
|
|
698
726
|
\u{1F4CA} Semantic Fold Applied (context: "definition")
|
|
699
727
|
|
|
700
|
-
Original file: ${
|
|
701
|
-
Folded view: ${
|
|
728
|
+
Original file: ${g.totalOriginalLines} lines
|
|
729
|
+
Folded view: ${g.foldedToLines} lines
|
|
702
730
|
Target Symbol: ${a.name}
|
|
703
731
|
\u{1F4A1} Need more context?
|
|
704
732
|
\u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${a.name}", context: "full" })
|
|
705
|
-
\u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${
|
|
706
|
-
\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`,
|
|
733
|
+
\u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${N}", detailLevel: "signatures" })
|
|
734
|
+
\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`,h=!0}else m=p.slice(a.start_line-1,a.start_line-1+d).join(`
|
|
707
735
|
`)+`
|
|
708
736
|
|
|
709
|
-
... (truncated ${d
|
|
710
|
-
`);let
|
|
737
|
+
... (truncated ${u-d} lines)`,h=!0}else m=p.slice(a.start_line-1,a.end_line).join(`
|
|
738
|
+
`);let _=a.parent_name?`${a.parent_name}.${a.name}`:a.name,b=o.exports.findHydratedById(a.id),y={name:_,kind:a.kind,file:n.getRelative(a.file_path),startLine:a.start_line,endLine:a.end_line,totalLines:u,...h&&{truncated:!0,previewLines:d},classification:a.classification,intelligence:b?{working_set_of:b.active_missions.map(v=>`Mission #${v.id}: ${v.name}`),total_intents:b.intent_log_count,latest_intent:b.recent_intents[0]?`${b.recent_intents[0].type}: ${b.recent_intents[0].content}`:null}:void 0,source:m};if(r==="definition")return{content:[{type:"text",text:JSON.stringify(y,null,2)}]};let E={definition:y,dependencies:o.imports.getImportsForFile(a.file_path).map(v=>({module:v.module_specifier,symbols:v.imported_symbols,relativePath:v.resolved_path?vo.relative(e,v.resolved_path):null}))},w=[a.file_path],x=o.imports.findVerifiedDependents(w,s);return E.verifiedUsages=x.slice(0,10).map(v=>({file:vo.relative(e,v.file_path),classification:v.classification,importedSymbols:v.imported_symbols})),{content:[{type:"text",text:JSON.stringify(E,null,2)}]}}async function To(i,e){let t=nn.resolve(e.dir);await B(async()=>{se("Semantic Concept Search");let n=be();n.start(`Analyzing intent: "${f.bold(i)}"...`);try{let s=await Eo({repoPath:t,query:i});n.stop("Analysis complete.");let r=s.content[0].text;if(r.includes("Found")){let c=r.split("## ").slice(1).map(a=>{let[l,...p]=a.split(`
|
|
711
739
|
|
|
712
|
-
`),[d
|
|
713
|
-
`),p=l[0],
|
|
740
|
+
`),[u,d]=l.split(" ( "),m=(u??"").replace(/^\d+\.\s*/,"").trim(),h=p.find(g=>g.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:m,matchPct:d??"",summaryLine:h}});if(c.forEach(({name:a,matchPct:l,summaryLine:p})=>{X(`${f.green(a)} ${f.dim("("+(l||""))}`,p,"blue"),console.log("")}),e.interactive&&c.length>1){let a=await kn("Inspect a file",c.map(l=>({value:{name:l.name},label:l.name,hint:l.summaryLine.slice(0,50)})),{limit:15});if(a){let l=a.name.startsWith(t)?a.name:nn.join(t,a.name),p=await Qn({repoPath:t,filePath:l});p.content?.[0]&&(console.log(""),X(f.bold("File summary"),p.content[0].text,"cyan"))}}}else console.log(r)}catch(s){throw n.stop(`Search failed: ${s.message}`),s}finally{await J(t)}})}async function Ro(i,e){let t=nn.resolve(e.dir);await B(async()=>{se("Symbol Search");let n=be();n.start(`Searching symbols: "${f.bold(i)}"...`);try{let s=await Bs({repoPath:t,query:i});n.stop("Search complete.");let r=s.content[0].text;try{let o=JSON.parse(r);if(Array.isArray(o)){if(console.log(""),Tn(["Symbol","Kind","File","Line"],o.map(c=>[f.bold(f.green(c.name)),f.dim(c.kind??""),f.cyan(c.file??""),f.yellow(String(c.line??""))])),e.interactive&&o.length>1){let c=o.map(l=>({value:l,label:l.name,hint:`${l.file??""}:${l.line??""}`})),a=await kn("Inspect symbol",c,{limit:15});if(a){let l=await Lt({repoPath:t,symbolName:a.name});l.content?.[0]&&(console.log(""),X(f.bold(a.name),l.content[0].text,"cyan"))}}}else console.log(r)}catch{console.log(r)}}catch(s){throw n.stop(`Search failed: ${s.message}`),s}finally{await J(t)}})}async function ko(i,e){let t=nn.resolve(e.dir);await B(async()=>{se("Fuzzy Symbol Search");let n=be();n.start(`Fuzzy matching: "${f.bold(i)}"...`);try{let s=await Bs({repoPath:t,query:i});n.stop("Search complete.");let r=s.content[0].text;if(r.includes("## ")){let c=r.split("## ").slice(1).map(a=>{let l=a.split(`
|
|
741
|
+
`),p=l[0],u=l.find(b=>b.startsWith("**Match**:"))||"",d=l.find(b=>b.startsWith("**File**:"))||"",m=p.match(/`([^`]+)`/),h=m?m[1]:"",g=u.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),_=d.match(/`([^:]+):(\d+)`/);return{symbolName:h,file:_?_[1]:"",line:_?_[2]:"",matchType:g?g[1]:"",confidence:g?g[2]:""}});if(console.log(""),console.log(f.dim(`Found ${c.length} fuzzy match(es):`)),console.log(""),c.forEach((a,l)=>{console.log(`${f.dim(`${l+1}.`)} ${f.bold(f.green(a.symbolName))} ${f.dim(`(${a.matchType}, ${a.confidence}% match)`)}`),console.log(` ${f.cyan(a.file)}:${f.yellow(a.line)}`),console.log("")}),e.interactive&&c.length>1){let a=await kn("Inspect symbol",c.map(l=>({value:l,label:l.symbolName,hint:`${l.file}:${l.line}`})),{limit:15});if(a){let l=await Lt({repoPath:t,symbolName:a.symbolName});l.content?.[0]&&(console.log(""),X(f.bold(a.symbolName),l.content[0].text,"cyan"))}}}else console.log(r)}catch(s){throw n.stop(`Search failed: ${s.message}`),s}finally{await J(t)}})}async function Io(i,e){let t=nn.resolve(e.dir);await B(async()=>{se("Config Search");let n=be();n.start(`Searching config: ${f.bold(i||"all")}...`);try{let s=await wo({repoPath:t,key:i,kind:e.kind});n.stop("Search complete."),X("\u2699\uFE0F Results",s.content[0].text,"yellow")}finally{await J(t)}})}W();var Gs=S.child({module:"mcp:tools:env:hooks"});async function Kn(i){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:s}=i;if(t==="install"){Gs.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:s},"Installing git hooks");let r=Hi({repoPath:e,enableAutoRefresh:n??!0,enableSymbolHealing:s??!0}),o=["# Git Hooks Installation","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(c=>`- \`${c}\``).join(`
|
|
714
742
|
`):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(c=>`- \`${c}\` (already installed)`).join(`
|
|
715
743
|
`):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(c=>`- ${c}`).join(`
|
|
716
744
|
`)),o.push("")),o.push("---"),o.push("**What happens now?**"),(n??!0)&&o.push("- After `git pull` or `git checkout`: Index auto-refreshes in background"),(s??!0)&&o.push("- After `git commit`: Symbol shift detection runs automatically"),{content:[{type:"text",text:o.join(`
|
|
717
|
-
`)}]}}if(t==="remove"){
|
|
745
|
+
`)}]}}if(t==="remove"){Gs.info({repoPath:e},"Uninstalling git hooks");let r=Ui(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(c=>`- \`${c}\``).join(`
|
|
718
746
|
`):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(c=>`- ${c}`).join(`
|
|
719
747
|
`))),{content:[{type:"text",text:o.join(`
|
|
720
|
-
`)}]}}if(t==="status"){
|
|
748
|
+
`)}]}}if(t==="status"){Gs.info({repoPath:e},"Checking git hooks status");let r=_t(e);return{content:[{type:"text",text:["# Git Hooks Status","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(c=>`- \`${c}\``).join(`
|
|
721
749
|
`):"- None","",`## Not Installed (${r.notInstalled.length})`,r.notInstalled.length>0?r.notInstalled.map(c=>`- \`${c}\``).join(`
|
|
722
750
|
`):"- None","","---",'**To install hooks**: Use `shadow_env_hooks({ action: "install" })`'].join(`
|
|
723
|
-
`)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function
|
|
751
|
+
`)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function Co(i){let[e,t="."]=i;if(!e||!["install","uninstall","status"].includes(e)){console.log(""),console.log(` ${f.bold("Usage: ")} liquid-shadow hooks <install|uninstall|status> [path]`),console.log(""),console.log(` ${f.bold("Commands: ")}`),console.log(` ${f.cyan("install")} Install git hooks for automatic index refresh and symbol healing`),console.log(` ${f.cyan("uninstall")} Remove installed git hooks`),console.log(` ${f.cyan("status")} Check git hooks installation status`),console.log(""),console.log(` ${f.bold("Examples: ")}`),console.log(" liquid-shadow hooks install ."),console.log(" liquid-shadow hooks status /path/to/repo"),console.log("");return}await B(async()=>{let n=fa("path").resolve(t);switch(e){case"install":{let s=await Kn({repoPath:n,action:"install",enableAutoRefresh:!0,enableSymbolHealing:!0});if(console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Git hooks installed successfully")}`),console.log(""),s.content&&s.content[0])try{let r=JSON.parse(s.content[0].text);console.log(` ${f.bold("Installed hooks: ")}`),r.hooks.forEach(o=>{console.log(` ${f.cyan("\u2022")} ${o}`)}),console.log("")}catch{console.log(s.content[0].text)}break}case"uninstall":{await Kn({repoPath:n,action:"remove"}),console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Git hooks uninstalled successfully")}`),console.log("");break}case"status":{let s=await Kn({repoPath:n,action:"status"});if(console.log(""),console.log(` ${f.bold("Git Hooks Status")}`),console.log(""),s.content&&s.content[0])try{let r=JSON.parse(s.content[0].text);r.installed&&r.installed.length>0?(console.log(` ${f.green("\u2714")} Installed hooks:`),r.installed.forEach(o=>{console.log(` ${f.cyan("\u2022")} ${o}`)})):console.log(` ${f.yellow("\u26A0")} No hooks installed`),r.missing&&r.missing.length>0&&(console.log(""),console.log(` ${f.dim("Missing hooks: ")}`),r.missing.forEach(o=>{console.log(` ${f.dim("\u2022")} ${o}`)}))}catch{console.log(s.content[0].text)}console.log("");break}}})}z();W();import fl from"path";import gl from"fs";var Lo=S.child({module:"mcp:tools:workspace:list"});async function $o(i){let{repoPaths:e,status:t,limit:n,summarize:s=!1}=i;Lo.info({repoCount:e.length,status:t,summarize:s},"Getting workspace missions");let r=[];for(let c of e)if(gl.existsSync(c))try{let{missions:a}=C.getInstance(c),l=a.findAll(t);for(let p of l){let u=a.getLinks(p.id);r.push({...p,repo_path:c,repo_name:fl.basename(c),cross_repo_links:u})}}catch(a){Lo.error({error:a,repoPath:c},"Failed to query repo missions")}if(r.sort((c,a)=>{let l=d=>d==="in-progress"?0:d==="verifying"?1:2,p=l(c.status),u=l(a.status);return p!==u?p-u:(c.created_at||0)-(a.created_at||0)}),s||r.length>50&&!n){let c=n||20,a=r.slice(0,c),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:c},top_missions:a,hint:`Showing top ${c} 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)}]}}z();W();var yl=S.child({module:"mcp:tools:workspace:link"});async function No(i){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:s,relationship:r="related"}=i;yl.info({parentRepoPath:e,childRepoPath:n},"Linking cross-repo missions");let{missions:o}=C.getInstance(e),{missions:c}=C.getInstance(n);try{let a=o.findById(t),l=c.findById(s);if(!a)throw new Error(`Parent mission ${t} not found`);if(!l)throw new Error(`Child mission ${s} not found`);return o.createLink(t,n,s,r,"parent"),c.createLink(s,e,t,r,"child"),{content:[{type:"text",text:JSON.stringify({status:"linked",relationship:r},null,2)}]}}catch(a){throw new Error(`Failed to link: ${a.message}`)}}W();import kl from"path";W();qe();import bl from"better-sqlite3";import $t from"path";import Ao from"fs";import _l from"os";import El from"crypto";var Sl=S.child({module:"fusion-connection"}),Xn=5,wl=1,Po=["files","exports","imports","configs","schema_migrations"],Zn=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),Sl.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=$t.dirname(this.fusionDbPath);Ao.existsSync(t)||Ao.mkdirSync(t,{recursive:!0}),this.fusionDb=new bl(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=_l.homedir(),n=$t.join(t,".mcp-liquid-shadow","fused"),s=e.replace(/[^a-zA-Z0-9-_]/g,"_");return $t.join(n,`${s}.db`)}initFusionSchema(){this.fusionDb.exec(`
|
|
724
752
|
CREATE TABLE IF NOT EXISTS fused_repos (
|
|
725
753
|
alias TEXT PRIMARY KEY,
|
|
726
754
|
repo_path TEXT NOT NULL UNIQUE,
|
|
@@ -754,19 +782,19 @@ Target Symbol: ${a.name}
|
|
|
754
782
|
|
|
755
783
|
CREATE INDEX IF NOT EXISTS idx_virtual_edges_source ON virtual_edges(source_repo, source_file_path);
|
|
756
784
|
CREATE INDEX IF NOT EXISTS idx_virtual_edges_target ON virtual_edges(target_repo, target_file_path);
|
|
757
|
-
`),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(
|
|
758
|
-
VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,s,r);return}catch(p){let
|
|
785
|
+
`),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(wl.toString())}attachRepo(e){let t=$t.resolve(e);if(this.attachedRepos.has(t))return;if(!He(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=We(t),s=n.name;this.validateSchemaCompatibility(n,t);let r=this.getSchemaVersion(n),o=this.generateAlias(t),c=3,a=100;for(let l=1;l<=c;l++)try{this.fusionDb.exec(`ATTACH DATABASE '${s}' AS ${o}`);let p={alias:o,repoPath:t,dbPath:s,schemaVersion:r,attached:!0};this.attachedRepos.set(t,p),this.fusionDb.prepare(`INSERT OR REPLACE INTO fused_repos (alias, repo_path, db_path, schema_version, attached_at, last_validated_at)
|
|
786
|
+
VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,s,r);return}catch(p){let u=p instanceof Error?p.message.toLowerCase():String(p).toLowerCase();if((u.includes("locked")||u.includes("busy"))&&l<c){this.sleep(a*l);continue}throw p}}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=$t.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=We(t.repoPath),s=Po.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=Xn&&s.length===0,missingTables:s}});return{valid:e.every(t=>t.compatible),minVersion:Xn,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=$t.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=El.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<Xn)throw new Error(`Schema version mismatch for ${t}. Expected >= ${Xn}, got ${n}.`);let s=Po.filter(r=>!this.checkTableExists(e,r));if(s.length>0)throw new Error(`Missing tables in ${t}: ${s.join(", ")}`)}checkTableExists(e,t){try{return!!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)}catch{return!1}}sleep(e){let t=Date.now()+e;for(;Date.now()<t;);}get nameValue(){return this.name}get dbPath(){return this.fusionDbPath}};W();var nt=S.child({module:"edge-scanner"});function qs(i){let e=i.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function xl(i){if(!i)return null;try{let e=JSON.parse(i);return e.path||e.name||null}catch{return null}}function vl(i,e){let t=qs(i),n=qs(e);if(t===n)return!0;let s=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${s}$`).test(t)}function Tl(i){nt.info("Starting HTTP gap detection scan");let e=i.getAttachedRepos();if(e.length<2)return nt.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
|
|
759
787
|
SELECT id, name, file_path, capabilities
|
|
760
788
|
FROM ${r.alias}.exports
|
|
761
789
|
WHERE kind = 'HTTP Route'
|
|
762
|
-
`,c=i.executeRawQuery(o);for(let a of c){let l=
|
|
790
|
+
`,c=i.executeRawQuery(o);for(let a of c){let l=xl(a.capabilities)||a.name;l&&l.startsWith("/")&&t.push({repo:r.alias,repoPath:r.repoPath,filePath:a.file_path,symbolId:a.id,routePath:l})}}catch(o){nt.warn({repo:r.alias,error:o},"Failed to query backend routes")}nt.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
|
|
763
791
|
SELECT file_path, name
|
|
764
792
|
FROM ${r.alias}.event_synapses
|
|
765
793
|
WHERE type = 'api_route' AND direction = 'produce'
|
|
766
|
-
`,c=i.executeRawQuery(o);for(let a of c){let l
|
|
767
|
-
`));let
|
|
794
|
+
`,c=i.executeRawQuery(o);for(let a of c){let l=qs(a.name);l&&l.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:a.file_path,routePath:l})}}catch(o){nt.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}nt.debug({count:n.length},"Found frontend API calls");let s=0;for(let r of n)for(let o of t)if(r.repoPath!==o.repoPath&&vl(r.routePath,o.routePath))try{i.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}),s++}catch(c){nt.debug({source:r.filePath,target:o.filePath,error:c},"Skipped duplicate edge")}return nt.info({edgesCreated:s,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),s}function Mo(i){let e=Tl(i);return{httpGaps:e,totalEdges:e}}W();var Rl=S.child({module:"fusion-index-service"}),es=class{constructor(e){this.connection=e}executeFederatedQuery(e,...t){return this.connection.prepare(e).all(...t).map(r=>{let{_repo_alias:o,_repo_path:c,...a}=r;return{repo:o,repoPath:c,data:a}})}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:s,columns:r,joins:o,where:c,groupBy:a,having:l,orderBy:p,limit:u,offset:d}=e,m=s||n.charAt(0),h=r.join(", "),_=t.map(b=>{let y=`${b.alias}.${n} ${m}`,E="";o&&o.length>0&&(E=o.map(k=>{let N=k.alias||k.table.charAt(0);return`${k.type} JOIN ${b.alias}.${k.table} ${N} ON ${k.on}`}).join(`
|
|
795
|
+
`));let w=c?`WHERE ${c}`:"",x=a&&a.length>0?`GROUP BY ${a.join(", ")}`:"",v=l?`HAVING ${l}`:"";return`SELECT '${b.alias}' as _repo_alias, '${b.repoPath}' as _repo_path, ${h} FROM ${y} ${E} ${w} ${x} ${v}`.trim()}).join(`
|
|
768
796
|
UNION ALL
|
|
769
|
-
`);return p&&(
|
|
797
|
+
`);return p&&(_=`SELECT * FROM (${_}) AS federated_results ORDER BY ${p}`),u!==void 0&&(_+=` LIMIT ${u}`),d!==void 0&&(_+=` OFFSET ${d}`),_}buildFtsQuery(e,t,n,s,r=50){let o=this.connection.getAttachedRepos();if(o.length===0)throw new Error("No repositories attached");let c=n.replace(/"/g,'""'),a=s.map(p=>`c.${p}`).join(", ");return`${o.map(p=>`
|
|
770
798
|
SELECT '${p.alias}' as _repo_alias, '${p.repoPath}' as _repo_path, ${a}, bm25(${p.alias}.${e}) as _fts_rank
|
|
771
799
|
FROM ${p.alias}.${e} fts
|
|
772
800
|
JOIN ${p.alias}.${t} c ON fts.rowid = c.id
|
|
@@ -788,7 +816,7 @@ WHERE i.resolved_path IS NOT NULL`);return t.join(`
|
|
|
788
816
|
INSERT INTO virtual_edges
|
|
789
817
|
(source_repo, source_file_path, source_symbol_id, target_repo, target_file_path, target_symbol_id, relationship, metadata, confidence, updated_at)
|
|
790
818
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
|
|
791
|
-
`).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 zc.info({name:this.connection.nameValue},"Starting edge scan"),mo(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var ho=_.child({module:"fused-index"}),Ls=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new On(e),this.service=new Fn(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(),ho.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,s,r){return this.service.buildFtsQuery(e,t,n,s,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return ho.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},ks=new Map;function fo(i){let e=ks.get(i.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),s=new Set(i.repoPaths.map(o=>Gc.resolve(o)));if(n.size===s.size&&[...n].every(o=>s.has(o)))return e;e.close(),ks.delete(i.name)}let t=new Ls(i);return ks.set(i.name,t),t}P();var qc=_.child({module:"mcp:tools:workspace:fuse"});async function go(i){let{repoPaths:e,name:t}=i;qc.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=fo({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 Hn from"path";async function yo(i){let[e,...t]=i;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${E.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${E.bold("Commands: ")}`),console.log(` ${E.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${E.cyan("link")} <args...> Link missions across repositories`),console.log(` ${E.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${E.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 B(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${E.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>Hn.resolve(r)),s=await co({repoPaths:n});if(console.log(""),console.log(` ${E.bold("Workspace Missions")}`),console.log(""),s.content&&s.content[0]){let r=JSON.parse(s.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${E.cyan("\u2022")} ${E.bold(o.name)} (ID: ${o.id})`),console.log(` ${E.dim("Repo: ")} ${o.repo_path}`),console.log(` ${E.dim("Status: ")} ${o.status}`),console.log(` ${E.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${E.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${E.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${E.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,s,r,o,c]=t;await lo({parentRepoPath:Hn.resolve(n),parentMissionId:parseInt(s,10),childRepoPath:Hn.resolve(r),childMissionId:parseInt(o,10),relationship:c}),console.log(""),console.log(` ${E.green("\u2714")} ${E.bold("Missions linked successfully")}`),console.log(` ${E.dim("Parent: ")} ${n} (Mission ${s})`),console.log(` ${E.dim("Child: ")} ${r} (Mission ${o})`),c&&console.log(` ${E.dim("Relationship: ")} ${c}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${E.red("\u2716")} Please provide at least one repository path`);return}let n,s=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):s.push(Hn.resolve(t[o]));let r=await go({repoPaths:s,name:n});if(console.log(""),console.log(` ${E.green("\u2714")} ${E.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${E.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${E.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${E.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${E.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}P();P();var Jc=_.child({module:"strategy-normalizer"}),Ne=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(s){return Jc.warn({strategyInput:e,err:s},"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],s)=>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-${s}`,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),s=new Set;for(let r of n.steps)if(s.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),s.add(r.id),r.dependencies)for(let o of r.dependencies)s.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}}}};P();import Ns from"fs";import bo from"path";import Yc from"os";var Vc=[{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"}],Qc=[{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"}],Kc=[{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"}],Eo=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:Vc},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:Qc},{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:Kc}],As=new Map(Eo.map(i=>[i.id,i])),Wn=!1;function Xc(){if(Wn)return;let i=bo.join(Yc.homedir(),".shadow","templates");if(!Ns.existsSync(i)){_.debug({templatesDir:i},"Custom templates directory does not exist"),Wn=!0;return}try{let e=Ns.readdirSync(i).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=bo.join(i,t),s=Ns.readFileSync(n,"utf8"),r=JSON.parse(s);if(!r.id||!r.name||!r.defaultGoal||!r.steps){_.warn({file:t,template:r},"Invalid custom template structure - skipping");continue}if(!Array.isArray(r.steps)||r.steps.length===0){_.warn({file:t},"Template has no steps - skipping");continue}if(Eo.some(o=>o.id===r.id)){_.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}As.set(r.id,r),_.info({file:t,templateId:r.id},"Loaded custom template")}catch(n){_.warn({file:t,error:n},"Failed to load custom template")}Wn=!0}catch(e){_.warn({error:e,templatesDir:i},"Failed to read custom templates directory"),Wn=!0}}function Zc(i){return Xc(),As.get(i)}function el(i,e){let t=i;for(let[n,s]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),s);return t}function So(i,e,t={}){let n=Zc(i);if(!n)throw new Error(`Unknown template: ${i}. Use one of: ${Array.from(As.keys()).join(", ")}`);let s=t.target||"scope",r=e||(i==="refactoring"?`Refactor ${s}`:i==="feature"?`Feature: ${s}`:`Fix: ${s}`),o=el(n.defaultGoal,{...t,target:s}),c=Ne.normalize({steps:n.steps}),a=Ne.stringify(c);return{name:r,goal:o,strategy:a}}U();var jn=_.child({module:"mcp:tools:ops:plan"});async function _o(i){let{repoPath:e,name:t,goal:n,strategy:s,missionId:r,parentId:o,outcomeContract:c,templateId:a,templateVars:l}=i,{missions:p}=C.getInstance(e),d=re(e),u=fe(e);jn.info({repoPath:e,name:t,missionId:r,templateId:a},"Planning mission");try{let m=t,f=n,h=s;if(a){let S=So(a,t,l||{});m=m??S.name,f=f??S.goal,h=h??S.strategy}if(!m||!f)throw new Error("Mission requires name and goal (or templateId with optional templateVars).");let b=null;if(h){let S=Ne.normalize(h);b=Ne.stringify(S);let R=Ne.validate(b);R.valid||jn.warn({errors:R.errors,strategy:h},"Strategy validation warnings detected")}let y,g;r?(p.update(r,{name:m,goal:f,strategy_graph:b,commit_sha:u,parent_id:o!==void 0?o:void 0,outcome_contract:c}),y=r,g=`Mission "${m}" updated.`):(y=p.create({name:m,goal:f,strategy_graph:b,status:"planned",git_branch:d,commit_sha:u,parent_id:o||null,verification_context:null,outcome_contract:c||null}),g=`Mission "${m}" planned.`);try{await new ve(e).syncMissionToGitNotes(Number(y))}catch(S){jn.warn({syncError:S,missionId:y},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:y,status:"planned",message:g,strategy_saved:!!h,contract_saved:!!c,from_template:a??void 0,commit:u},null,2)}]}}catch(m){throw jn.error({error:m,repoPath:e},"Failed to plan mission"),new Error(`Failed to plan mission: ${m instanceof Error?m.message:String(m)}`)}}P();U();U();P();var tl=_.child({module:"collision-service"}),Un=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=re(this.repoPath);if(!e)return[];let{missions:t,intentLogs:n}=C.getInstance(this.repoPath),s=t.findActive().filter(c=>c.git_branch&&c.git_branch!==e),r=[],o=new Set;for(let c of s){let a=c.git_branch;if(o.has(a))continue;o.add(a),tl.info({branch:a,currentBranch:e},"Checking predictive collisions"),Qi(this.repoPath,e,a)&&r.push({branch:a,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${a}'.`});let p=t.findActive(e),d=new Set;for(let f of p)t.getWorkingSet(f.id).forEach(h=>d.add(h.file_path));let m=t.getWorkingSet(c.id).filter(f=>d.has(f.file_path));m.length>0&&r.push({branch:a,type:"intent",description:`Logical conflict: Mission '${c.name}' on '${a}' is modifying files you are currently working on.`,conflictingFiles:m.map(f=>f.file_path)})}return r}};var Ut=_.child({module:"mcp:tools:ops:briefing"});async function xo(i){let{repoPath:e,missionId:t,scope:n="mission",activeMissionsLimit:s,recentActivityLimit:r=10,compact:o=!1}=i,{missions:c,intentLogs:a}=C.getInstance(e),l=fe(e),p=re(e);Ut.info({repoPath:e,missionId:t,scope:n},"Generating briefing");try{if(n==="project"){let h=c.findActive(p||void 0),b=h.length;s&&h.length>s&&(h=h.slice(0,s));let y=c.findParentOnlyIds(h),g=new Set(y),S=h.filter(N=>!g.has(N.id)),R={};for(let N of h)N.parent_id!=null&&(R[N.parent_id]||(R[N.parent_id]=[]),R[N.parent_id].push(N));let w={},T=new Map(h.map(N=>[N.id,N])),v=Object.keys(R).map(Number),k=v.filter(N=>!T.has(N)),F=k.length>0?c.findByIds(k):[],x=new Map(T);for(let N of F)x.set(N.id,N);for(let N of v){let L=x.get(N);L&&(w[N]={id:L.id,name:L.name??"",goal:L.goal??"",status:L.status??"unknown"})}let I=o?h.map(N=>({...N,strategy_graph:void 0})):h,M=o?S.map(N=>({...N,strategy_graph:void 0})):S,$=a.findRecentDecisionActivity(r),j={scope:"project",counts:c.getStats(),analytics:c.getAnalytics(),active_missions:I,parent_only_ids:y,missions_by_parent:o?Object.fromEntries(Object.entries(R).map(([N,L])=>[N,L.map(A=>({...A,strategy_graph:void 0}))])):R,parents_summary:Object.keys(w).length?w:void 0,close_parent_when_all_children_done:'When all children of a parent are completed, call shadow_ops_track({ missionId: <parent_id>, status: "completed" }) with no stepId.',next_work_candidates:M,recent_completed:c.findRecentCompleted(),recent_activity:$,meta:{current_branch:p,current_commit:l,activeMissionsTotal:b,activeMissionsShown:h.length,hasMoreMissions:s?b>s:!1}};if(n==="project"){let N=y.map(L=>{let A=h.find(te=>te.id===L),D=R[L]??[];return{parent:A,children:D}});j.missions_grouped_by_parent=N}let H=S.length===0?{tool:"shadow_ops_plan",reason:"No open work; create a mission"}:{tool:"shadow_ops_track",reason:"Pick one from next_work_candidates and run /continue"};return{content:[{type:"text",text:JSON.stringify(j,null,2)}],suggestedNext:H}}let d;if(t?d=c.findById(t):d=c.findActive(p||void 0)[0],!d)return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let u="No external shadow changes detected.";try{new mt(e).analyzeGhostChanges(d.commit_sha||void 0),u="Shadow Trace completed: Checked for external modifications."}catch(h){Ut.warn({error:h},"Ghost analysis failed")}let m={repaired:0,failed:0};try{m=new Te(e).detectAndRepairShifts()}catch(h){Ut.warn({error:h},"Symbol shift repair failed")}let f={mission:{id:d.id,name:d.name,goal:d.goal,status:d.status,last_updated:new Date(d.updated_at*1e3).toISOString(),git_branch:d.git_branch,commit_sha:d.commit_sha,outcome_contract:d.outcome_contract},artifacts:c.getArtifacts(d.id),shadow_trace:{ghost_analysis:u,symbols_repaired:m.repaired,symbols_missing:m.failed},context:{current_commit:l,working_set:c.getWorkingSet(d.id).map(h=>h.file_path)},strategy_snapshot:d.strategy_graph?JSON.parse(d.strategy_graph):null,recent_activity:a.findByMission(d.id,15),ancestor_activity:[],predictive_collisions:[]};try{let h=new Un(e);f.predictive_collisions=await h.analyzePotentialCollisions()}catch(h){Ut.warn({error:h},"Predictive collision analysis failed")}if(n==="mission"){let y=new nt(e).getAncestorMissionIds().filter(g=>g!==d?.id);if(y.length>0)for(let g of y){let S=a.findByMission(g,5);f.ancestor_activity.push(...S)}}return{content:[{type:"text",text:JSON.stringify(f,null,2)}]}}catch(d){throw Ut.error({error:d,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${d instanceof Error?d.message:String(d)}`)}}P();U();U();P();P();var nl=_.child({module:"reasoning-engine"}),Bn=class{analyze(e){nl.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[]};for(let n of e){let s=n.content.toLowerCase(),r=this.matchesContext(s,n.type),o=this.matchesDecision(s,n.type),c=this.matchesConsequence(s,n.type),a=this.matchesRecommendation(s,n.type);r?t.context.push(n.content):o?t.decisions.push(n.content):a?t.recommendations.push(n.content):c?t.consequences.push(n.content):n.type==="decision"?t.decisions.push(n.content):n.type==="discovery"||n.type==="fix"?t.consequences.push(n.content):t.unclassified.push(n.content)}return t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(s=>e.includes(s))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(s=>e.includes(s))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(s=>e.includes(s))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(s=>e.includes(s))}};var zn=_.child({module:"briefing-engine"}),Ge=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=C.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Bn,this.persistencePivot=new ve(e)}async distillMission(e,t=!0){zn.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 s=this.reasoningEngine.analyze(n),r=new Set(n.map(c=>c.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
|
|
819
|
+
`).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 Rl.info({name:this.connection.nameValue},"Starting edge scan"),Mo(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var Do=S.child({module:"fused-index"}),Ys=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Zn(e),this.service=new es(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(),Do.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,s,r){return this.service.buildFtsQuery(e,t,n,s,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return Do.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},Js=new Map;function Oo(i){let e=Js.get(i.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),s=new Set(i.repoPaths.map(o=>kl.resolve(o)));if(n.size===s.size&&[...n].every(o=>s.has(o)))return e;e.close(),Js.delete(i.name)}let t=new Ys(i);return Js.set(i.name,t),t}W();var Il=S.child({module:"mcp:tools:workspace:fuse"});async function Fo(i){let{repoPaths:e,name:t}=i;Il.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=Oo({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 ts from"path";async function Wo(i){let[e,...t]=i;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${f.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${f.bold("Commands: ")}`),console.log(` ${f.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${f.cyan("link")} <args...> Link missions across repositories`),console.log(` ${f.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${f.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 B(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${f.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>ts.resolve(r)),s=await $o({repoPaths:n});if(console.log(""),console.log(` ${f.bold("Workspace Missions")}`),console.log(""),s.content&&s.content[0]){let r=JSON.parse(s.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${f.cyan("\u2022")} ${f.bold(o.name)} (ID: ${o.id})`),console.log(` ${f.dim("Repo: ")} ${o.repo_path}`),console.log(` ${f.dim("Status: ")} ${o.status}`),console.log(` ${f.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${f.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${f.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${f.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,s,r,o,c]=t;await No({parentRepoPath:ts.resolve(n),parentMissionId:parseInt(s,10),childRepoPath:ts.resolve(r),childMissionId:parseInt(o,10),relationship:c}),console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Missions linked successfully")}`),console.log(` ${f.dim("Parent: ")} ${n} (Mission ${s})`),console.log(` ${f.dim("Child: ")} ${r} (Mission ${o})`),c&&console.log(` ${f.dim("Relationship: ")} ${c}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${f.red("\u2716")} Please provide at least one repository path`);return}let n,s=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):s.push(ts.resolve(t[o]));let r=await Fo({repoPaths:s,name:n});if(console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${f.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${f.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${f.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${f.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}W();W();var Cl=S.child({module:"strategy-normalizer"}),je=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(s){return Cl.warn({strategyInput:e,err:s},"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],s)=>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-${s}`,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),s=new Set;for(let r of n.steps)if(s.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),s.add(r.id),r.dependencies)for(let o of r.dependencies)s.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}}}};W();import Vs from"fs";import Ho from"path";import Ll from"os";var $l=[{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"}],Nl=[{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"}],Al=[{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"}],Uo=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:$l},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:Nl},{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:Al}],Qs=new Map(Uo.map(i=>[i.id,i])),ns=!1;function Pl(){if(ns)return;let i=Ho.join(Ll.homedir(),".shadow","templates");if(!Vs.existsSync(i)){S.debug({templatesDir:i},"Custom templates directory does not exist"),ns=!0;return}try{let e=Vs.readdirSync(i).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=Ho.join(i,t),s=Vs.readFileSync(n,"utf8"),r=JSON.parse(s);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(Uo.some(o=>o.id===r.id)){S.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}Qs.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")}ns=!0}catch(e){S.warn({error:e,templatesDir:i},"Failed to read custom templates directory"),ns=!0}}function Ml(i){return Pl(),Qs.get(i)}function Dl(i,e){let t=i;for(let[n,s]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),s);return t}function jo(i,e,t={}){let n=Ml(i);if(!n)throw new Error(`Unknown template: ${i}. Use one of: ${Array.from(Qs.keys()).join(", ")}`);let s=t.target||"scope",r=e||(i==="refactoring"?`Refactor ${s}`:i==="feature"?`Feature: ${s}`:`Fix: ${s}`),o=Dl(n.defaultGoal,{...t,target:s}),c=je.normalize({steps:n.steps}),a=je.stringify(c);return{name:r,goal:o,strategy:a}}z();var ss=S.child({module:"mcp:tools:ops:plan"});async function zo(i){let{repoPath:e,name:t,goal:n,strategy:s,missionId:r,parentId:o,outcomeContract:c,templateId:a,templateVars:l}=i,{missions:p}=C.getInstance(e),u=ce(e),d=xe(e);ss.info({repoPath:e,name:t,missionId:r,templateId:a},"Planning mission");try{let m=t,h=n,g=s;if(a){let E=jo(a,t,l||{});m=m??E.name,h=h??E.goal,g=g??E.strategy}if(!m||!h)throw new Error("Mission requires name and goal (or templateId with optional templateVars).");let _=null;if(g){let E=je.normalize(g);_=je.stringify(E);let w=je.validate(_);w.valid||ss.warn({errors:w.errors,strategy:g},"Strategy validation warnings detected")}let b,y;r?(p.update(r,{name:m,goal:h,strategy_graph:_,commit_sha:d,parent_id:o!==void 0?o:void 0,outcome_contract:c}),b=r,y=`Mission "${m}" updated.`):(b=p.create({name:m,goal:h,strategy_graph:_,status:"planned",git_branch:u,commit_sha:d,parent_id:o||null,verification_context:null,outcome_contract:c||null}),y=`Mission "${m}" planned.`);try{await new Re(e).syncMissionToGitNotes(Number(b))}catch(E){ss.warn({syncError:E,missionId:b},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:b,status:"planned",message:y,strategy_saved:!!g,contract_saved:!!c,from_template:a??void 0,commit:d},null,2)}]}}catch(m){throw ss.error({error:m,repoPath:e},"Failed to plan mission"),new Error(`Failed to plan mission: ${m instanceof Error?m.message:String(m)}`)}}W();z();z();W();var Ol=S.child({module:"collision-service"}),sn=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=ce(this.repoPath);if(!e)return[];let{missions:t,intentLogs:n}=C.getInstance(this.repoPath),s=t.findActive().filter(c=>c.git_branch&&c.git_branch!==e),r=[],o=new Set;for(let c of s){let a=c.git_branch;if(o.has(a))continue;o.add(a),Ol.info({branch:a,currentBranch:e},"Checking predictive collisions"),yr(this.repoPath,e,a)&&r.push({branch:a,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${a}'.`});let p=t.findActive(e),u=new Set;for(let h of p)t.getWorkingSet(h.id).forEach(g=>u.add(g.file_path));let m=t.getWorkingSet(c.id).filter(h=>u.has(h.file_path));m.length>0&&r.push({branch:a,type:"intent",description:`Logical conflict: Mission '${c.name}' on '${a}' is modifying files you are currently working on.`,conflictingFiles:m.map(h=>h.file_path)})}return r}};var is=class i{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(a=>a.id),s=this.intentLogs.countByMissions(n),r=this.intentLogs.findMissionsWithBlockers(n),o=Math.max(1,...Object.values(s));return e.map(a=>{let l=this.computeRecency(a.updated_at,t),p=(s[a.id]||0)/o,u=this.computeStatusBoost(a.status),d=r.has(a.id)?1:0,m=i.WEIGHTS,h=l*m.recency+p*m.activity+u*m.statusBoost+d*m.blockerBoost;return{mission:a,score:Math.round(h*1e3)/1e3,breakdown:{recency:Math.round(l*1e3)/1e3,activity:Math.round(p*1e3)/1e3,blockerBoost:d,statusBoost:u}}}).sort((a,l)=>l.score-a.score)}computeRecency(e,t){let n=Math.max(0,(t-e)/3600);return Math.pow(.5,n/i.RECENCY_HALF_LIFE_HOURS)}computeStatusBoost(e){switch(e){case"in-progress":return 1;case"verifying":return .8;case"planned":return .4;default:return 0}}};var ut=S.child({module:"mcp:tools:ops:briefing"});async function Bo(i){let{repoPath:e,missionId:t,scope:n="mission",altitude:s,activeMissionsLimit:r,recentActivityLimit:o,compact:c}=i,a=c??(s==="orbit"||s==="atmosphere"),l=o??(s==="orbit"?0:s==="ground"?20:10),{missions:p,intentLogs:u}=C.getInstance(e),d=xe(e),m=ce(e);ut.info({repoPath:e,missionId:t,scope:n},"Generating briefing");try{if(n==="project"){let E=p.findActive(m||void 0),w=E.length;r&&E.length>r&&(E=E.slice(0,r));let x=p.findParentOnlyIds(E),v=new Set(x),k=E.filter(j=>!v.has(j.id)),O=new is(u).score(k),T=.15,I=3,U=a&&O.length>I?O.filter((j,F)=>F<I||j.score>=T):O,H=U.map(j=>j.mission),P=new Map(U.map(j=>[j.mission.id,j.score])),R=j=>({id:j.id,name:j.name,goal:j.goal,status:j.status,relevance:P.get(j.id)}),A=H.length===0&&E.length===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"};if(s==="orbit"){let j={scope:"project",altitude:"orbit",counts:p.getStats(),next_work_candidates:H.map(R),meta:{current_branch:m,activeMissionsTotal:w}};return{content:[{type:"text",text:JSON.stringify(j,null,2)}],suggestedNext:A}}let D={},$=[];for(let j of E)j.parent_id!=null?(D[j.parent_id]||(D[j.parent_id]=[]),D[j.parent_id].push(j)):$.push(j);let L=p.findRecentCompleted(5).map(R);if(s==="ground"){let j=l>0?u.findRecentDecisionActivity(l):void 0,F=x.map(de=>({parent:E.find(ie=>ie.id===de),children:D[de]??[]})),M=$.filter(de=>!v.has(de.id)),_e={scope:"project",altitude:"ground",counts:p.getStats(),analytics:p.getAnalytics(),hierarchy:F.length>0?F:void 0,standalone_active:M.length>0?M:void 0,active_missions:F.length===0?E:void 0,next_work_candidates:H,recent_completed:L,recent_activity:j,meta:{current_branch:m,current_commit:d,activeMissionsTotal:w,active_limit_applied:!!r,relevance_filtered:U.length<O.length?{shown:U.length,total:O.length}:void 0}};return{content:[{type:"text",text:JSON.stringify(_e,null,2)}],suggestedNext:A}}let Y=l>0?u.findRecentDecisionActivity(l):void 0,he=E;a&&(he=E.map(j=>({...j,strategy_graph:void 0,verification_context:void 0,outcome_contract:void 0})));let pe=x.map(j=>{let F=E.find(_e=>_e.id===j);return{parent:a?{...F,strategy_graph:void 0,verification_context:void 0}:F,children:D[j]??[]}}),ae=$.filter(j=>!v.has(j.id)),ye={scope:"project",altitude:"atmosphere",counts:p.getStats(),analytics:p.getAnalytics(),hierarchy:pe.length>0?pe:void 0,standalone_active:ae.length>0?ae:void 0,active_missions:pe.length===0?he:void 0,next_work_candidates:H.map(R),recent_completed:L,recent_activity:Y,meta:{current_branch:m,current_commit:d,activeMissionsTotal:w,active_limit_applied:!!r,relevance_filtered:U.length<O.length?{shown:U.length,total:O.length}:void 0}};return{content:[{type:"text",text:JSON.stringify(ye,null,2)}],suggestedNext:A}}let h;if(t?h=p.findById(t):h=p.findActive(m||void 0)[0],!h)return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let g=null;try{h.strategy_graph&&(g=JSON.parse(h.strategy_graph))}catch{ut.warn({missionId:h.id},"Failed to parse strategy graph")}if(s==="orbit"){let E={altitude:"orbit",mission:{id:h.id,name:h.name,goal:h.goal,status:h.status,last_updated:new Date(h.updated_at*1e3).toISOString()},strategy_snapshot:g};return{content:[{type:"text",text:JSON.stringify(E,null,2)}]}}let _="No external shadow changes detected.";try{new kt(e).analyzeGhostChanges(h.commit_sha||void 0),_="Shadow Trace completed: Checked for external modifications."}catch(E){ut.warn({error:E},"Ghost analysis failed")}let b={repaired:0,failed:0};try{b=new Pe(e).detectAndRepairShifts()}catch(E){ut.warn({error:E},"Symbol shift repair failed")}if(s==="ground"){let E={altitude:"ground",mission:{id:h.id,name:h.name,goal:h.goal,status:h.status,last_updated:new Date(h.updated_at*1e3).toISOString(),git_branch:h.git_branch,commit_sha:h.commit_sha,outcome_contract:h.outcome_contract},artifacts:p.getArtifacts(h.id),shadow_trace:{ghost_analysis:_,symbols_repaired:b.repaired,symbols_missing:b.failed},context:{current_commit:d,working_set:p.getWorkingSet(h.id).map(w=>w.file_path)},strategy_snapshot:g,recent_activity:u.findByMission(h.id,l||20),ancestor_activity_summary:[],predictive_collisions:[]};try{let w=new sn(e);E.predictive_collisions=await w.analyzePotentialCollisions()}catch(w){ut.warn({error:w},"Predictive collision analysis failed")}if(h.parent_id){let w=u.findByMission(h.parent_id,5);E.ancestor_activity_summary=w.map(x=>({type:x.type,content:x.content,date:new Date(x.created_at*1e3).toISOString()}))}return{content:[{type:"text",text:JSON.stringify(E,null,2)}]}}let y={altitude:"atmosphere",mission:{id:h.id,name:h.name,goal:h.goal,status:h.status,last_updated:new Date(h.updated_at*1e3).toISOString(),git_branch:h.git_branch,commit_sha:h.commit_sha,outcome_contract:h.outcome_contract},artifacts:p.getArtifacts(h.id),shadow_trace:{ghost_analysis:_,symbols_repaired:b.repaired,symbols_missing:b.failed},context:{current_commit:d,working_set:p.getWorkingSet(h.id).map(E=>E.file_path)},strategy_snapshot:g,recent_activity:u.findByMissionPreferCrystal(h.id,15),ancestor_activity_summary:[],predictive_collisions:[]};try{let E=new sn(e);y.predictive_collisions=await E.analyzePotentialCollisions()}catch(E){ut.warn({error:E},"Predictive collision analysis failed")}if(h.parent_id){let E=u.findByMissionPreferCrystal(h.parent_id,3);y.ancestor_activity_summary=E.map(w=>({type:w.type,content:w.content,date:new Date(w.created_at*1e3).toISOString()}))}return{content:[{type:"text",text:JSON.stringify(y,null,2)}]}}catch(h){throw ut.error({error:h,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${h instanceof Error?h.message:String(h)}`)}}W();z();z();W();W();var Fl=S.child({module:"reasoning-engine"}),rs=class{analyze(e){Fl.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[]};for(let n of e){let s=n.content.toLowerCase(),r=this.matchesContext(s,n.type),o=this.matchesDecision(s,n.type),c=this.matchesConsequence(s,n.type),a=this.matchesRecommendation(s,n.type);r?t.context.push(n.content):o?t.decisions.push(n.content):a?t.recommendations.push(n.content):c?t.consequences.push(n.content):n.type==="decision"?t.decisions.push(n.content):n.type==="discovery"||n.type==="fix"?t.consequences.push(n.content):t.unclassified.push(n.content)}return t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(s=>e.includes(s))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(s=>e.includes(s))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(s=>e.includes(s))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(s=>e.includes(s))}};var os=S.child({module:"briefing-engine"}),ze=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=C.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new rs,this.persistencePivot=new Re(e)}async distillMission(e,t=!0){os.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 s=this.reasoningEngine.analyze(n),r=new Set(n.map(c=>c.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
|
|
792
820
|
|
|
793
821
|
`;if(o+=`## Summary of Intent
|
|
794
822
|
`,o+=`Collected ${n.length} intent events across ${r.size} symbols.
|
|
@@ -810,8 +838,8 @@ WHERE i.resolved_path IS NOT NULL`);return t.join(`
|
|
|
810
838
|
`}),o+=`
|
|
811
839
|
`),o+=`
|
|
812
840
|
---
|
|
813
|
-
*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),zn.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(c){zn.error({missionId:e,error:c},"Failed to sync ADR to Git Notes")}}else zn.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.findByMission(e,500);if(t>2)return n;let s=this.missions.findByParentId(e);for(let r of s)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};P();import{Visitor as sl}from"@swc/core/Visitor.js";import*as To from"@swc/core";var il=_.child({module:"verification-engine"}),Ms=class extends sl{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)}},Gn=class{async verify(e,t){try{let n=await To.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),s=new Ms(t);s.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=s.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=s.foundUsage,!r){let c=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${c} 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 il.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};import Ro from"path";import qn from"fs";var bt=_.child({module:"mcp:tools:ops:track"});async function vo(i){let{repoPath:e,missionId:t,stepId:n,status:s,contextPivot:r,updates:o,artifacts:c}=i,{missions:a,intentLogs:l}=C.getInstance(e),p=fe(e);bt.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:c?.length},"Updating mission status");try{if(c&&Array.isArray(c))for(let m of c)a.addArtifact(t,m.type,m.identifier,m.metadata);let d=[];if(o&&Array.isArray(o)&&d.push(...o),n&&s&&d.push({stepId:n,status:s,contextPivot:r}),s&&!n){if(a.updateStatus(t,s,p||void 0),l.create({mission_id:t,type:"system",content:`Mission status changed to "${s}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),s==="completed")try{await new Ge(e).distillMission(t),bt.info({missionId:t},"Auto-Synthesis completed successfully")}catch(m){bt.warn({synthesisError:m,missionId:t},"Auto-Synthesis deferred or failed")}if(!d.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:s,message:"Mission status updated successfully.",artifacts_added:c?.length||0,commit:p},null,2)}]}}if(d.length===0&&(!c||c.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let u=[];for(let m of d){let{stepId:f,status:h,contextPivot:b}=m,y=a.findById(t);if(!y)throw new Error(`Mission ID ${t} not found`);let g=JSON.parse(y.strategy_graph||"{}"),S=null;if(Array.isArray(g)?S=g.find(R=>R.id===f):g.nodes&&Array.isArray(g.nodes)?S=g.nodes.find(R=>R.id===f):g.steps?Array.isArray(g.steps)?S=g.steps.find(R=>R.id===f):S=g.steps[f]:g[f]&&(S=g[f]),!S)throw new Error(`Step ID "${f}" not found`);if(h==="completed"&&S.verification){let R=new Gn,w=Array.isArray(S.verification)?S.verification:[S.verification];for(let T of w){let v=T.filePath;if(v&&!Ro.isAbsolute(v)&&(v=Ro.join(e,v)),v){if(!qn.existsSync(v))throw new Error(`Verification failed: File not found at ${v}`);let k=await R.verify(qn.readFileSync(v,"utf8"),T);if(!k.passed)throw new Error(`Verification failed: ${k.errors.join("")}`)}else{let k=a.getWorkingSet(t),F=!1;for(let x of k){if(!qn.existsSync(x.file_path))continue;if((await R.verify(qn.readFileSync(x.file_path,"utf8"),T)).passed){F=!0;break}}if(!F)throw new Error(`Verification failed for rule "${T.target}" in working set.`)}}}if(S.status=h,a.update(t,{strategy_graph:JSON.stringify(g),commit_sha:p}),l.create({mission_id:t,type:"system",content:`Step "${f}" updated to "${h}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),b)try{let R=JSON.parse(b);if(a.clearWorkingSet(t),R.files&&Array.isArray(R.files))for(let w of R.files)a.addToWorkingSet(t,w)}catch(R){bt.warn({error:R},"Failed to apply context pivot")}u.push({stepId:f,status:h})}try{await new ve(e).syncMissionToGitNotes(t)}catch(m){bt.warn({syncError:m,missionId:t},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,updates:u,artifacts_added:c?.length||0,message:"Status updated",commit:p},null,2)}]}}catch(d){throw bt.error({error:d,repoPath:e},"Failed to update status"),new Error(`Failed to update status: ${d instanceof Error?d.message:String(d)}`)}}P();var $o=_.child({module:"mcp:tools:ops:graph"});async function ko(i){let{repoPath:e,missionId:t,depth:n,limit:s,format:r="mermaid"}=i;$o.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(Co(),Io));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:s})}]}}catch(o){throw $o.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}U();P();var Bt=_.child({module:"mcp:tools:ops:log"});async function Lo(i){let{repoPath:e,missionId:t,type:n,content:s,filePath:r,symbolName:o}=i;Bt.info({repoPath:e,type:n,symbolName:o},"Logging intent");let{missions:c,exports:a,intentLogs:l}=C.getInstance(e);try{let p=t??null;if(p){if(!c.findById(p))throw new Error(`Mission ${p} not found. Use shadow_ops_briefing to see available missions.`)}else{let h=c.findActive();h.length>0?(p=h[0].id,Bt.debug({missionId:p},"Auto-resolved to active mission")):(p=null,Bt.debug("No active mission found, logging as system/unlinked intent"))}let d=null,u=null,m=o||null;if(o){let b=(r?a.findByNameAndFile(o,r):a.findByName(o))[0];b?(d=b.id,u=b.signature,m=b.name):Bt.warn({symbolName:o,filePath:r},"Symbol not found for intent linking")}let f=l.create({mission_id:p,symbol_id:d,file_path:r||null,type:n,content:s,confidence:1,symbol_name:m,signature:u,commit_sha:null});return{content:[{type:"text",text:JSON.stringify({logId:f,missionId:p,symbolId:d,status:"logged",message:d?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(p){throw Bt.error({error:p,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${p instanceof Error?p.message:String(p)}`)}}U();P();var No=_.child({module:"mcp:tools:ops:synthesize"});async function Ao(i){let{repoPath:e,missionId:t}=i;No.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=C.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new Ge(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics},null,2)}]}}catch(s){throw No.error({error:s,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${s instanceof Error?s.message:String(s)}`)}}import rl from"path";var V={...E,box:se,table:an,list:li};async function Mo(i){let[e,...t]=i;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${V.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${V.bold("Actions: ")}`),console.log(` ${V.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${V.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${V.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${V.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${V.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${V.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await B(async()=>{let n=t[0]?rl.resolve(t[0]):process.cwd();switch(e){case"plan":{let[s,r,o]=t;if(!r||!o){console.error(` ${V.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let c=await _o({repoPath:n,name:r,goal:o}),a=JSON.parse(c.content[0].text);console.log(` ${V.green("\u2714")} Mission planned (ID: ${a.missionId})`);break}case"update":{let[s,r,o]=t;if(!r||!o){console.error(` ${V.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await vo({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${V.green("\u2714")} Status updated to ${o}`);break}case"log":{let[s,r,o,...c]=t;if(!r||!o||c.length===0){console.error(` ${V.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await Lo({repoPath:n,missionId:parseInt(r),type:o,content:c.join(" ")}),console.log(` ${V.green("\u2714")} Intent logged`);break}case"synthesize":{let[s,r]=t;if(!r){console.error(` ${V.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await Ao({repoPath:n,missionId:parseInt(r)});console.log(""),V.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[s,r]=t,o=await ko({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let s=await xo({repoPath:n});if(s.content&&s.content[0]){let r=s.content[0].text;try{let o=JSON.parse(r);if(o.mission){console.log(""),console.log(V.bold(V.cyan(` Mission Dashboard: ${o.mission.name} `))),V.box("Tactical Goal",o.mission.goal,"cyan");let c=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",a=[["Status",V.bold(V[c](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];V.table(["Field","Value"],a),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${V.bold("Recent Activity:")}`),V.list(o.recent_activity.slice(0,5).map(l=>`${V.dim(`[${l.type.toUpperCase()}]`)} ${l.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import Ds from"path";async function Po(i){let[e,...t]=i;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${E.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${E.bold("Actions: ")}`),console.log(` ${E.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${E.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await B(async()=>{let n=t[0]?Ds.resolve(t[0]):process.cwd();if(e==="symbol"){let s=t[1];if(!s){console.error(` ${E.red("\u2716")} Please provide a symbol name`);return}let r=await gt({repoPath:n,symbolName:s});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let s=t[1];if(!s){console.error(` ${E.red("\u2716")} Please provide a file path`);return}let r=Ds.isAbsolute(s)?s:Ds.join(n,s),o=await Mn({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var Do=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],ol=["--help","-h","--version","-v","--dir","-d"],al={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 cl(){let i=Object.entries(al).map(([n,s])=>` ${n}) opts="${s.join(" ")}" ;;`).join(`
|
|
814
|
-
`),e=
|
|
841
|
+
*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),os.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(c){os.error({missionId:e,error:c},"Failed to sync ADR to Git Notes")}}else os.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 s=this.missions.findByParentId(e);for(let r of s)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};W();import{Visitor as Wl}from"@swc/core/Visitor.js";import*as Go from"@swc/core";var Hl=S.child({module:"verification-engine"}),Ks=class extends Wl{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)}},as=class{async verify(e,t){try{let n=await Go.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),s=new Ks(t);s.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=s.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=s.foundUsage,!r){let c=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${c} 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 Hl.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};import qo from"path";import cs from"fs";var De=S.child({module:"mcp:tools:ops:track"});async function Jo(i,e,t){let{missions:n,intentLogs:s}=C.getInstance(i),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 a=n.findById(r.parent_id);if(!(!a||a.status==="completed")){De.info({parentId:a.id,childCount:o.length},"All children completed \u2014 cascading parent completion"),n.updateStatus(a.id,"completed",t||void 0),s.create({mission_id:a.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 ze(i).distillMission(a.id),De.info({parentId:a.id},"Parent Auto-Synthesis completed")}catch(l){De.warn({synthesisError:l,parentId:a.id},"Parent Auto-Synthesis deferred")}try{await new Re(i).syncMissionToGitNotes(a.id)}catch(l){De.warn({syncError:l,parentId:a.id},"Parent Git Notes sync deferred")}await Jo(i,a.id,t)}}async function Yo(i){let{repoPath:e,missionId:t,stepId:n,status:s,contextPivot:r,updates:o,artifacts:c}=i,{missions:a,intentLogs:l}=C.getInstance(e),p=xe(e);De.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:c?.length},"Updating mission status");try{if(c&&Array.isArray(c))for(let m of c)a.addArtifact(t,m.type,m.identifier,m.metadata);let u=[];if(o&&Array.isArray(o)&&u.push(...o),n&&s&&u.push({stepId:n,status:s,contextPivot:r}),s&&!n){if(a.updateStatus(t,s,p||void 0),l.create({mission_id:t,type:"system",content:`Mission status changed to "${s}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),s==="completed"){try{await new ze(e).distillMission(t),De.info({missionId:t},"Auto-Synthesis completed successfully")}catch(m){De.warn({synthesisError:m,missionId:t},"Auto-Synthesis deferred or failed")}await Jo(e,t,p)}if(!u.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:s,message:"Mission status updated successfully.",artifacts_added:c?.length||0,commit:p},null,2)}]}}if(u.length===0&&(!c||c.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let d=[];for(let m of u){let{stepId:h,status:g,contextPivot:_}=m,b=a.findById(t);if(!b)throw new Error(`Mission ID ${t} not found`);let y=JSON.parse(b.strategy_graph||"{}"),E=null;if(Array.isArray(y)?E=y.find(w=>w.id===h):y.nodes&&Array.isArray(y.nodes)?E=y.nodes.find(w=>w.id===h):y.steps?Array.isArray(y.steps)?E=y.steps.find(w=>w.id===h):E=y.steps[h]:y[h]&&(E=y[h]),!E)throw new Error(`Step ID "${h}" not found`);if(g==="completed"&&E.verification){let w=new as,x=Array.isArray(E.verification)?E.verification:[E.verification];for(let v of x){let k=v.filePath;if(k&&!qo.isAbsolute(k)&&(k=qo.join(e,k)),k){if(!cs.existsSync(k))throw new Error(`Verification failed: File not found at ${k}`);let N=await w.verify(cs.readFileSync(k,"utf8"),v);if(!N.passed)throw new Error(`Verification failed: ${N.errors.join("")}`)}else{let N=a.getWorkingSet(t),O=!1;for(let T of N){if(!cs.existsSync(T.file_path))continue;if((await w.verify(cs.readFileSync(T.file_path,"utf8"),v)).passed){O=!0;break}}if(!O)throw new Error(`Verification failed for rule "${v.target}" in working set.`)}}}if(E.status=g,a.update(t,{strategy_graph:JSON.stringify(y),commit_sha:p}),l.create({mission_id:t,type:"system",content:`Step "${h}" updated to "${g}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),_)try{let w=JSON.parse(_);if(a.clearWorkingSet(t),w.files&&Array.isArray(w.files))for(let x of w.files)a.addToWorkingSet(t,x)}catch(w){De.warn({error:w},"Failed to apply context pivot")}d.push({stepId:h,status:g})}try{await new Re(e).syncMissionToGitNotes(t)}catch(m){De.warn({syncError:m,missionId:t},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,updates:d,artifacts_added:c?.length||0,message:"Status updated",commit:p},null,2)}]}}catch(u){throw De.error({error:u,repoPath:e},"Failed to update status"),new Error(`Failed to update status: ${u instanceof Error?u.message:String(u)}`)}}W();var Xo=S.child({module:"mcp:tools:ops:graph"});async function Zo(i){let{repoPath:e,missionId:t,depth:n,limit:s,format:r="mermaid"}=i;Xo.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(Ko(),Qo));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:s})}]}}catch(o){throw Xo.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}z();W();var rn=S.child({module:"mcp:tools:ops:log"});async function ea(i){let{repoPath:e,missionId:t,type:n,content:s,filePath:r,symbolName:o}=i;rn.info({repoPath:e,type:n,symbolName:o},"Logging intent");let{missions:c,exports:a,intentLogs:l}=C.getInstance(e);try{let p=t??null;if(p){if(!c.findById(p))throw new Error(`Mission ${p} not found. Use shadow_ops_briefing to see available missions.`)}else{let g=c.findActive();g.length>0?(p=g[0].id,rn.debug({missionId:p},"Auto-resolved to active mission")):(p=null,rn.debug("No active mission found, logging as system/unlinked intent"))}let u=null,d=null,m=o||null;if(o){let _=(r?a.findByNameAndFile(o,r):a.findByName(o))[0];_?(u=_.id,d=_.signature,m=_.name):rn.warn({symbolName:o,filePath:r},"Symbol not found for intent linking")}let h=l.create({mission_id:p,symbol_id:u,file_path:r||null,type:n,content:s,confidence:1,symbol_name:m,signature:d,commit_sha:null});return{content:[{type:"text",text:JSON.stringify({logId:h,missionId:p,symbolId:u,status:"logged",message:u?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(p){throw rn.error({error:p,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${p instanceof Error?p.message:String(p)}`)}}z();W();var ta=S.child({module:"mcp:tools:ops:synthesize"});async function na(i){let{repoPath:e,missionId:t}=i;ta.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=C.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new ze(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics},null,2)}]}}catch(s){throw ta.error({error:s,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${s instanceof Error?s.message:String(s)}`)}}import Ul from"path";var Q={...f,box:X,table:Tn,list:Mi};async function sa(i){let[e,...t]=i;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${Q.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${Q.bold("Actions: ")}`),console.log(` ${Q.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${Q.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${Q.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${Q.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${Q.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${Q.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await B(async()=>{let n=t[0]?Ul.resolve(t[0]):process.cwd();switch(e){case"plan":{let[s,r,o]=t;if(!r||!o){console.error(` ${Q.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let c=await zo({repoPath:n,name:r,goal:o}),a=JSON.parse(c.content[0].text);console.log(` ${Q.green("\u2714")} Mission planned (ID: ${a.missionId})`);break}case"update":{let[s,r,o]=t;if(!r||!o){console.error(` ${Q.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await Yo({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${Q.green("\u2714")} Status updated to ${o}`);break}case"log":{let[s,r,o,...c]=t;if(!r||!o||c.length===0){console.error(` ${Q.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await ea({repoPath:n,missionId:parseInt(r),type:o,content:c.join(" ")}),console.log(` ${Q.green("\u2714")} Intent logged`);break}case"synthesize":{let[s,r]=t;if(!r){console.error(` ${Q.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await na({repoPath:n,missionId:parseInt(r)});console.log(""),Q.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[s,r]=t,o=await Zo({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let s=await Bo({repoPath:n});if(s.content&&s.content[0]){let r=s.content[0].text;try{let o=JSON.parse(r);if(o.mission){console.log(""),console.log(Q.bold(Q.cyan(` Mission Dashboard: ${o.mission.name} `))),Q.box("Tactical Goal",o.mission.goal,"cyan");let c=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",a=[["Status",Q.bold(Q[c](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];Q.table(["Field","Value"],a),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${Q.bold("Recent Activity:")}`),Q.list(o.recent_activity.slice(0,5).map(l=>`${Q.dim(`[${l.type.toUpperCase()}]`)} ${l.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import Zs from"path";async function ia(i){let[e,...t]=i;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${f.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${f.bold("Actions: ")}`),console.log(` ${f.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${f.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await B(async()=>{let n=t[0]?Zs.resolve(t[0]):process.cwd();if(e==="symbol"){let s=t[1];if(!s){console.error(` ${f.red("\u2716")} Please provide a symbol name`);return}let r=await Lt({repoPath:n,symbolName:s});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let s=t[1];if(!s){console.error(` ${f.red("\u2716")} Please provide a file path`);return}let r=Zs.isAbsolute(s)?s:Zs.join(n,s),o=await Qn({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var ra=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],jl=["--help","-h","--version","-v","--dir","-d"],zl={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 Bl(){let i=Object.entries(zl).map(([n,s])=>` ${n}) opts="${s.join(" ")}" ;;`).join(`
|
|
842
|
+
`),e=ra.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
|
|
815
843
|
_liquid_shadow() {
|
|
816
844
|
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
817
845
|
local words=("\${COMP_WORDS[@]}")
|
|
@@ -821,7 +849,7 @@ _liquid_shadow() {
|
|
|
821
849
|
if [[ "\${words[$i]}" != -* ]]; then cmd="\${words[$i]}"; break; fi
|
|
822
850
|
((i++))
|
|
823
851
|
done
|
|
824
|
-
local opts="${
|
|
852
|
+
local opts="${jl.join(" ")}"
|
|
825
853
|
if [ -n "$cmd" ]; then
|
|
826
854
|
case "$cmd" in
|
|
827
855
|
${i}
|
|
@@ -833,11 +861,11 @@ ${i}
|
|
|
833
861
|
COMPREPLY=($(compgen -W "$opts" -- "$cur"))
|
|
834
862
|
}
|
|
835
863
|
complete -F _liquid_shadow liquid-shadow
|
|
836
|
-
`}function
|
|
864
|
+
`}function Gl(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
|
|
837
865
|
# Run after compinit (e.g. in .zshrc after compinit)
|
|
838
866
|
|
|
839
867
|
_liquid_shadow() {
|
|
840
|
-
local -a cmds; cmds=(${
|
|
868
|
+
local -a cmds; cmds=(${ra.map(e=>`'${e}'`).join(" ")})
|
|
841
869
|
if [ $CURRENT -eq 2 ]; then
|
|
842
870
|
_describe 'command' cmds
|
|
843
871
|
return
|
|
@@ -854,7 +882,7 @@ _liquid_shadow() {
|
|
|
854
882
|
_describe 'flag' fl
|
|
855
883
|
}
|
|
856
884
|
compdef _liquid_shadow liquid-shadow
|
|
857
|
-
`}async function
|
|
885
|
+
`}async function oa(i){i==="bash"?console.log(Bl()):i==="zsh"?console.log(Gl()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}import ql from"fs";import Jl from"path";var Yl=2e3;async function aa(i){let e=Jl.resolve(i);await B(async()=>{se("Watch mode");let t=Oe(e),n=null,s=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(f.dim(" Changes detected, reindexing...")),await G(e,5,!1,!0),console.log(f.green(" Reindex complete."))}catch(r){console.error(f.red(" Reindex failed:"),r instanceof Error?r.message:r)}},Yl)};try{ql.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&s()}),console.log(f.cyan(` Watching ${e}`)),console.log(f.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),Ee("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 J(e)}})}z();W();var Vl=S.child({module:"narrative-service"}),ls=class{missions;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t}=C.getInstance(e);this.missions=t,this.briefingEngine=new ze(e)}async generateChronicle(e={}){Vl.info(e,"Generating Repo Chronicle...");let n=this.missions.findAll().filter(l=>l.parent_id===null&&l.status!=="planned");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 s=e.offset||0,r=e.limit||10;n=n.slice(s,s+r);let o=[],c=[],a=[];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 m=[];for(let g of p)m.push(await this.mapMissionToEpisode(g));m.unshift(await this.mapMissionToEpisode(l));let h={kind:"initiative",root_mission_id:l.id,title:l.name,strategy_graph:l.strategy_graph?JSON.parse(l.strategy_graph):{},episodes:e.compact?[]:m,synthesized_narrative:e.compact?this.truncateText(d.adr):d.adr||""};o.push(h),a.push(h)}else{let m=await this.mapMissionToEpisode(l,d.adr,e.compact);c.push(m),a.push(m)}}return{repo_path:this.repoPath,generated_at:Date.now(),initiatives:o,unattached_episodes:c,timeline:a}}async mapMissionToEpisode(e,t,n=!1){let s=t;return s||(s=(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(s):s}}truncateText(e,t=300){return e?e.length<=t?e:e.slice(0,t)+"... (truncated)":""}renderChronicleMarkdown(e){let t=`# Repository Chronicle
|
|
858
886
|
|
|
859
887
|
`;if(t+=`*Generated at ${new Date(e.generated_at).toISOString()}*
|
|
860
888
|
|
|
@@ -865,4 +893,261 @@ compdef _liquid_shadow liquid-shadow
|
|
|
865
893
|
`,t+=`${n.adr_summary}
|
|
866
894
|
|
|
867
895
|
`),t+=`---
|
|
868
|
-
`;return t}};
|
|
896
|
+
`;return t}};W();import Ql from"path";async function ca(i,e){let t=Ql.resolve(i||process.cwd()),n=e.format==="json"?"json":"markdown",s=S.child({module:"cli:chronicle",repoPath:t});s.info("Generating repository chronicle...");try{let r=new ls(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){s.error({error:r},"Failed to generate chronicle"),console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}}import Ie from"fs";import st from"path";import Kl from"os";var ei={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\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:`---
|
|
897
|
+
name: chronicle
|
|
898
|
+
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.
|
|
899
|
+
---
|
|
900
|
+
|
|
901
|
+
# Repository Chronicle
|
|
902
|
+
|
|
903
|
+
Retrieve narrative archive from Git-native memory.
|
|
904
|
+
|
|
905
|
+
## \u{1F680} Workflow
|
|
906
|
+
|
|
907
|
+
1. **Recent History**: \`shadow_ops_chronicle\` (limit: 10, format: "markdown", repoPath) \u2014 Last 10 entries.
|
|
908
|
+
2. **Time-Filtered**:
|
|
909
|
+
- \`shadow_ops_chronicle\` (since: <unix>, limit: 20, repoPath)
|
|
910
|
+
- \`shadow_ops_chronicle\` (until: <unix>, limit: 20, repoPath)
|
|
911
|
+
3. **Structured Data**: \`shadow_ops_chronicle\` (format: "json", limit: 50, repoPath) \u2014 For processing.
|
|
912
|
+
4. **Paginated**: \`shadow_ops_chronicle\` (limit: 10, offset: 10, repoPath) \u2014 Second page.
|
|
913
|
+
|
|
914
|
+
## \u{1F6E0} Precise Tooling
|
|
915
|
+
|
|
916
|
+
| Chronicle Query | Atomic Tool |
|
|
917
|
+
| :--- | :--- |
|
|
918
|
+
| **Recent (Markdown)** | \`shadow_ops_chronicle\` (limit: 10, format: "markdown") |
|
|
919
|
+
| **Time Range** | \`shadow_ops_chronicle\` (since: <unix>, until: <unix>) |
|
|
920
|
+
| **JSON Data** | \`shadow_ops_chronicle\` (format: "json", limit: 50) |
|
|
921
|
+
| **Pagination** | \`shadow_ops_chronicle\` (limit: 10, offset: 10) |
|
|
922
|
+
|
|
923
|
+
## Output Formats
|
|
924
|
+
|
|
925
|
+
- **\`format: "markdown"\`** (default): Human-readable narrative feed with missions grouped as Strategic Initiatives and Standalone Episodes
|
|
926
|
+
- **\`format: "json"\`**: Structured data for programmatic analysis (includes missionId, steps, timestamps, ADRs)
|
|
927
|
+
|
|
928
|
+
## Use Cases
|
|
929
|
+
|
|
930
|
+
- **Onboarding**: Read last 10 entries to catch up
|
|
931
|
+
- **Release Notes**: Get completed missions since last release
|
|
932
|
+
- **ADR Review**: Extract all architectural decisions
|
|
933
|
+
- **Progress Reports**: Show what's been done this week
|
|
934
|
+
|
|
935
|
+
**Note:** Chronicle reads from Git Notes, so it's persistent across branches and clones.
|
|
936
|
+
`,shadow_continue:'---\nname: continue\ndescription: Get briefing, pick one mission from next_work_candidates, then work that mission to completion with all remaining steps in one run. Use when continuing work on missions, executing mission steps, or when the user asks to continue work, finish a mission, or proceed with development tasks.\n---\n\n**In one sentence:** Get briefing (+ optional trace), pick **one mission** from **next_work_candidates** (ranked by relevance), then work that mission to completion \u2014 all remaining steps in one run. Update and log as you go. No status reports; when you\'re done with that mission, it\'s done.\n\n---\n## 1. Context\n\n- **Option A (one shot):** `shadow_ops_context` (repoPath) \u2192 returns hologram + chronicle(5) + **briefing** (counts, **next_work_candidates** ranked by relevance). Use when you want architecture + history + backlog in one call at the start of /continue.\n- **Option B:** `shadow_ops_briefing` (scope: "project", repoPath) \u2192 **next_work_candidates** (relevance-ranked), hierarchy, analytics.\n - Use **altitude** to control output density: `orbit` (~200 tokens, counts + candidates only), `atmosphere` (default, strategy + crystals), `ground` (raw logs + working set + collisions).\n- `shadow_sync_trace` (repoPath) only if you care about external changes. Otherwise skip.\n\n## 2. Pick one mission\n\n- **`next_work_candidates`** are ranked by the MissionRelevanceScorer (recency \xD7 0.4 + activity \xD7 0.3 + status \xD7 0.2 + blockers \xD7 0.1). Higher score = more relevant.\n- Choose the top-ranked candidate. Prefer in-progress over planned. Parent-only missions (umbrellas) are already filtered out.\n\n## 3. Work the whole mission\n\n- For that mission, run through **all remaining steps** (not just one):\n - **Surgical Discovery:** `shadow_analyze_flow` (symbolName, filePath, repoPath).\n - **Execute Step**: Set in-progress \u2192 implement \u2192 `shadow_ops_track` (missionId, stepId, status: "completed", contextPivot, repoPath).\n - **Atomic Logging:** At least once per step. `shadow_ops_log` (missionId, type: "decision", content, symbolName, repoPath).\n- **Seal the mission**: `shadow_ops_track` (missionId, status: "completed", repoPath).\n - This **auto-triggers**: ADR synthesis, Git Notes persistence, and cascade parent completion (if all sibling missions are also done, the parent auto-completes too).\n - No need to call `shadow_ops_synthesize` separately \u2014 it\'s automatic on completion.\n- **Optional \u2014 Crystallize** (for long-running missions with many logs): `shadow_ops_crystallize` (missionId, repoPath) compresses raw intent logs into a single crystal summary. Useful mid-mission to keep briefings lean.\n\n## \u{1F6E0} Precise Tooling\n\n| Action | Atomic Tool | Example |\n| :--- | :--- | :--- |\n| **Context (one shot)** | `shadow_ops_context` | repoPath \u2014 hologram + chronicle + briefing |\n| **Briefing** | `shadow_ops_briefing` | scope: "project", altitude: "orbit", repoPath |\n| **Flow Trace** | `shadow_analyze_flow` | symbolName: "handleRequest", filePath, repoPath |\n| **Step Update** | `shadow_ops_track` | missionId: 4, stepId: "s2", status: "completed" |\n| **Intent Log** | `shadow_ops_log` | missionId: 4, type: "fix", content: "..." |\n| **Complete Mission** | `shadow_ops_track` | missionId: 4, status: "completed" \u2014 auto-synthesizes ADR |\n| **Crystallize** | `shadow_ops_crystallize` | missionId: 4 \u2014 compress logs mid-mission |\n\n*Note: Always use `symbolName` in `shadow_ops_log` to create Liquid Anchors.*\n\n## 4. Don\'t\n\n- Don\'t do one step and stop \u2014 /continue is "finish a mission," not "do one step."\n- Don\'t call `shadow_ops_synthesize` after completing \u2014 it\'s automatic on `status: "completed"`.\n- Don\'t long status reports. Don\'t ask "what should I work on?" unless a real tie. Don\'t auto-commit.\n\n---\n\n**Tools:** `shadow_ops_context` (optional start), `shadow_ops_briefing`, `shadow_ops_track`, `shadow_ops_log`, `shadow_ops_crystallize`, `shadow_sync_trace`. For discovery: `shadow_search_*`, `shadow_recon_*`, `shadow_analyze_*`.\n',shadow_crystallize:`---
|
|
937
|
+
name: crystallize
|
|
938
|
+
description: Compress a mission's intent logs into a dense crystal summary for token-efficient briefings. Use when a mission has accumulated many raw logs, when briefings are too verbose, or when the user asks about log compression, crystallization, or context reduction.
|
|
939
|
+
---
|
|
940
|
+
|
|
941
|
+
# Intent Log Crystallization
|
|
942
|
+
|
|
943
|
+
Compress raw intent logs into a single crystal summary node. The crystal replaces verbose raw logs in briefings, reducing token usage while preserving the mission's key decisions, context, and consequences.
|
|
944
|
+
|
|
945
|
+
## When to Crystallize
|
|
946
|
+
|
|
947
|
+
- A mission has **10+ raw intent logs** and briefings are getting verbose.
|
|
948
|
+
- Mid-mission, before requesting a detailed briefing \u2014 keeps \`atmosphere\` altitude lean.
|
|
949
|
+
- Before synthesis (optional) \u2014 produces cleaner ADRs from compressed input.
|
|
950
|
+
- The briefing at \`atmosphere\` altitude already prefers crystals over raw logs (\`findByMissionPreferCrystal\`), so crystallizing makes those briefings significantly leaner.
|
|
951
|
+
|
|
952
|
+
## Workflow
|
|
953
|
+
|
|
954
|
+
1. **Crystallize**: \`shadow_ops_crystallize\` (missionId, repoPath) \u2014 Compresses all raw logs into one crystal node. Raw logs are marked as \`absorbed\`.
|
|
955
|
+
2. **Verify**: \`shadow_ops_briefing\` (scope: "mission", missionId, altitude: "atmosphere", repoPath) \u2014 Crystal should appear in \`recent_activity\` instead of raw logs.
|
|
956
|
+
|
|
957
|
+
## Precise Tooling
|
|
958
|
+
|
|
959
|
+
| Action | Atomic Tool | Usage |
|
|
960
|
+
| :--- | :--- | :--- |
|
|
961
|
+
| **Crystallize** | \`shadow_ops_crystallize\` | missionId, repoPath \u2014 compress raw logs |
|
|
962
|
+
| **Check Status** | \`shadow_ops_briefing\` (altitude: "atmosphere") | Verify crystal appears in activity |
|
|
963
|
+
| **Full Logs** | \`shadow_ops_briefing\` (altitude: "ground") | Still shows raw logs if needed |
|
|
964
|
+
|
|
965
|
+
## What the Crystal Contains
|
|
966
|
+
|
|
967
|
+
- Mission name and ID
|
|
968
|
+
- Count of compressed logs and symbols
|
|
969
|
+
- Log types present (decision, fix, discovery, blocker)
|
|
970
|
+
- Structured breakdown: decisions, context, consequences, recommendations
|
|
971
|
+
|
|
972
|
+
## Notes
|
|
973
|
+
|
|
974
|
+
- Crystallization is **idempotent**: if no new raw logs exist, it reports \`already_crystallized\`.
|
|
975
|
+
- New logs added after crystallization remain as raw until the next crystallize call.
|
|
976
|
+
- Raw logs are **not deleted** \u2014 they're marked as absorbed. \`ground\` altitude still shows them.
|
|
977
|
+
`,shadow_mission:`---
|
|
978
|
+
name: mission
|
|
979
|
+
description: Define the objective, strategy, and success criteria for a new development mission. Use when planning strategic initiatives, creating missions, setting up development goals, or when the user asks about mission planning, strategic alignment, or outcome contracts.
|
|
980
|
+
---
|
|
981
|
+
|
|
982
|
+
# Mission Strategy & Setup
|
|
983
|
+
|
|
984
|
+
Define the objective, strategy, and success criteria for a new mission. This workflow is for **Strategic Alignment and Planning**.
|
|
985
|
+
|
|
986
|
+
> **IMPORTANT**: This workflow stops at the "Ready to Execute" state. For implementation and automated execution, use **/continue**.
|
|
987
|
+
|
|
988
|
+
## Workflow
|
|
989
|
+
|
|
990
|
+
1. **Session Context**: \`shadow_ops_context\` (repoPath) \u2014 **ONE CALL** for hologram + chronicle(5) + briefing (with relevance-ranked \`next_work_candidates\`). Check existing candidates and recent decisions before creating new work.
|
|
991
|
+
2. **Optional Expanded Context** (only if needed):
|
|
992
|
+
- \`shadow_recon_topography\` (repoPath) \u2014 Detailed layer breakdown to align goal with architecture.
|
|
993
|
+
- \`shadow_ops_chronicle\` (limit: 10, repoPath) \u2014 More historical ADRs if 5 isn't enough.
|
|
994
|
+
- \`shadow_ops_briefing\` (scope: "project", altitude: "ground", repoPath) \u2014 Full detail with analytics, collisions, and working sets.
|
|
995
|
+
3. **Strategic Plan**: \`shadow_ops_plan\` (name, goal, outcomeContract, ...).
|
|
996
|
+
* **Strategy DAG**: Define logical steps and verification rules.
|
|
997
|
+
* **Initiative vs Mission**: Decide if this is a parent (Initiative) or a leaf (Mission). Parent missions auto-complete via cascade when all children finish.
|
|
998
|
+
4. **Alignment**: Present the plan to the user. Do not begin execution until the user approves the strategy.
|
|
999
|
+
|
|
1000
|
+
## Precise Tooling
|
|
1001
|
+
|
|
1002
|
+
| Setup Action | Precise Tool Call | Usage |
|
|
1003
|
+
| :--- | :--- | :--- |
|
|
1004
|
+
| **Session Start** | \`shadow_ops_context\` | **START HERE** \u2014 hologram + chronicle + briefing in one call |
|
|
1005
|
+
| **Establish Plan** | \`shadow_ops_plan\` | Create the mission and strategy. |
|
|
1006
|
+
| **Architectural Map** | \`shadow_recon_topography\` | Contextualize the target layers (if context wasn't enough). |
|
|
1007
|
+
| **Detailed Briefing** | \`shadow_ops_briefing\` (altitude: "ground") | Full analytics, collisions, working sets. |
|
|
1008
|
+
| **Lean Briefing** | \`shadow_ops_briefing\` (altitude: "orbit") | Counts + candidates only (~200 tokens). |
|
|
1009
|
+
| **Graph View** | \`shadow_ops_graph\` | Visualize the initiative's hierarchy. |
|
|
1010
|
+
|
|
1011
|
+
*Note: **Always start with \`shadow_ops_context\`** for instant mission landscape + architectural context. Ensure the \`outcomeContract\` is binary and verifiable. Parent initiatives auto-cascade on child completion \u2014 no manual closing needed.*
|
|
1012
|
+
|
|
1013
|
+
## Briefing Altitude Levels
|
|
1014
|
+
|
|
1015
|
+
- **\`orbit\`** (~200 tokens): Counts + relevance-ranked candidates only. Use for quick checks.
|
|
1016
|
+
- **\`atmosphere\`** (default): Strategy graphs, crystal summaries, hierarchy, analytics.
|
|
1017
|
+
- **\`ground\`** (full): Raw logs, working sets, collision analysis, ancestor activity.
|
|
1018
|
+
|
|
1019
|
+
## Intent Logging (Strategic Quality)
|
|
1020
|
+
|
|
1021
|
+
Capture the "Why" and "How" during the planning phase to ensure the final ADR has architectural depth.
|
|
1022
|
+
|
|
1023
|
+
* **Decision Logs**: Capture why a specific strategy or library was chosen.
|
|
1024
|
+
* **Discovery Logs**: Record insights found during initial reconnaissance.
|
|
1025
|
+
|
|
1026
|
+
**Hand-off**: Once the mission is planned and logged, the setup phase is over. Execute via \`/continue\`.
|
|
1027
|
+
`,shadow_onboard:'---\nname: onboard\ndescription: Initialize and analyze a new repository for deep intelligence by building semantic index, syncing state, activating git hooks, and establishing missions. Use when onboarding to a new repository, initializing Shadow Engine, setting up git hooks, or when the user asks about repository setup, initialization, or first-time configuration.\n---\n\n# Repository Onboarding\n\nInitialize and analyze a new repository for deep intelligence.\n\n## Workflow\n\n1. **Semantic Init**: `shadow_recon_onboard` (repoPath) \u2014 **Only run once** per repo to build the baseline. Auto-populates the hologram.\n2. **Read Hologram**: `shadow_recon_hologram` (repoPath) \u2014 Get instant architectural context (~1300 tokens: topography + gravity zones).\n3. **Unified Sync**: `shadow_sync_trace` (repoPath) \u2014 **The One-Stop Shop**. Performs indexing + ghost analysis + mission re-hydration.\n4. **Active Briefing**: `shadow_ops_briefing` (scope: "project", altitude: "atmosphere", repoPath) \u2014 Resumes the shared backlog with relevance-ranked candidates.\n - Use `altitude: "orbit"` for a lean overview (~200 tokens), or `altitude: "ground"` for full detail.\n5. **Architectural Deep Dive** (optional):\n - `shadow_recon_topography` (repoPath) \u2014 View layers (Entry/Logic/Data/Utility/Test).\n - `shadow_ops_chronicle` (limit: 5, repoPath) \u2014 Narrative feed.\n6. **Hooks Activation**: `shadow_env_hooks` (action: "install", repoPath).\n7. **Establish Mission**: `shadow_ops_plan` (name, goal, repoPath).\n\n## Precise Tooling\n\n| Action | Atomic Tool |\n| :--- | :--- |\n| **Index** | `shadow_recon_onboard` |\n| **Hologram** | `shadow_recon_hologram` (repoPath) |\n| **Layers** | `shadow_recon_topography` |\n| **History** | `shadow_ops_chronicle` (limit: 10) |\n| **Resume (lean)** | `shadow_ops_briefing` (scope: "project", altitude: "orbit") |\n| **Resume (full)** | `shadow_ops_briefing` (scope: "project", altitude: "atmosphere") |\n| **Hooks** | `shadow_env_hooks` (action: "install") |\n\n*Note: Always use absolute paths for `repoPath`. Call `shadow_recon_hologram` immediately after init for instant architectural context.*\n',shadow_research:`---
|
|
1028
|
+
name: research
|
|
1029
|
+
description: Conduct high-signal research for external dependencies by combining local context, web search, and Context7 documentation. Use when researching libraries, checking integration examples, verifying versions, or when the user asks about external dependencies, library documentation, or integration patterns.
|
|
1030
|
+
---
|
|
1031
|
+
|
|
1032
|
+
# External Research
|
|
1033
|
+
|
|
1034
|
+
High-signal research for external dependencies.
|
|
1035
|
+
|
|
1036
|
+
## \u{1F680} Workflow
|
|
1037
|
+
|
|
1038
|
+
1. **Local Context**: \`shadow_search_concept\` (query: "library name", repoPath). Find existing integration examples.
|
|
1039
|
+
2. **Web Search**: Use the \`WebSearch\` tool for official docs and latest versions.
|
|
1040
|
+
3. **Deep Intel (Context7)**: resolve-library-id, query-docs (server: user-context7).
|
|
1041
|
+
4. **Integration Check**: \`shadow_inspect_file\` (filePath, detailLevel: "signatures", repoPath).
|
|
1042
|
+
5. **Log Findings**: \`shadow_ops_log\` (type: "discovery", content, repoPath).
|
|
1043
|
+
|
|
1044
|
+
## \u{1F6E0} Precise Tooling
|
|
1045
|
+
|
|
1046
|
+
| Discovery Layer | Atomic Tool |
|
|
1047
|
+
| :--- | :--- |
|
|
1048
|
+
| **Local Usage** | \`shadow_search_concept\` (query, **compact: true** for broad search) |
|
|
1049
|
+
| **File Discovery** | \`shadow_search_path\` (query, **ranked: true**) \u2014 gravity-sorted with layers |
|
|
1050
|
+
| **Config Check** | \`shadow_search_config\` (key, **showUsage: true**) \u2014 with usage counts |
|
|
1051
|
+
| **External Docs**| context7 tools (user-context7) |
|
|
1052
|
+
| **Relational** | \`shadow_analyze_deps\` (filePath, direction) |
|
|
1053
|
+
|
|
1054
|
+
## \u{1F4A1} Intelligence Options
|
|
1055
|
+
|
|
1056
|
+
- **\`shadow_search_concept\` with \`compact: true\`**: Returns file paths + scores without snippets (~60% token savings). Use for broad exploration.
|
|
1057
|
+
- **\`shadow_search_path\` with \`ranked: true\`**: Results sorted by gravity (high-import files first) with layer classification. Reveals architecturally important files.
|
|
1058
|
+
- **\`shadow_search_config\` with \`showUsage: true\`**: Shows usage counts per config var and identifies orphaned vars (defined but never used in code).
|
|
1059
|
+
|
|
1060
|
+
*Note: Always check \`package.json\` for the exact version before querying Context7 to ensure documentation alignment.*`,shadow_sync:`---
|
|
1061
|
+
name: sync
|
|
1062
|
+
description: Sync index and mission state after external changes. Day-to-day: index + NanoRepair run automatically when MCP tools (search, inspect, etc.) trigger reindex. Use trace after git pull/checkout/merge (or rely on hooks); use index deep:true for full rebuild.
|
|
1063
|
+
---
|
|
1064
|
+
|
|
1065
|
+
# Repository Synchronization
|
|
1066
|
+
|
|
1067
|
+
**Day-to-day:** Index and NanoRepair run automatically when you use MCP tools (search, inspect, analyze, etc.) and a reindex occurs. No manual sync needed for edits or renames.
|
|
1068
|
+
|
|
1069
|
+
## When to run sync manually
|
|
1070
|
+
|
|
1071
|
+
| Situation | Action |
|
|
1072
|
+
| :--- | :--- |
|
|
1073
|
+
| **After git pull/checkout/merge** | \`shadow_sync_trace\` (repoPath) \u2014 or rely on Git hooks if installed |
|
|
1074
|
+
| **Full rebuild (corruption)** | \`shadow_sync_index\` (repoPath; use deep: true if supported) |
|
|
1075
|
+
| **Repair only (rare)** | \`shadow_sync_repair\` (repoPath) |
|
|
1076
|
+
|
|
1077
|
+
**Note:** \`trace\` does index + ghost analysis + NanoRepair + lifecycle + mission re-hydration. Hooks run it on commit/checkout/merge.
|
|
1078
|
+
`,shadow_synthesize:`---
|
|
1079
|
+
name: synthesize
|
|
1080
|
+
description: Distill mission logs into Architectural Decision Records (ADRs) and persist them to the Shadow Engine and Git Notes. Use when completing missions, creating ADRs, synthesizing architectural decisions, or when the user asks about decision records, mission completion, or architectural documentation.
|
|
1081
|
+
---
|
|
1082
|
+
|
|
1083
|
+
# Architectural Synthesis
|
|
1084
|
+
|
|
1085
|
+
Distill mission logs into an Architectural Decision Record (ADR) and persist it to the Shadow Engine.
|
|
1086
|
+
|
|
1087
|
+
> **AUTO-PILOT ACTIVE**: Synthesis is **automatically triggered** when a mission status is set to \`completed\` via \`shadow_ops_track\`. The system handles: ADR distillation (recursive for child missions), Git Notes persistence, and **cascade parent completion** (if all siblings are done, the parent auto-completes and synthesizes too).
|
|
1088
|
+
|
|
1089
|
+
## Workflow
|
|
1090
|
+
|
|
1091
|
+
1. **Complete Mission**: \`shadow_ops_track\` (missionId, status: "completed", repoPath).
|
|
1092
|
+
* The Shadow Engine will automatically:
|
|
1093
|
+
* Distill all intent logs (recursive for child missions).
|
|
1094
|
+
* Format the ADR using markdown and **Liquid Anchors**.
|
|
1095
|
+
* Persist the record to SQLite and **Git Notes**.
|
|
1096
|
+
* **Cascade**: If all sibling missions under the same parent are completed, the parent mission auto-completes with its own ADR synthesis.
|
|
1097
|
+
2. **Verify**: Check the synthesized record via \`shadow_ops_chronicle\` (limit: 5, repoPath).
|
|
1098
|
+
3. **Manual Synthesis**: Use \`shadow_ops_synthesize\` only to **re-generate** an existing record or for specific partial distillations.
|
|
1099
|
+
4. **Pre-synthesis Compression** (optional): For missions with many raw logs, \`shadow_ops_crystallize\` (missionId, repoPath) compresses logs into a crystal summary before synthesis for cleaner ADRs.
|
|
1100
|
+
|
|
1101
|
+
## Precise Tooling
|
|
1102
|
+
|
|
1103
|
+
| Action | Atomic Tool | Usage |
|
|
1104
|
+
| :--- | :--- | :--- |
|
|
1105
|
+
| **Complete & Seal** | \`shadow_ops_track\` (status: "completed") | **Primary**. Triggers auto-synthesis + cascade. |
|
|
1106
|
+
| **Manual Distill** | \`shadow_ops_synthesize\` | Re-run synthesis manually (re-gen only). |
|
|
1107
|
+
| **Crystallize First** | \`shadow_ops_crystallize\` | Compress raw logs before synthesis. |
|
|
1108
|
+
| **View Chronicle** | \`shadow_ops_chronicle\` | View the combined narrative feed. |
|
|
1109
|
+
|
|
1110
|
+
*Note: Synthesis consolidation includes all child missions recursively. Cascade parent completion propagates upward through the entire hierarchy.*
|
|
1111
|
+
|
|
1112
|
+
## Cascade Parent Completion
|
|
1113
|
+
|
|
1114
|
+
When the last child mission under a parent is completed:
|
|
1115
|
+
1. Parent status is set to \`completed\`
|
|
1116
|
+
2. A system intent log records the cascade event
|
|
1117
|
+
3. Parent ADR is synthesized (recursive child distillation)
|
|
1118
|
+
4. Parent is synced to Git Notes
|
|
1119
|
+
5. If the parent itself has a parent, the cascade continues upward
|
|
1120
|
+
|
|
1121
|
+
## Tooling Strategy
|
|
1122
|
+
|
|
1123
|
+
Synthesis is the final commit of the mission's logic into the repository's permanent history. Avoid manual markdown files for ADRs; trust the **Git Notes** architecture to preserve the "Story of the Code."
|
|
1124
|
+
`,"shadow_trace-impact":'---\nname: trace-impact\ndescription: Map the blast radius of a change by analyzing impact, flow traces, cross-repo dependencies, and boundary maps. Use when analyzing change impact, assessing risk, tracing dependencies, or when the user asks about change impact, blast radius, or dependency analysis.\n---\n\n# Impact Analysis\n\nMap the blast radius of a change using the full Shadow analyze toolkit.\n\n## \u{1F680} Workflow\n\n1. **Session Context**: `shadow_ops_context` (repoPath) \u2014 **ONE CALL** for hologram + chronicle + briefing. Check if symbol is in gravity zones.\n2. **Impact (Blast Radius)**: `shadow_analyze_impact` (symbolName, filePath, depth: 3, repoPath) \u2014 ALL affected files.\n3. **Dependencies**:\n - `shadow_analyze_deps` (filePath, direction: "imported_by", repoPath) \u2014 Who imports this?\n - `shadow_analyze_deps` (filePath, direction: "imports", repoPath) \u2014 What does it import?\n4. **Flow Trace**: `shadow_analyze_flow` (symbolName, filePath, repoPath) \u2014 Execution path.\n5. **Health Check**:\n - `shadow_analyze_debt` (mode: "circular-deps", repoPath) \u2014 Any import cycles?\n - `shadow_analyze_debt` (mode: "dead-code", limit: 50, repoPath) \u2014 Unused exports?\n6. **Cross-Repo Check** (if multi-repo):\n - `shadow_workspace_fuse` (repoPaths, repoPath).\n - `shadow_search_symbol` (query, limit: 50, repoPath).\n7. **Boundary Map**: `shadow_recon_topography` (repoPath) \u2014 Layer crossing check.\n8. **Log Risk**: `shadow_ops_log` (missionId, type: "discovery", content, symbolName, repoPath).\n\n## \u{1F6E0} Precise Tooling\n\n| Impact Layer | Atomic Tool |\n| :--- | :--- |\n| **Session Start** \u{1F680} | `shadow_ops_context` (repoPath) \u2014 **START HERE** for context |\n| **Hologram** | `shadow_recon_hologram` (repoPath) \u2014 if you need standalone |\n| **Blast Radius** | `shadow_analyze_impact` (symbolName, depth: 3) |\n| **Dependents** | `shadow_analyze_deps` (filePath, direction: "imported_by") |\n| **Dependencies** | `shadow_analyze_deps` (filePath, direction: "imports") |\n| **Flow Path** | `shadow_analyze_flow` (symbolName, filePath) |\n| **Circular Deps** | `shadow_analyze_debt` (mode: "circular-deps") |\n| **Dead Code** | `shadow_analyze_debt` (mode: "dead-code", **confidenceThreshold: "high"**) |\n| **File Discovery** | `shadow_search_path` (query, **ranked: true**) \u2014 gravity-sorted |\n| **Workspace Fuse**| `shadow_workspace_fuse` (repoPaths, repoPath) |\n| **Topography** | `shadow_recon_topography` |\n\n## \u{1F4A1} Intelligence Options\n\n- **`shadow_search_path` with `ranked: true`**: Find related files sorted by gravity (high-import files first) with layer classification. Helps identify which affected files are architecturally critical.\n- **`shadow_analyze_debt` confidence levels**: Use `confidenceThreshold: "high"` to focus on likely dead code, avoiding noise from test fixtures and migrations.\n\n*Note: **Start with `shadow_ops_context`** for instant gravity zones + architectural context. Use depth higher than 3 for impact analysis only if the symbol is a fundamental primitive (e.g., RepositoryFactory).*\n\n## \u{1F6E0} Risk Classification\n\n- **Critical Risk**: Symbol in gravity zones (top 10) + >20 dependents + crosses layers\n- **High Risk**: >10 dependents OR crosses layers (e.g., Test -> Logic)\n- **Medium Risk**: 5-10 dependents within same layer\n- **Low Risk**: <5 dependents, same layer, no circular deps',shadow_understand:'---\nname: understand\ndescription: Find the high-signal path to understanding complex logic through intent retrieval, topological placement, relational analysis, and mechanics inspection. Use when understanding architecture, analyzing complex code, tracing logic flow, or when the user asks about how something works, architectural patterns, or code comprehension.\n---\n\n# Architectural Understanding\n\nFind the high-signal path to understanding complex logic.\n\n## Workflow\n\n1. **Session Context (The Fast Lane)**: `shadow_ops_context` (repoPath) \u2014 **ONE CALL** returns hologram + chronicle(5) + briefing (relevance-ranked candidates).\n - Skip to step 3 if you have what you need from context alone.\n2. **Optional Expanded Context** (only if shadow_ops_context wasn\'t enough):\n - `shadow_recon_topography` (repoPath) \u2014 Detailed layer breakdown beyond hologram summary.\n - `shadow_recon_tree` (subPath: "src/services", maxDepth: 2, repoPath) \u2014 Visual file hierarchy.\n - `shadow_ops_briefing` (scope: "mission", missionId, altitude: "ground") \u2014 Full mission detail with raw logs, working set, collisions.\n3. **Relational Analysis (The Who)**:\n - `shadow_analyze_impact` (symbolName, filePath, depth: 3, repoPath) \u2014 Blast radius.\n - `shadow_analyze_deps` (filePath, direction: "imported_by", repoPath) \u2014 Who depends on this?\n - `shadow_search_concept` (query, repoPath) \u2014 Semantic search.\n4. **Mechanics (The How)**:\n - **For Logic**: `shadow_analyze_flow` (symbolName, filePath, repoPath) \u2014 Trace execution.\n - **For Objects**: `shadow_inspect_file` (filePath, detailLevel: "signatures", repoPath) \u2014 All exports.\n - **For Symbol Deep Dive**: `shadow_inspect_symbol` (symbolName, filePath, context: "full", repoPath) \u2014 With deps.\n5. **Synthesis**: `shadow_ops_log` (missionId, type: "discovery", content, symbolName, repoPath).\n\n## Precise Tooling\n\n| Discovery Layer | Atomic Tool |\n| :--------------------- | :---------------------------------------------------- |\n| **Session Start** | `shadow_ops_context` (repoPath) \u2014 **START HERE** |\n| **Hologram** | `shadow_recon_hologram` (repoPath) \u2014 if you need standalone hologram |\n| **History** | `shadow_ops_chronicle` (limit: 5) \u2014 if you need more than 5 from context |\n| **Layers** | `shadow_recon_topography` \u2014 detailed breakdown |\n| **Mission Detail** | `shadow_ops_briefing` (altitude: "ground") \u2014 full logs + working set |\n| **Blast Radius** | `shadow_analyze_impact` (symbolName, depth: 3) |\n| **Dependents** | `shadow_analyze_deps` (filePath, direction: "imported_by") |\n| **Flow Trace** | `shadow_analyze_flow` (symbolName, filePath) |\n| **Structure** | `shadow_inspect_file` (detailLevel: "signatures") |\n| **Deep Dive** | `shadow_inspect_symbol` (context: "full") |\n| **File Discovery** | `shadow_search_path` (query, **ranked: true**) \u2014 gravity-sorted results with layer classification |\n\n*Note: **ALWAYS start with `shadow_ops_context`** for instant architectural context + history + mission state in ONE call. Use `context: "definition"` for token-efficient single symbol inspection.*\n\n## Intelligence Options\n\n- **`shadow_search_path` with `ranked: true`**: Results sorted by gravity (high-import files first) with layer classification (Entry/Logic/Data). Use when you need to find the most architecturally important files matching a pattern.\n- **`shadow_search_concept` with `compact: true`**: Omits code snippets for ~60% token savings. Use for broad exploration before deep dives.\n- **Briefing altitude levels**: Use `orbit` for quick status, `atmosphere` for strategy + crystals, `ground` for raw logs + collisions.\n- **`shadow_ops_crystallize`**: If a mission has excessive raw logs, crystallize them first for leaner briefings.\n',shadow_workspace:`---
|
|
1125
|
+
name: workspace
|
|
1126
|
+
description: Manage multi-repository workspaces and cross-repo mission links using the Shadow Engine. Use when working with multiple repositories, federated search across repos, linking missions across repos, or when the user asks about workspace management, multi-repo workflows, or cross-repository dependencies.
|
|
1127
|
+
---
|
|
1128
|
+
|
|
1129
|
+
# Workspace Orchestration
|
|
1130
|
+
|
|
1131
|
+
Manage multi-repository workspaces and cross-repo mission links using the Shadow Engine.
|
|
1132
|
+
|
|
1133
|
+
## \u{1F680} Workflow
|
|
1134
|
+
|
|
1135
|
+
1. **List Workspaces**: \`shadow_workspace_list\` (repoPath, repoPaths).
|
|
1136
|
+
2. **Federated Search**: \`shadow_workspace_fuse\` (repoPath, repoPaths).
|
|
1137
|
+
3. **Link Missions**: \`shadow_workspace_link\` (parentRepoPath, parentMissionId, childRepoPath, childMissionId, relationship, repoPath).
|
|
1138
|
+
4. **Verify Graph**: \`shadow_ops_graph\` (missionId, depth, repoPath).
|
|
1139
|
+
|
|
1140
|
+
## \u{1F6E0} Precise Tooling
|
|
1141
|
+
|
|
1142
|
+
| Action | Atomic Tool | Example |
|
|
1143
|
+
| :--- | :--- | :--- |
|
|
1144
|
+
| **List** | \`shadow_workspace_list\` | \`{ repoPath, repoPaths: [...] }\` |
|
|
1145
|
+
| **Fuse** | \`shadow_workspace_fuse\` | \`{ repoPath, repoPaths: [...] }\` |
|
|
1146
|
+
| **Link** | \`shadow_workspace_link\` | \`{ parentMissionId: 1, childMissionId: 2, ... }\` |
|
|
1147
|
+
| **Visualize** | \`shadow_ops_graph\` | \`{ missionId: 1, depth: 3, repoPath }\` |
|
|
1148
|
+
|
|
1149
|
+
*Note: Use fused search after \`shadow_workspace_fuse\` to look up concepts across all repositories simultaneously.*
|
|
1150
|
+
|
|
1151
|
+
## \u{1F6E0} Tooling Strategy
|
|
1152
|
+
|
|
1153
|
+
Use **\`shadow_workspace_fuse\`** early in multi-repo sessions to unlock "X-Ray" vision across boundaries.`};import{pino as Xl}from"pino";import*as oe from"@clack/prompts";var ps=Xl({transport:{target:"pino-pretty",options:{colorize:!0}}});async function la(i=!1,e=!1){oe.intro("\u{1F311} Liquid Shadow: Tactical Onboarding");let t=Kl.homedir(),n=st.join(t,".claude","skills"),s=st.join(t,".gemini","antigravity","global_workflows"),r=0,o=e||await oe.confirm({message:"Deploy Autonomous Reasoning Skills? (Injects /onboard, /understand, etc.)",initialValue:!0});if(oe.isCancel(o)){oe.outro("Onboarding aborted.");return}let c=e||await oe.confirm({message:"Connect to MCP Reasoning Engines? (Claude Code, Desktop, Antigravity)",initialValue:!0});if(oe.isCancel(c)){oe.outro("Onboarding aborted.");return}if(!o&&!c){oe.outro("No actions selected. Operational state unchanged.");return}let a=oe.spinner();if(a.start("Establishing intelligence assets..."),o){if(Ie.existsSync(n))for(let[l,p]of Object.entries(ei)){let u=st.join(n,l);Ie.existsSync(u)||Ie.mkdirSync(u,{recursive:!0});let d=st.join(u,"SKILL.md");(i||!Ie.existsSync(d))&&(Ie.writeFileSync(d,p),r++)}if(Ie.existsSync(s))for(let[l,p]of Object.entries(ei)){let u=st.join(s,`${l}.md`);(i||!Ie.existsSync(u))&&(Ie.writeFileSync(u,p),r++)}}c&&await Zl(t),a.stop("Intelligence layer established."),r>0?oe.note(`Successfully deployed ${r} tactical skills.`,"Manifest"):oe.note("No new skills deployed (up to date or scope skipped).","Manifest"),oe.outro("\u{1F311} Liquid Shadow is operational.")}async function Zl(i){let e=[{name:"Claude Code",path:st.join(i,".claude.json"),type:"stdio"},{name:"Antigravity IDE",path:st.join(i,".gemini","antigravity","mcp_config.json")},{name:"Claude Desktop",path:st.join(i,"Library","Application Support","Claude","claude_desktop_config.json")}];for(let t of e){if(!Ie.existsSync(t.path)){ps.debug(`${t.name} config not found at ${t.path}, skipping.`);continue}try{let n=Ie.readFileSync(t.path,"utf8"),s=JSON.parse(n);s.mcpServers||(s.mcpServers={});let r="liquid-shadow",o=s.mcpServers[r],c={command:"liquid-shadow-mcp",args:[],env:{}};if(t.type==="stdio"&&(c.type="stdio"),o){ps.info(`${t.name}: ${r} MCP server already configured.`);continue}s.mcpServers[r]=c,Ie.writeFileSync(t.path,JSON.stringify(s,null,2)),ps.info(`Updated ${t.name} config at ${t.path}`)}catch(n){ps.error(`Failed to update ${t.name} config at ${t.path}: ${n}`)}}}function le(i){let e=process.cwd();return hs(e,i.flags)}process.on("unhandledRejection",i=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",i),J().then(()=>process.exit(1))});process.on("uncaughtException",i=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",i),J().then(()=>process.exit(1))});var Z=ep().name("liquid-shadow").version("1.0.2").description("Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem").scriptName("liquid-shadow");Z.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 i=>{let e=le(i),t={...i.flags,dir:i.flags.dir??e.dir,level:i.flags.level??e.level,deep:i.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await Ir(i.parameters.dir||e.dir,t)});Z.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async i=>{let e=le(i);await Di(i.parameters.dir||e.dir)});Z.command("dashboard","Operational intelligence dashboard (TUI)",{parameters:["[dir]"]}).on("dashboard",async i=>{let e=le(i);await Rs(i.parameters.dir||e.dir)});Z.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async i=>{let e=le(i);await zi(i.parameters.dir||e.dir)});Z.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async i=>{let e=le(i);await Lr(i.parameters.dir||e.dir)});Z.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 i=>{let e=le(i);await Tr(i.parameters.dir||e.dir,{...i.flags,dir:i.flags.dir??e.dir})});Z.command("recon","Repository reconnaissance and architecture analysis",{parameters:["<mode>","[dir]"],flags:{subPath:{type:String,description:"Subpath to focus on"}}}).on("recon",async i=>{let e=le(i);await yo(i.parameters.mode,i.parameters.dir||e.dir,{...i.flags})});Z.command("trace","Trace execution flow for a given file/symbol",{parameters:["<file>","[symbolName]"],flags:{dir:{type:String,alias:"d",default:"."}}}).on("trace",async i=>{let e=le(i);await Pr(i.parameters.file,{...i.flags,dir:i.flags.dir??e.dir,symbolName:i.parameters.symbolName})});Z.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"]}).on("sync",async i=>{let e=le(i);await ho(i.parameters.dir||e.dir,{})});Z.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 i=>{let e=le(i);await Io(i.parameters.key,{...i.flags,dir:i.flags.dir??e.dir})});Z.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 i=>{let e=le(i);await To(i.parameters.query,{...i.flags,dir:i.flags.dir??e.dir})});Z.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 i=>{let e=le(i);await Ro(i.parameters.query,{...i.flags,dir:i.flags.dir??e.dir})});Z.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 i=>{let e=le(i);await ko(i.parameters.query,{...i.flags,dir:i.flags.dir??e.dir})});Z.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async i=>{await Co([i.parameters.action,i.parameters.path])});Z.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async i=>{await Wo([i.parameters.action,...i.parameters.args])});Z.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async i=>{await sa([i.parameters.action,...i.parameters.args])});Z.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async i=>{await ia([i.parameters.mode,...i.parameters.args])});Z.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async i=>{let e=le(i);await aa(i.parameters.dir||e.dir)});Z.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 i=>{let e=le(i);await ca(i.parameters.dir||e.dir,{...i.flags,format:i.flags.format,limit:i.flags.limit?parseInt(String(i.flags.limit),10):void 0,offset:i.flags.offset?parseInt(String(i.flags.offset),10):void 0,since:i.flags.since?Math.floor(new Date(String(i.flags.since)).getTime()/1e3):void 0,until:i.flags.until?Math.floor(new Date(String(i.flags.until)).getTime()/1e3):void 0})});Z.command("init","Initialize Liquid Shadow skills and configuration",{flags:{force:{type:Boolean,alias:"f",description:"Force overwrite existing skills",default:!1},yes:{type:Boolean,alias:"y",description:"Skip interactive confirmation (unsafe)",default:!1}}}).on("init",async i=>{await la(i.flags.force,i.flags.yes)});Z.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async i=>{await oa(i.parameters.shell||"")});if(process.argv.length<=2){let i=hs(process.cwd(),{});Rs(i.dir)}else Z.parse();
|