@precisionutilityguild/liquid-shadow 1.0.1 → 1.0.2

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.
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDescriptor;var Oo=Object.getOwnPropertyNames;var Fo=Object.getPrototypeOf,Ho=Object.prototype.hasOwnProperty;var Wo=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var V=(s,e)=>()=>(s&&(e=s(s=0)),e);var Uo=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ai=(s,e)=>{for(var t in e)Jn(s,t,{get:e[t],enumerable:!0})},jo=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oo(e))!Ho.call(s,i)&&i!==t&&Jn(s,i,{get:()=>e[i],enumerable:!(n=Do(e,i))||n.enumerable});return s};var Bo=(s,e,t)=>(t=s!=null?Po(Fo(s)):{},jo(e||!s||!s.__esModule?Jn(t,"default",{value:s,enumerable:!0}):t,s));import zo from"pino";var Go,qo,_,N=V(()=>{"use strict";Go={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},qo=zo({level:process.env.LOG_LEVEL||"info",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:Go[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),_=qo});import St from"fs";import Yn from"path";import{fileURLToPath as Vo}from"url";function Xo(s){s.exec(`
2
+ var Wo=Object.create;var Vn=Object.defineProperty;var jo=Object.getOwnPropertyDescriptor;var Uo=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,zo=Object.prototype.hasOwnProperty;var Go=(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 Q=(i,e)=>()=>(i&&(e=i(i=0)),e);var qo=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Os=(i,e)=>{for(var t in e)Vn(i,t,{get:e[t],enumerable:!0})},Jo=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Uo(e))!zo.call(i,s)&&s!==t&&Vn(i,s,{get:()=>e[s],enumerable:!(n=jo(e,s))||n.enumerable});return i};var Yo=(i,e,t)=>(t=i!=null?Wo(Bo(i)):{},Jo(e||!i||!i.__esModule?Vn(t,"default",{value:i,enumerable:!0}):t,i));import Vo from"pino";var Qo,Ko,_,P=Q(()=>{"use strict";Qo={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},Ko=Vo({level:process.env.LOG_LEVEL||"info",base:{service:"liquid-shadow"},formatters:{level(i,e){return{level:i,severity:Qo[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),_=Ko});import St from"fs";import Qn from"path";import{fileURLToPath as ea}from"url";function sa(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 Zo(s){Xo(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function ea(){let s=Ko;if(!St.readdirSync(s).some(r=>r.match(/^\d{3}_.*\.sql$/))){let r=Yn.resolve(s,"../../data/migrations");St.existsSync(r)&&St.readdirSync(r).some(l=>l.match(/^\d{3}_.*\.sql$/))&&(s=r)}let n=St.readdirSync(s).filter(r=>r.match(/^\d{3}_.*\.sql$/)).sort(),i=[];for(let r of n){let o=r.match(/^(\d{3})_(.+)\.sql$/);if(!o)continue;let l=parseInt(o[1],10),c=o[2],p=St.readFileSync(Yn.join(s,r),"utf-8").split(/^-- DOWN$/m),d=p[0].trim(),u=p[1]?.trim();i.push({version:l,name:c,up:d,down:u})}return i}function ta(s,e){_t.info({version:e.version,name:e.name},"Applying migration"),s.transaction(()=>{s.exec(e.up),s.prepare("INSERT INTO schema_migrations (version, name) VALUES (?, ?)").run(e.version,e.name)})(),_t.info({version:e.version},"Migration applied successfully")}function Fi(s){let e=Zo(s),n=ea().filter(i=>!e.has(i.version));if(n.length===0){_t.debug("No pending migrations");return}_t.info({count:n.length},"Running pending migrations");for(let i of n)ta(s,i);_t.info("All migrations complete")}var _t,Qo,Ko,Hi=V(()=>{"use strict";N();_t=_.child({module:"migrations"}),Qo=Vo(import.meta.url),Ko=Yn.dirname(Qo)});import na from"better-sqlite3";import Bt from"path";import Vn from"fs";import Wi from"crypto";import ia from"os";function Gt(s){let e=ia.homedir(),t=Bt.join(e,".mcp-liquid-shadow"),n=Bt.join(t,"dbs");Vn.existsSync(n)||Vn.mkdirSync(n,{recursive:!0});let i=Wi.createHash("sha256").update(s).digest("hex").substring(0,12),o=`${Bt.basename(s).replace(/[^a-zA-Z0-9-_]/g,"_")}_${i}.db`;return Bt.join(n,o)}function sa(s,e){let t=e||Gt(s);Ie.info({repoPath:s,dbPath:t},"Initializing database");let n=new na(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),Fi(n),zt.set(s,t),Me.set(t,n),Ie.info({repoPath:s,dbPath:t},"Database initialized successfully"),n}function Qn(s){return Wi.createHash("sha256").update(s,"utf8").digest("hex")}function Ui(s,e){return e?Qn(s)!==e:!0}function ke(s){let e=zt.get(s)||Gt(s),t=Me.get(e);if(t){if(t.open)return t;Me.delete(e)}let n=sa(s);return Me.set(e,n),n}function Ye(s){let e=Gt(s);if(!Vn.existsSync(e))return!1;try{let t=ke(s);return t.prepare(`
8
+ `)}function ia(i){sa(i);let e=i.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function ra(){let i=na;if(!St.readdirSync(i).some(r=>r.match(/^\d{3}_.*\.sql$/))){let r=Qn.resolve(i,"../../data/migrations");St.existsSync(r)&&St.readdirSync(r).some(c=>c.match(/^\d{3}_.*\.sql$/))&&(i=r)}let n=St.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=St.readFileSync(Qn.join(i,r),"utf-8").split(/^-- DOWN$/m),d=p[0].trim(),u=p[1]?.trim();s.push({version:c,name:a,up:d,down:u})}return s}function oa(i,e){_t.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)})(),_t.info({version:e.version},"Migration applied successfully")}function Us(i){let e=ia(i),n=ra().filter(s=>!e.has(s.version));if(n.length===0){_t.debug("No pending migrations");return}_t.info({count:n.length},"Running pending migrations");for(let s of n)oa(i,s);_t.info("All migrations complete")}var _t,ta,na,Bs=Q(()=>{"use strict";P();_t=_.child({module:"migrations"}),ta=ea(import.meta.url),na=Qn.dirname(ta)});import aa from"better-sqlite3";import Gt from"path";import Kn from"fs";import zs from"crypto";import ca from"os";function Jt(i){let e=ca.homedir(),t=Gt.join(e,".mcp-liquid-shadow"),n=Gt.join(t,"dbs");Kn.existsSync(n)||Kn.mkdirSync(n,{recursive:!0});let s=zs.createHash("sha256").update(i).digest("hex").substring(0,12),o=`${Gt.basename(i).replace(/[^a-zA-Z0-9-_]/g,"_")}_${s}.db`;return Gt.join(n,o)}function la(i,e){let t=e||Jt(i);$e.info({repoPath:i,dbPath:t},"Initializing database");let n=new aa(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),Us(n),qt.set(i,t),Me.set(t,n),$e.info({repoPath:i,dbPath:t},"Database initialized successfully"),n}function Xn(i){return zs.createHash("sha256").update(i,"utf8").digest("hex")}function Gs(i,e){return e?Xn(i)!==e:!0}function ke(i){let e=qt.get(i)||Jt(i),t=Me.get(e);if(t){if(t.open)return t;Me.delete(e)}let n=la(i);return Me.set(e,n),n}function Ve(i){let e=Jt(i);if(!Kn.existsSync(e))return!1;try{let t=ke(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 Ie.debug({repoPath:s,error:t},"Error checking index status"),!1}}function Kn(s,e){let t=ke(s);t.prepare(`
11
+ `).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return $e.debug({repoPath:i,error:t},"Error checking index status"),!1}}function Zn(i,e){let t=ke(i);t.prepare(`
12
12
  INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
13
13
  VALUES ('index_completed', 'true', unixepoch())
14
14
  `).run(),t.prepare(`
@@ -17,14 +17,14 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
17
17
  `).run(Date.now().toString()),e&&t.prepare(`
18
18
  INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
19
19
  VALUES ('last_indexed_commit', ?, unixepoch())
20
- `).run(e),Ie.info({repoPath:s,commitSha:e},"Repository marked as indexed")}function xt(s){try{return ke(s).prepare(`
20
+ `).run(e),$e.info({repoPath:i,commitSha:e},"Repository marked as indexed")}function xt(i){try{return ke(i).prepare(`
21
21
  SELECT value FROM index_metadata
22
22
  WHERE key = 'last_indexed_commit'
23
- `).get()?.value||null}catch(e){return Ie.debug({repoPath:s,error:e},"Error getting last indexed commit"),null}}function qt(s){let e=zt.get(s)||Gt(s),t=Me.get(e);t&&(t.open&&(Ie.info({repoPath:s,dbPath:e},"Closing database connection"),t.close()),Me.delete(e)),zt.delete(s)}function ji(){for(let[s,e]of Me.entries())try{e.open&&(Ie.info({dbPath:s},"Closing database connection"),e.close())}catch(t){Ie.error({dbPath:s,err:t},"Error closing database execution")}Me.clear()}var Ie,Me,zt,Bi,Ve=V(()=>{"use strict";N();Hi();Ie=_.child({module:"db"});Me=new Map,zt=new Map;process.on("exit",()=>ji());Bi=s=>{Ie.info({signal:s},"Received termination signal, closing databases"),ji(),process.exit(0)};process.on("SIGINT",()=>Bi("SIGINT"));process.on("SIGTERM",()=>Bi("SIGTERM"))});var K,be=V(()=>{"use strict";K=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 ra from"path";var Jt,zi=V(()=>{"use strict";be();Jt=class extends K{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=ra.resolve(e,t),i=n.endsWith("/")?n:n+"/";return this.all(`
23
+ `).get()?.value||null}catch(e){return $e.debug({repoPath:i,error:e},"Error getting last indexed commit"),null}}function Yt(i){let e=qt.get(i)||Jt(i),t=Me.get(e);t&&(t.open&&($e.info({repoPath:i,dbPath:e},"Closing database connection"),t.close()),Me.delete(e)),qt.delete(i)}function qs(){for(let[i,e]of Me.entries())try{e.open&&($e.info({dbPath:i},"Closing database connection"),e.close())}catch(t){$e.error({dbPath:i,err:t},"Error closing database execution")}Me.clear()}var $e,Me,qt,Js,Qe=Q(()=>{"use strict";P();Bs();$e=_.child({module:"db"});Me=new Map,qt=new Map;process.on("exit",()=>qs());Js=i=>{$e.info({signal:i},"Received termination signal, closing databases"),qs(),process.exit(0)};process.on("SIGINT",()=>Js("SIGINT"));process.on("SIGTERM",()=>Js("SIGTERM"))});var X,Ee=Q(()=>{"use strict";X=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 Vt,Ys=Q(()=>{"use strict";Ee();Vt=class extends X{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
24
  SELECT * FROM files
25
25
  WHERE (path LIKE ? OR path = ?)
26
26
  ORDER BY path ASC
27
- `,`${i}%`,n)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
27
+ `,`${s}%`,n)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
28
28
  SELECT files.*, files_fts.rank
29
29
  FROM files_fts
30
30
  JOIN files ON files.rowid = files_fts.rowid
@@ -35,7 +35,7 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
35
35
  SELECT * FROM files
36
36
  WHERE ${n}
37
37
  LIMIT ?
38
- `,...e.map(i=>`%${i}%`),t)}getContent(e){return this.get("SELECT content FROM file_content WHERE file_path = ?",e)?.content}findContentByToken(e,t=10){return this.all(`
38
+ `,...e.map(s=>`%${s}%`),t)}getContent(e){return this.get("SELECT content FROM file_content WHERE file_path = ?",e)?.content}findContentByToken(e,t=10){return this.all(`
39
39
  SELECT file_path
40
40
  FROM content_fts
41
41
  WHERE content_fts MATCH ?
@@ -43,12 +43,12 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
43
43
  AND file_path NOT LIKE '%/test/%'
44
44
  AND file_path NOT LIKE '%.spec.%'
45
45
  LIMIT ?
46
- `,`"${e.replace(/[^a-zA-Z0-9_\/]/g," ")}"`,t).map(i=>i.file_path)}findSynapses(e){let t="SELECT * FROM event_synapses WHERE 1=1",n=[];if(e.type&&(t+=" AND type = ?",n.push(e.type)),e.name){let i=e.name;i.startsWith("/")&&(i=i.substring(1)),i.endsWith("/")&&(i=i.substring(0,i.length-1)),i.length>0&&(t+=" AND (name LIKE ? OR name LIKE ? OR name = ?)",n.push(`${i}%`),n.push(`%/${i}%`),n.push(e.name))}return e.direction&&(t+=" AND direction = ?",n.push(e.direction)),t+=` LIMIT ${e.limit||50}`,this.all(t,...n)}exists(e){return!!this.get("SELECT 1 FROM files WHERE path = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE files SET ${i} WHERE path = ?`,...r)}getStats(){let e=this.get(`
47
- SELECT
46
+ `,`"${e.replace(/[^a-zA-Z0-9_\/]/g," ")}"`,t).map(s=>s.file_path)}findSynapses(e){let t="SELECT * FROM event_synapses WHERE 1=1",n=[];if(e.type&&(t+=" AND type = ?",n.push(e.type)),e.name){let s=e.name;s.startsWith("/")&&(s=s.substring(1)),s.endsWith("/")&&(s=s.substring(0,s.length-1)),s.length>0&&(t+=" AND (name LIKE ? OR name LIKE ? OR name = ?)",n.push(`${s}%`),n.push(`%/${s}%`),n.push(e.name))}return e.direction&&(t+=" AND direction = ?",n.push(e.direction)),t+=` LIMIT ${e.limit||50}`,this.all(t,...n)}exists(e){return!!this.get("SELECT 1 FROM files WHERE path = ?",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 files SET ${s} WHERE path = ?`,...r)}getStats(){let e=this.get(`
47
+ SELECT
48
48
  COUNT(*) as total,
49
49
  SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
50
50
  FROM files
51
- `);return{total:e?.total||0,withSummary:e?.withSummary||0}}getGravityMap(e=[],t){let n={},i=`
51
+ `);return{total:e?.total||0,withSummary:e?.withSummary||0}}getGravityMap(e=[],t){let n={},s=`
52
52
  SELECT ws.file_path, m.name as mission_name, m.status
53
53
  FROM working_set ws
54
54
  JOIN missions m ON ws.mission_id = m.id
@@ -57,14 +57,14 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
57
57
  OR m.id IN (${e.length>0?e.join(","):"-1"})
58
58
  )
59
59
  AND ws.file_path IS NOT NULL
60
- `,r=[];t&&r.push(t);let o=this.all(i,...r);for(let a of o){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let p=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.file_path].score+=p;let d=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.file_path].reasons.push(`${d}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
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 d=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.file_path].reasons.push(`${d}: ${l.mission_name}`)}let c=Math.floor(Date.now()/1e3)-86400,a=this.all(`
61
61
  SELECT file_path, type, mission_id
62
62
  FROM intent_logs
63
63
  WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
64
64
  AND file_path IS NOT NULL
65
65
  ORDER BY created_at DESC
66
66
  LIMIT 100
67
- `,l);for(let a of c){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let p=a.mission_id?e.includes(a.mission_id):!1,d=p?.1:.2;n[a.file_path].score<5&&(n[a.file_path].score+=d);let u=p?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.file_path].reasons.includes(u)&&n[a.file_path].reasons.length<5&&n[a.file_path].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
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,d=p?.1:.2;n[l.file_path].score<5&&(n[l.file_path].score+=d);let u=p?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.file_path].reasons.includes(u)&&n[l.file_path].reasons.length<5&&n[l.file_path].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
68
68
  SELECT
69
69
  SUBSTR(path, LENGTH(?) + 2,
70
70
  INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
@@ -82,12 +82,12 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
82
82
  ORDER BY total_files DESC
83
83
  LIMIT ?
84
84
  `,e,e,e,t)}hasFilesPattern(e){return!!this.get("SELECT 1 FROM files WHERE path LIKE ? LIMIT 1",e)}findPackageJsonChildren(e){return this.all(`
85
- SELECT
85
+ SELECT
86
86
  path,
87
87
  SUBSTR(path, LENGTH(?) + 2) as relPath
88
- FROM files
88
+ FROM files
89
89
  WHERE path LIKE ? || '/%/package.json'
90
- `,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(i=>{for(let r of i)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,i){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),l=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),a=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),u=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 (?, ?, ?, ?, ?, ?)"),b=this.db.prepare(`
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),u=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),f=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),h=this.db.prepare(`
91
91
  INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
92
92
  VALUES (?, ?, ?, ?, ?, ?, ?)
93
93
  ON CONFLICT(path) DO UPDATE SET
@@ -97,7 +97,7 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
97
97
  summary=excluded.summary,
98
98
  embedding=excluded.embedding,
99
99
  content_hash=excluded.content_hash
100
- `);this.db.transaction(g=>{for(let y of g){let{meta:S,exports:w,imports:C,configs:T,events:I,content:x,classification:$,summary:R,embedding:v}=y;r.run(S.path),o.run(S.path),l.run(S.path),c.run(S.path),a.run(S.path);let P=x?n(x):null;if(b.run(S.path,S.mtime,Date.now(),$||"Unknown",R||"",v?JSON.stringify(v):null,P),w){let L=(H,B,ne)=>{for(let W of B){let D=W.embedding?JSON.stringify(W.embedding):null,M=p.run(H,W.name,W.kind,W.signature,W.doc||"",W.line,W.endLine||W.line,W.classification||"Other",W.capabilities||"[]",ne,D);W.members&&W.members.length>0&&L(H,W.members,M.lastInsertRowid)}};L(S.path,w,null)}if(C)for(let L of C){let H=i(L.module,S.path,t);d.run(S.path,L.module,L.name,H)}if(T)for(let L of T)u.run(S.path,L.key,L.value,L.kind);if(x!==void 0&&m.run(S.path,x),I)for(let L of I)h.run(S.path,L.type,L.name,L.direction,L.line,L.snippet)}})(e)}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}}});var Yt,Gi=V(()=>{"use strict";be();Yt=class extends K{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(`
100
+ `);this.db.transaction(y=>{for(let g of y){let{meta:S,exports:R,imports:w,configs:T,events:v,content:k,classification:F,summary:x,embedding:I}=g;r.run(S.path),o.run(S.path),c.run(S.path),a.run(S.path),l.run(S.path);let M=k?n(k):null;if(h.run(S.path,S.mtime,Date.now(),F||"Unknown",x||"",I?JSON.stringify(I):null,M),R){let $=(j,H,N)=>{for(let L of H){let A=L.embedding?JSON.stringify(L.embedding):null,D=p.run(j,L.name,L.kind,L.signature,L.doc||"",L.line,L.endLine||L.line,L.classification||"Other",L.capabilities||"[]",N,A);L.members&&L.members.length>0&&$(j,L.members,D.lastInsertRowid)}};$(S.path,R,null)}if(w)for(let $ of w){let j=s($.module,S.path,t);d.run(S.path,$.module,$.name,j)}if(T)for(let $ of T)u.run(S.path,$.key,$.value,$.kind);if(k!==void 0&&m.run(S.path,k),v)for(let $ of v)f.run(S.path,$.type,$.name,$.direction,$.line,$.snippet)}})(e)}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}}});var Qt,Vs=Q(()=>{"use strict";Ee();Qt=class extends X{findByNameAndFile(e,t){return this.all("SELECT * FROM exports WHERE file_path = ? AND name = ?",t,e)}findByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ?",e)}findAtLine(e,t){return this.get(`
101
101
  SELECT * FROM exports
102
102
  WHERE file_path = ? AND start_line <= ? AND end_line >= ?
103
103
  ORDER BY (end_line - start_line) ASC -- Get innermost symbol
@@ -134,7 +134,7 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
134
134
  WHERE file_path = ?
135
135
  AND parent_id IS NULL
136
136
  ORDER BY start_line ASC
137
- `,e)}findByName(e,t=20){return this.all("SELECT * FROM exports WHERE name = ? LIMIT ?",e,t)}findClassByName(e){return this.get("SELECT * FROM exports WHERE name = ? AND kind = 'ClassDeclaration' LIMIT 1",e)}findDefinitionCandidates(e,t){let n=[e],i=`
137
+ `,e)}findByName(e,t=20){return this.all("SELECT * FROM exports WHERE name = ? LIMIT ?",e,t)}findClassByName(e){return this.get("SELECT * FROM exports WHERE name = ? AND kind = 'ClassDeclaration' LIMIT 1",e)}findDefinitionCandidates(e,t){let n=[e],s=`
138
138
  SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
139
139
  f.path as file_path, e.classification, e.capabilities,
140
140
  p.name as parent_name, p.kind as parent_kind
@@ -142,12 +142,12 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
142
142
  JOIN files f ON e.file_path = f.path
143
143
  LEFT JOIN exports p ON e.parent_id = p.id
144
144
  WHERE e.name = ?
145
- `;return t&&(i+=" AND f.path = ?",n.push(t)),i+=`
145
+ `;return t&&(s+=" AND f.path = ?",n.push(t)),s+=`
146
146
  ORDER BY
147
147
  CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
148
148
  CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
149
149
  LIMIT 10
150
- `,this.all(i,...n)}findMemberCandidates(e,t,n){let i=[e,t],r=`
150
+ `,this.all(s,...n)}findMemberCandidates(e,t,n){let s=[e,t],r=`
151
151
  SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
152
152
  f.path as file_path, e.classification, e.capabilities,
153
153
  p.name as parent_name, p.kind as parent_kind
@@ -155,12 +155,12 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
155
155
  JOIN files f ON e.file_path = f.path
156
156
  LEFT JOIN exports p ON e.parent_id = p.id
157
157
  WHERE p.name = ? AND e.name = ?
158
- `;return n&&(r+=" AND f.path = ?",i.push(n)),r+=`
158
+ `;return n&&(r+=" AND f.path = ?",s.push(n)),r+=`
159
159
  ORDER BY
160
160
  CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
161
161
  CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
162
162
  LIMIT 10
163
- `,this.all(r,...i)}findPotentialParents(e){return this.all(`
163
+ `,this.all(r,...s)}findPotentialParents(e){return this.all(`
164
164
  SELECT name, kind, file_path
165
165
  FROM exports
166
166
  WHERE kind IN ('ClassDeclaration', 'ClassExpression', 'TsInterfaceDeclaration')
@@ -179,16 +179,16 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
179
179
  WHERE file_path = ? AND parent_id IS NULL
180
180
  ORDER BY start_line ASC
181
181
  `,e)}findFts(e,t=20){return this.all(`
182
- SELECT e.*
182
+ SELECT e.*
183
183
  FROM exports e
184
- JOIN exports_fts ef ON e.id = ef.rowid
185
- WHERE ef MATCH ?
184
+ JOIN exports_fts ON e.id = exports_fts.rowid
185
+ WHERE exports_fts MATCH ?
186
186
  LIMIT ?
187
187
  `,e,t)}findByPartialName(e,t=20){return this.all(`
188
188
  SELECT * FROM exports
189
189
  WHERE lower(name) LIKE ?
190
190
  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=50,t=!1){let n=t?"":"AND e.file_path NOT LIKE '%/test/%' AND e.file_path NOT LIKE '%/__tests__/%' AND e.file_path NOT LIKE '%.spec.%' AND e.file_path NOT LIKE '%.test.%'";return this.all(`
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 f=m.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");a.push(`e.file_path NOT LIKE '${f}'`)}let l=a.length>0?`AND ${a.join(" AND ")}`:"",d=this.all(`
192
192
  SELECT e.name, e.kind, e.file_path, e.start_line
193
193
  FROM exports e
194
194
  WHERE e.kind IN (
@@ -197,12 +197,12 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
197
197
  'ArrowFunctionExpression', 'FunctionExpression'
198
198
  )
199
199
  AND e.parent_id IS NULL
200
- ${n}
200
+ ${l}
201
201
  AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.imported_symbols LIKE '%' || e.name || '%')
202
202
  AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
203
203
  ORDER BY e.file_path, e.start_line
204
204
  LIMIT ?
205
- `,e)}getGravityMap(e=[],t){let n={},i=`
205
+ `,t*2).map(m=>{let{confidence:f,reason:h}=this.scoreDeadExportConfidence(m);return{...m,confidence:f,reason:h}}),u=d;return c==="high"?u=d.filter(m=>m.confidence==="high"):c==="medium"&&(u=d.filter(m=>m.confidence==="high"||m.confidence==="medium")),u.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
206
  SELECT ws.symbol_id, m.name as mission_name, m.status
207
207
  FROM working_set ws
208
208
  JOIN missions m ON ws.mission_id = m.id
@@ -211,14 +211,14 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
211
211
  OR m.id IN (${e.length>0?e.join(","):"-1"})
212
212
  )
213
213
  AND ws.symbol_id IS NOT NULL
214
- `,r=[];t&&r.push(t);let o=this.all(i,...r);for(let a of o){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let p=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.symbol_id].score+=p;let d=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.symbol_id].reasons.push(`${d}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
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 d=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.symbol_id].reasons.push(`${d}: ${l.mission_name}`)}let c=Math.floor(Date.now()/1e3)-86400,a=this.all(`
215
215
  SELECT symbol_id, type, mission_id
216
216
  FROM intent_logs
217
217
  WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
218
218
  AND symbol_id IS NOT NULL
219
219
  ORDER BY created_at DESC
220
220
  LIMIT 200
221
- `,l);for(let a of c){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let p=a.mission_id?e.includes(a.mission_id):!1,d=p?.1:.2;n[a.symbol_id].score<5&&(n[a.symbol_id].score+=d);let u=p?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.symbol_id].reasons.includes(u)&&n[a.symbol_id].reasons.length<5&&n[a.symbol_id].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
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,d=p?.1:.2;n[l.symbol_id].score<5&&(n[l.symbol_id].score+=d);let u=p?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.symbol_id].reasons.includes(u)&&n[l.symbol_id].reasons.length<5&&n[l.symbol_id].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
222
222
  SELECT kind, COUNT(*) as c
223
223
  FROM exports
224
224
  WHERE kind IS NOT NULL AND kind != ''
@@ -231,7 +231,7 @@ var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDe
231
231
  OR name LIKE ?
232
232
  OR name LIKE ?
233
233
  LIMIT 10
234
- `,e,`%.${e}`,`%::${e}`)}}});var qi,Ji=V(()=>{"use strict";qi=`
234
+ `,e,`%.${e}`,`%::${e}`)}}});var Qs,Ks=Q(()=>{"use strict";Qs=`
235
235
  WITH RECURSIVE dependency_chain AS (
236
236
  -- Base case: Direct dependents of the target symbol
237
237
  -- Meaning: Files that import the file where the symbol is defined
@@ -266,7 +266,14 @@ WITH RECURSIVE dependency_chain AS (
266
266
  FROM imports i
267
267
  JOIN dependency_chain dc ON i.resolved_path = dc.consumer_path
268
268
  WHERE dc.depth < ? -- Max depth limit
269
- AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection: ensure we haven't visited this file in this chain
269
+ AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection
270
+ AND (
271
+ -- If the intermediate file is a re-exporter (barrel),
272
+ -- the next consumer must still be looking for the symbol
273
+ i.imported_symbols LIKE ?
274
+ OR i.imported_symbols = '*'
275
+ OR i.imported_symbols = ''
276
+ )
270
277
  )
271
278
  SELECT DISTINCT
272
279
  dc.consumer_path,
@@ -275,7 +282,7 @@ SELECT DISTINCT
275
282
  dc.imported_symbols
276
283
  FROM dependency_chain dc
277
284
  ORDER BY dc.depth, dc.consumer_path;
278
- `});var Vt,Yi=V(()=>{"use strict";be();Ji();Vt=class extends K{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(`
285
+ `});var Kt,Xs=Q(()=>{"use strict";Ee();Ks();Kt=class extends X{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(`
279
286
  SELECT * FROM imports
280
287
  WHERE resolved_path IS NOT NULL AND resolved_path != ''
281
288
  `)}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(`
@@ -301,7 +308,7 @@ ORDER BY dc.depth, dc.consumer_path;
301
308
  SELECT COUNT(*) as count FROM imports
302
309
  WHERE resolved_path IN (${n})
303
310
  AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
304
- `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(qi,e,t,n)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});var Qt,Vi=V(()=>{"use strict";be();Qt=class extends K{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
311
+ `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(Qs,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});var Xt,Zs=Q(()=>{"use strict";Ee();Xt=class extends X{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
305
312
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
306
313
  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
307
314
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
@@ -313,7 +320,7 @@ ORDER BY dc.depth, dc.consumer_path;
313
320
  `,e)}create(e){return this.insert(`
314
321
  INSERT INTO missions (name, goal, strategy_graph, status, git_branch, commit_sha, parent_id, verification_context, outcome_contract)
315
322
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
316
- `,e.name,e.goal,e.strategy_graph,e.status,e.git_branch,e.commit_sha,e.parent_id,e.verification_context,e.outcome_contract)}addArtifact(e,t,n,i){this.run("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,t,n,i?JSON.stringify(i):null)}getArtifacts(e){return this.all("SELECT * FROM mission_artifacts WHERE mission_id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE missions SET ${i}, updated_at = unixepoch() WHERE id = ?`,...r)}updateStatus(e,t,n){n?this.run("UPDATE missions SET status = ?, updated_at = unixepoch(), commit_sha = ? WHERE id = ?",t,n,e):this.run("UPDATE missions SET status = ?, updated_at = unixepoch() WHERE id = ?",t,e)}getWorkingSet(e){return this.all("SELECT file_path, type FROM working_set WHERE mission_id = ?",e)}clearWorkingSet(e){this.run("DELETE FROM working_set WHERE mission_id = ?",e)}addToWorkingSet(e,t,n="file"){this.run("INSERT OR IGNORE INTO files (path, mtime, last_scanned_at) VALUES (?, unixepoch(), unixepoch())",t),this.run("INSERT INTO working_set (mission_id, file_path, type) VALUES (?, ?, ?)",e,t,n)}findColdMissions(e,t=10){return this.all(`
323
+ `,e.name,e.goal,e.strategy_graph,e.status,e.git_branch,e.commit_sha,e.parent_id,e.verification_context,e.outcome_contract)}addArtifact(e,t,n,s){this.run("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,t,n,s?JSON.stringify(s):null)}getArtifacts(e){return this.all("SELECT * FROM mission_artifacts WHERE mission_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 missions SET ${s}, updated_at = unixepoch() WHERE id = ?`,...r)}updateStatus(e,t,n){n?this.run("UPDATE missions SET status = ?, updated_at = unixepoch(), commit_sha = ? WHERE id = ?",t,n,e):this.run("UPDATE missions SET status = ?, updated_at = unixepoch() WHERE id = ?",t,e)}getWorkingSet(e){return this.all("SELECT file_path, type FROM working_set WHERE mission_id = ?",e)}clearWorkingSet(e){this.run("DELETE FROM working_set WHERE mission_id = ?",e)}addToWorkingSet(e,t,n="file"){this.run("INSERT OR IGNORE INTO files (path, mtime, last_scanned_at) VALUES (?, unixepoch(), unixepoch())",t),this.run("INSERT INTO working_set (mission_id, file_path, type) VALUES (?, ?, ?)",e,t,n)}findColdMissions(e,t=10){return this.all(`
317
324
  SELECT m.id, COUNT(il.id) as log_count
318
325
  FROM missions m
319
326
  LEFT JOIN intent_logs il ON il.mission_id = m.id
@@ -321,8 +328,8 @@ ORDER BY dc.depth, dc.consumer_path;
321
328
  AND m.status != 'distilled'
322
329
  GROUP BY m.id
323
330
  HAVING log_count > ?
324
- `,e,t).map(i=>i.id)}getStats(){let e=this.get(`
325
- SELECT
331
+ `,e,t).map(s=>s.id)}getStats(){let e=this.get(`
332
+ SELECT
326
333
  COUNT(*) as total,
327
334
  SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
328
335
  SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
@@ -331,13 +338,13 @@ ORDER BY dc.depth, dc.consumer_path;
331
338
  SELECT AVG(updated_at - created_at) AS avg_duration
332
339
  FROM missions
333
340
  WHERE status = 'completed' AND updated_at > created_at
334
- `),i=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,l=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),a=l?.n??0,p=c?.n??0,d=`${a} completed in last 7 days, ${p} in last 30 days.`;if(i!=null){let u=Math.round(i/60);d+=` Avg mission duration: ${u} min.`}return{completionRate:t,averageDurationSeconds:i,completedLast7Days:a,completedLast30Days:p,velocityNote:d}}suspendByBranch(e){this.run(`UPDATE missions
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,d=`${l} completed in last 7 days, ${p} in last 30 days.`;if(s!=null){let u=Math.round(s/60);d+=` Avg mission duration: ${u} min.`}return{completionRate:t,averageDurationSeconds:s,completedLast7Days:l,completedLast30Days:p,velocityNote:d}}suspendByBranch(e){this.run(`UPDATE missions
335
342
  SET status = 'suspended', updated_at = unixepoch()
336
343
  WHERE git_branch = ? AND status IN ('in-progress', 'planned', 'verifying')`,e)}resumeByBranch(e){this.run(`UPDATE missions
337
344
  SET status = 'in-progress', updated_at = unixepoch()
338
- WHERE git_branch = ? AND status = 'suspended'`,e)}findMergedMissions(e,t){if(t.length===0)return[];let n=t.filter(r=>r!==e);if(n.length===0)return[];let i=n.map(()=>"?").join(",");return this.all(`SELECT * FROM missions
345
+ WHERE git_branch = ? AND status = 'suspended'`,e)}findMergedMissions(e,t){if(t.length===0)return[];let n=t.filter(r=>r!==e);if(n.length===0)return[];let s=n.map(()=>"?").join(",");return this.all(`SELECT * FROM missions
339
346
  WHERE status IN ('in-progress', 'planned', 'verifying', 'suspended')
340
- AND git_branch IN (${i})`,...n)}findByCommitShas(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.all(`SELECT * FROM missions WHERE commit_sha IN (${t})`,...e)}findByParentId(e){return this.all("SELECT * FROM missions WHERE parent_id = ?",e)}hasChildren(e){return!!this.get("SELECT 1 FROM missions WHERE parent_id = ? LIMIT 1",e)}hasNoSteps(e){if(!e.strategy_graph)return!0;try{let t=JSON.parse(e.strategy_graph),n=t?.steps??t;return!Array.isArray(n)||n.length===0}catch{return!0}}findParentOnlyIds(e){return e.filter(t=>t.parent_id!=null||!this.hasChildren(t.id)?!1:this.hasNoSteps(t)).map(t=>t.id)}createLink(e,t,n,i,r){this.db.exec(`
347
+ AND git_branch IN (${s})`,...n)}findByCommitShas(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.all(`SELECT * FROM missions WHERE commit_sha IN (${t})`,...e)}findByParentId(e){return this.all("SELECT * FROM missions WHERE parent_id = ?",e)}hasChildren(e){return!!this.get("SELECT 1 FROM missions WHERE parent_id = ? LIMIT 1",e)}hasNoSteps(e){if(!e.strategy_graph)return!0;try{let t=JSON.parse(e.strategy_graph),n=t?.steps??t;return!Array.isArray(n)||n.length===0}catch{return!0}}findParentOnlyIds(e){return e.filter(t=>t.parent_id!=null||!this.hasChildren(t.id)?!1:this.hasNoSteps(t)).map(t=>t.id)}createLink(e,t,n,s,r){this.db.exec(`
341
348
  CREATE TABLE IF NOT EXISTS cross_repo_links (
342
349
  id INTEGER PRIMARY KEY AUTOINCREMENT,
343
350
  mission_id INTEGER NOT NULL,
@@ -352,11 +359,11 @@ ORDER BY dc.depth, dc.consumer_path;
352
359
  `),this.run(`
353
360
  INSERT INTO cross_repo_links (mission_id, linked_repo_path, linked_mission_id, relationship, direction)
354
361
  VALUES (?, ?, ?, ?, ?)
355
- `,e,t,n,i,r)}getLinks(e){try{return this.all(`
362
+ `,e,t,n,s,r)}getLinks(e){try{return this.all(`
356
363
  SELECT linked_repo_path, linked_mission_id, relationship, direction
357
364
  FROM cross_repo_links
358
365
  WHERE mission_id = ?
359
- `,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 Kt,Qi=V(()=>{"use strict";be();Kt=class extends K{findByMission(e,t=50){return this.all(`
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 Zt,ei=Q(()=>{"use strict";Ee();Zt=class extends X{findByMission(e,t=50){return this.all(`
360
367
  SELECT * FROM intent_logs
361
368
  WHERE mission_id = ?
362
369
  ORDER BY created_at DESC
@@ -369,7 +376,7 @@ ORDER BY dc.depth, dc.consumer_path;
369
376
  `,e)}create(e){return this.insert(`
370
377
  INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
371
378
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
372
- `,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 i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${i} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
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(`
373
380
  SELECT id, file_path, symbol_name, signature
374
381
  FROM intent_logs
375
382
  WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
@@ -391,34 +398,34 @@ ORDER BY dc.depth, dc.consumer_path;
391
398
  type = 'lapsed',
392
399
  content = 'Lapsed: ' || content
393
400
  WHERE id = ?
394
- `,e)}importHeritage(e,t,n,i){this.run(`
401
+ `,e)}importHeritage(e,t,n,s){this.run(`
395
402
  INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
396
403
  VALUES ('heritage', ?, ?, ?, ?, 0)
397
- `,e,t,n,i)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}}});var Xt,Ki=V(()=>{"use strict";be();Xt=class extends K{findByKey(e,t=20){return this.all(`
404
+ `,e,t,n,s)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}}});var en,ti=Q(()=>{"use strict";Ee();en=class extends X{findByKey(e,t=20){return this.all(`
398
405
  SELECT file_path, key, value, kind
399
406
  FROM configs
400
407
  WHERE key LIKE ? OR value LIKE ?
401
408
  LIMIT ?
402
- `,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",i=[];return e&&(n+=" WHERE kind = ?",i.push(e)),n+=" LIMIT ?",i.push(t),this.all(n,...i)}findEnvValue(e){return this.get("SELECT value FROM configs WHERE key LIKE ? OR key = ? LIMIT 1",`%:env:${e}`,e)?.value}countByKind(e){return this.get("SELECT COUNT(*) as count FROM configs WHERE kind = ?",e)?.count||0}getAll(){return this.all("SELECT key, value, kind, file_path FROM configs")}}});var Zt,Xi=V(()=>{"use strict";be();Zt=class extends K{search(e,t=10){return this.all(`
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 tn,ni=Q(()=>{"use strict";Ee();tn=class extends X{search(e,t=10){return this.all(`
403
410
  SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
404
411
  FROM content_fts
405
412
  WHERE content_fts MATCH ?
406
413
  LIMIT ?
407
- `,e,t)}}});var Zi,en,es=V(()=>{"use strict";be();Zi=500,en=class extends K{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
408
- 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)<=Zi||this.run(`DELETE FROM search_history WHERE id NOT IN (
414
+ `,e,t)}}});var si,nn,ii=Q(()=>{"use strict";Ee();si=500,nn=class extends X{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
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)<=si||this.run(`DELETE FROM search_history WHERE id NOT IN (
409
416
  SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
410
- )`,Zi)}}});var tn,ts=V(()=>{"use strict";be();tn=class extends K{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(`
417
+ )`,si)}}});var sn,ri=Q(()=>{"use strict";Ee();sn=class extends X{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(`
411
418
  INSERT INTO hologram_snapshot (section, data, updated_at)
412
419
  VALUES (?, ?, unixepoch())
413
420
  ON CONFLICT(section) DO UPDATE SET
414
421
  data = excluded.data,
415
422
  updated_at = excluded.updated_at
416
- `,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 k,F=V(()=>{"use strict";Ve();zi();Gi();Yi();Vi();Qi();Ki();Xi();es();ts();k=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=ke(e),o=t.files?.database,l=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!l)return t;this.repositoryCache.delete(e)}let n=ke(e),i={files:new Jt(n),exports:new Yt(n),imports:new Vt(n),missions:new Qt(n),intentLogs:new Kt(n),configs:new Xt(n),content:new Zt(n),searchHistory:new en(n),hologram:new tn(n)};return this.repositoryCache.set(e,i),i}static closeInstance(e){this.repositoryCache.delete(e),qt(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var ss=Uo((pp,Xn)=>{var sn=process||{},ns=sn.argv||[],nn=sn.env||{},oa=!(nn.NO_COLOR||ns.includes("--no-color"))&&(!!nn.FORCE_COLOR||ns.includes("--color")||sn.platform==="win32"||(sn.stdout||{}).isTTY&&nn.TERM!=="dumb"||!!nn.CI),aa=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+ca(i,e,t,r)+e:s+i+e},ca=(s,e,t,n)=>{let i="",r=0;do i+=s.substring(r,n)+t,r=n+e.length,n=s.indexOf(e,r);while(~n);return i+s.substring(r)},is=(s=oa)=>{let e=s?aa:()=>String;return{isColorSupported:s,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Xn.exports=is();Xn.exports.createColors=is});var lr,pr,ur,dr,mr,hr,fr,gr,yr,br,Er,Sr,_r,xr,_i,Rr,Tr,vr,wr=V(()=>{"use strict";lr=[/\/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],pr=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],ur=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],dr=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],mr=[/\/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],fr=[/\/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],gr=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],yr=[/\/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],Er=[/\/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],Sr=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],_r=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],xr=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],_i=[/\.(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)$/],Rr=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],Tr=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],vr=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var Ir,kr,Cr,Lr,$r=V(()=>{"use strict";Ir=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],kr=[/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],Cr=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],Lr=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var Nr,Ar,Mr,Pr,Dr=V(()=>{"use strict";Nr=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],Ar=[/\/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],Mr=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],Pr=["laravel","symfony","slim","cakephp","codeigniter"]});import Or from"path";function Dt(s,e,t){let n=[],i="Unknown",r=0;t||(t=dc(s,e));let{inDegree:o,outDegree:l}=t,c=(u,m,h,b)=>{for(let E of u)if(E.test(s))return n.push(`${b}: ${E.source}`),i=m,r+=h,!0;return!1},a=!1;if(a||(a=c(lr,"Entry",45,"Next.js entry")),a||(a=c(mr,"Entry",40,"MCP handler")),a||(a=c(fr,"Entry",40,"CLI command")),a||(a=c(_i,"Data",45,"Data layer/Repository")),a||(a=c(Er,"Data",35,"State management")),a||(a=c(ur,"Logic",40,"React component")),a||(a=c(dr,"Logic",35,"Logic pattern")),a||(a=c(gr,"Logic",35,"Parser/AST")),a||(a=c(yr,"Logic",35,"Core module")),a||(a=c(br,"Logic",30,"UI layer")),a||(a=c(xr,"Types",35,"Type definition")),a||(a=c(Ir,"Entry",40,"Python Entry")),a||(a=c(Cr,"Data",40,"Python Data")),a||(a=c(kr,"Logic",35,"Python Logic")),a||(a=c(Nr,"Entry",40,"PHP Entry")),a||(a=c(Mr,"Data",40,"PHP Data")),a||(a=c(Ar,"Logic",35,"PHP Logic")),a||(a=c(Sr,"Logic",35,"Hook/Context")),!a){for(let u of hr)if(u.test(s)){n.push(`MCP utility: ${u.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,a=!0;break}}a||c(_r,"Data",35,"Schema definition")&&(a=!0),a||(c(_i,"Data",30,"Path matches data pattern")||c(Rr,"Utility",25,"Path matches utility pattern")||c(pr,"Entry",30,"Path matches entry pattern"))&&(a=!0);for(let u of lc)if(u.test(s)){n.push(`Test file: ${u.source}`),i="Test",r=50,a=!0;break}a||c(pc,"Infrastructure",40,"Infrastructure")&&(a=!0);for(let u of uc)u.test(s)&&(n.push(`Monorepo component: ${u.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let d=e.imports.getImportsForFile(s).map(u=>u.module_specifier.toLowerCase());for(let u of vr)if(d.some(m=>m.includes(u))){n.push(`Imports JS data library: ${u}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let u of Lr)if(d.some(m=>m.includes(u))){n.push(`Imports Python framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let u of Pr)if(d.some(m=>m.includes(u))){n.push(`Imports PHP framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let u of Tr)if(d.some(m=>m.includes(u))){n.push(`Imports JS framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}if(o===0&&l>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),i==="Unknown"?(i="Entry",r+=30):i==="Entry"&&(r+=15)),o>5&&l<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),i==="Unknown"?(i="Utility",r+=25):i==="Utility"&&(r+=10)),i==="Unknown"&&o>0&&l>0){let u=o/(o+l);u>.3&&u<.7&&(n.push(`Balanced traffic: in=${o}, out=${l} (likely Logic layer)`),i="Logic",r+=25)}return i==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:i,confidence:r,signals:n}}function dc(s,e){let t=e.imports.countDependents(s),n=e.imports.countByFile(s);return{inDegree:t,outDegree:n}}function ut(s,e){let t=s.files.getAllPaths().map(h=>({path:h})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let h of t){let b=Dt(h.path,s);n.set(h.path,b),i[b.layer].push({path:h.path,classification:b})}let r={Entry:We(i.Entry,e),Logic:We(i.Logic,e),Data:We(i.Data,e),Utility:We(i.Utility,e),Infrastructure:We(i.Infrastructure,e),Test:We(i.Test,e),Types:We(i.Types,e),Unknown:We(i.Unknown,e)},o={};t.forEach(h=>{let b=Or.extname(h.path).toLowerCase();b&&(o[b]=(o[b]||0)+1)});let l={".ts":"TypeScript",".tsx":"Typescript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".php":"PHP",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".vue":"Vue"},c={};Object.entries(o).forEach(([h,b])=>{let E=l[h];E&&(c[E]=(c[E]||0)+b)});let a=Object.entries(c).sort((h,b)=>b[1]-h[1]),p=a.length>0?a[0][0]:"Unknown",{pattern:d,patternConfidence:u,insights:m}=mc(r,t.length,s);return{pattern:d,patternConfidence:u,layers:r,insights:m,primaryStack:p}}function We(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:Or.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function mc(s,e,t){let n=[],i="Unknown",r=0,o=s.Entry.count/e*100,l=s.Logic.count/e*100,c=s.Data.count/e*100,a=s.Utility.count/e*100,p=s.Unknown.count/e*100;o>5&&l>10&&c>5&&p<40?(i="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${l.toFixed(1)}%), Data (${c.toFixed(1)}%)`)):a>20?(i="Modular",r=50+a/2,n.push(`High shared module usage: ${a.toFixed(1)}% utility files`)):p>60&&(i="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let d=t.configs.countByKind("Service");return d>3&&(i="Microservices",r=55+d*5,n.push(`Detected ${d} service definitions (likely microservices)`)),s.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),s.Data.count===0&&n.push("\u26A0\uFE0F No data layer detected - repository may not use traditional ORM patterns"),a>30&&n.push(`High utility concentration (${a.toFixed(1)}%) - good reusability`),{pattern:i,patternConfidence:Math.min(100,r),insights:n}}var lc,pc,uc,Ot=V(()=>{"use strict";wr();$r();Dr();lc=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],pc=[/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],uc=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});var Fr={};Ai(Fr,{HologramService:()=>de});var ye,de,dt=V(()=>{"use strict";F();Ot();N();ye=_.child({module:"hologram"}),de=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=k.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 l=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(l*10)/10,topFiles:o.topFiles.slice(0,3).map(c=>({path:c.path,confidence:c.confidence}))}}let i={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(i)),ye.info({repoPath:this.repoPath},"Topography snapshot updated")}updateGravityZones(e){ye.debug({repoPath:this.repoPath,count:e.length},"Updating gravity zones");let t={hotspots:e.slice(0,10),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 i=JSON.parse(n.data);switch(n.section){case"topography":t.topography=i;break;case"gravity":t.gravity=i;break;case"ghosts":t.ghosts=i;break}}catch(i){ye.error({repoPath:this.repoPath,section:n.section,error:i},"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 i of e){let r=Dt(i,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(i);if(o.length===0)continue;let l=this.repos.imports.countDependents(i),c=this.repos.imports.countByFile(i),a=l*2+c;if(a>0){let p=o.find(u=>u.kind!=="TsTypeAliasDeclaration"&&u.kind!=="TsInterfaceDeclaration")||o[0],d=`${i}::${p.name}`;t.set(d,{symbol:p.name,filePath:i,inDegree:l,outDegree:c,gravity:a})}}let n=Array.from(t.values()).sort((i,r)=>r.gravity-i.gravity).slice(0,20);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 xo={};Ai(xo,{GraphExporterService:()=>$i});var _o,$i,Ro=V(()=>{"use strict";F();N();_o=_.child({module:"graph-exporter"}),$i=class{constructor(e){this.repoPath=e;this.repos=k.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;_o.info({focusMissionId:i,depth:r,format:n,includeCompleted:t},"Generating mission graph");let l=this.buildMissionTree(i,t,r,o);return n==="json"?JSON.stringify(l,null,2):this.generateMermaidDiagram(l)}buildMissionTree(e,t,n,i){let r;if(e){let c=this.repos.missions.findById(e);r=c?[c]:[]}else r=this.repos.missions.findAll().filter(a=>!a.parent_id),t||(r=r.filter(a=>a.status!=="completed"));let o=0,l=[];for(let c of r){if(o>=i)break;let a=this.buildNode(c,t,n,1,{count:o,max:i});a&&(l.push(a),o+=this.countNodes(a))}return l}buildNode(e,t,n,i,r){if(i>n||r.count>=r.max)return null;let o;if(e.strategy_graph)try{let p=JSON.parse(e.strategy_graph);o=this.parseStrategySteps(p)}catch(p){_o.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let l={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},c=this.repos.missions.findByParentId(e.id),a=t?c:c.filter(p=>p.status!=="completed");for(let p of a){if(r.count>=r.max)break;let d=this.buildNode(p,t,n,i+1,r);d&&(l.children.push(d),r.count++)}return l}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,i)=>({id:n.id||`step-${i}`,description:n.description||n.content||n.name||`Step ${i+1}`,status:n.status,dependencies:n.dependencies||n.deps})):e.steps&&Array.isArray(e.steps)?this.parseStrategySteps(e.steps):typeof e=="object"?Object.entries(e).map(([n,i])=>({id:n,description:i.description||i.content||n,status:i.status,dependencies:i.dependencies||i.deps})):t}countNodes(e){let t=1;for(let n of e.children)t+=this.countNodes(n);return t}generateMermaidDiagram(e){let t=["graph TD"];for(let n of e)this.addMermaidNode(n,t);return t.join(`
417
- `)}addMermaidNode(e,t,n){let i=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),l=`${r} ${e.name}`;if(t.push(` ${i}["${this.escapeMermaid(l)}"]:::${o}`),n&&t.push(` ${n} --> ${i}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let c of e.steps){let a=`S${e.id}_${c.id}`,p=c.status||"pending",d=this.getStatusIcon(p),u=this.getStatusClass(p),m=`${d} ${c.description}`;if(t.push(` ${a}["${this.escapeMermaid(m)}"]:::${u}`),t.push(` ${i} -.-> ${a}`),c.dependencies&&c.dependencies.length>0)for(let h of c.dependencies){let b=`S${e.id}_${h}`;t.push(` ${b} --> ${a}`)}}for(let c of e.children)this.addMermaidNode(c,t,i);n||(t.push(""),t.push(" classDef completed fill:#90EE90,stroke:#2E8B57,stroke-width:2px"),t.push(" classDef inProgress fill:#87CEEB,stroke:#4682B4,stroke-width:2px"),t.push(" classDef planned fill:#FFE4B5,stroke:#DAA520,stroke-width:2px"),t.push(" classDef suspended fill:#D3D3D3,stroke:#808080,stroke-width:2px"),t.push(" classDef failed fill:#FFB6C1,stroke:#DC143C,stroke-width:2px"),t.push(" classDef pending fill:#FFF8DC,stroke:#B8860B,stroke-width:1px"))}getStatusIcon(e){return{completed:"\u2713","in-progress":"\u26A1",planned:"\u{1F4CB}",suspended:"\u23F8",failed:"\u2717",pending:"\u25CB",verifying:"\u{1F50D}"}[e]||"\u25CB"}getStatusClass(e){return{completed:"completed","in-progress":"inProgress",planned:"planned",suspended:"suspended",failed:"failed",pending:"pending",verifying:"inProgress"}[e]||"pending"}escapeMermaid(e){return e.replace(/"/g,"#quot;").replace(/\n/g," ").replace(/\[/g,"#91;").replace(/]/g,"#93;").slice(0,100)}}});import"dotenv/config";import{Cli as cl}from"clerc";N();import Mi from"fs";import Jo from"path";import Pi from"js-yaml";var Di={ignore:[],include:[],maxDepth:10},Yo=[{name:".liquid-shadow.yaml",parse:s=>Pi.load(s)??{}},{name:".liquid-shadow.yml",parse:s=>Pi.load(s)??{}},{name:".ls.json",parse:s=>JSON.parse(s)},{name:".liquid-shadow.json",parse:s=>JSON.parse(s)},{name:".ls.rc",parse:s=>JSON.parse(s)},{name:".liquid-shadow.rc",parse:s=>JSON.parse(s)}];function we(s){for(let{name:e,parse:t}of Yo){let n=Jo.join(s,e);if(Mi.existsSync(n))try{let i=Mi.readFileSync(n,"utf8"),r=t(i);return _.info({repoPath:s,configFile:e},"Loaded repository configuration"),{...Di,...r}}catch(i){_.error({repoPath:s,file:e,err:i},"Failed to parse configuration file")}}return Di}function Oi(s,e){let n=we(s).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}F();import Ra from"path";var ee=Bo(ss(),1);import*as Ee from"@clack/prompts";var z={red:ee.default.red,green:ee.default.green,yellow:ee.default.yellow,blue:ee.default.blue,magenta:ee.default.magenta,cyan:ee.default.cyan,white:ee.default.white,gray:ee.default.gray,bold:ee.default.bold,dim:ee.default.dim,italic:ee.default.italic,underline:ee.default.underline,inverse:ee.default.inverse},Pe=s=>s.replace(/\x1b\[[0-9;]*m/g,""),le=s=>Ee.intro(ee.default.bgCyan(ee.default.black(ee.default.bold(` ${s} `)))),Rt=s=>Ee.outro(ee.default.cyan(s)),te=(s,e,t="blue")=>{let n=e.split(`
418
- `),i=Pe(s),r=Math.max(i.length+4,...n.map(c=>Pe(c).length))+2,o="\u2500".repeat(r),l=z[t];console.log(l(`\u250C${o}\u2510`)),console.log(l("\u2502 ")+z.bold(s).padEnd(r+(s.length-i.length)-1)+l("\u2502")),console.log(l(`\u251C${o}\u2524`)),n.forEach(c=>{let a=Pe(c),p=" ".repeat(r-a.length-1);console.log(l("\u2502 ")+c+p+l("\u2502"))}),console.log(l(`\u2514${o}\u2518`))},rn=(s,e)=>{let t=s.map((i,r)=>Math.max(Pe(i).length,...e.map(o=>Pe(o[r]||"").length))+2),n=z.cyan("\u2502");console.log(n),console.log(n+" "+s.map((i,r)=>z.bold(z.cyan(i)).padEnd(t[r]+(i.length-Pe(i).length))).join(z.gray(" "))+" "),e.forEach(i=>{console.log(n+" "+i.map((r,o)=>(r||"").padEnd(t[o]+(r.length-Pe(r).length))).join(z.gray(" "))+" ")}),console.log(n)},rs=(s,e="\u2022")=>{s.forEach(t=>{console.log(`${z.cyan("\u2502")} ${z.cyan(e)} ${t}`)})},os=(s,e=40)=>{let t=Math.max(...s.map(i=>i.value)),n=Math.max(...s.map(i=>Pe(i.label).length));console.log(z.cyan("\u2502")),s.forEach(i=>{let r=Math.round(i.value/t*e),o="\u2588".repeat(r)+z.dim("\u2591".repeat(e-r)),l=i.color?z[i.color]:z.cyan,c=i.label.padEnd(n);console.log(`${z.cyan("\u2502")} ${z.bold(c)} ${l(o)} ${z.white(i.value.toString())}`)}),console.log(z.cyan("\u2502"))},Zn=(s,e="")=>{s.forEach((t,n)=>{let i=n===s.length-1,r=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?z[t.color]:t.children?z.blue:z.white,l=t.info?` ${z.gray(`(${t.info})`)}`:"";if(console.log(`${z.cyan("\u2502")} ${e}${z.gray(r)}${o(t.name)}${l}`),t.children&&t.children.length>0){let c=e+(i?" ":"\u2502 ");Zn(t.children,c)}})},ue=()=>Ee.spinner();async function on(s,e,t){if(e.length===0)return;let n=await Ee.select({message:s,options:e.map(i=>({value:i.value,label:i.label,...i.hint!=null&&{hint:i.hint}})),...t?.limit!=null&&{maxItems:t.limit}});if(!Ee.isCancel(n))return n}var la=s=>{console.error("");let e=s instanceof Error?s.message:String(s);console.error(` ${z.red("\u2716")} ${z.bold("Error: ")} ${e}`),s instanceof Error&&"cause"in s&&console.error(` ${z.dim("Cause: "+String(s.cause))}`),console.error(""),process.exit(1)},U=async s=>{try{await s()}catch(e){la(e)}},f=z;N();N();import{Worker as fa}from"node:worker_threads";import{cpus as ga}from"node:os";import{fileURLToPath as ya}from"node:url";import{dirname as ba,join as ls}from"node:path";import{existsSync as ps}from"node:fs";import{fileURLToPath as pa}from"node:url";import{dirname as ei,join as cs,resolve as ua}from"node:path";import{existsSync as da}from"node:fs";var ma=pa(import.meta.url),as=ei(ma);function ha(){let s=as;for(;s!==ei(s);){if(da(cs(s,"package.json")))return s;s=ei(s)}return ua(as,"..","..")}function an(...s){return cs(ha(),...s)}var ds=ya(import.meta.url),us=ba(ds);function Ea(){if(ds.endsWith(".ts")){let e=ls(us,"worker.ts");if(ps(e))return e}let s=ls(us,"worker.js");return ps(s)?s:an("dist/logic/domain/embeddings/worker.js")}var Tt=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,ga().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{_.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((n,i)=>{e=setTimeout(()=>i(new Error(`Worker pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0,_.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,_.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=Ea();_.debug({workerPath:e},"Resolved worker path");for(let t=0;t<this.numWorkers;t++)await this.createWorker(e,t),await new Promise(n=>setTimeout(n,50))}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new fa(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),l={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){_.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(l),_.debug({workerIndex:t},"Worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(l,c.id,c.embeddings||[]):c.type==="error"&&c.id&&this.handleTaskError(l,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),_.error({err:c,workerIndex:t},"Worker error"),l.currentTaskId&&this.handleTaskError(l,l.currentTaskId,c),!this.initialized){i(c);return}let a=this.workers.indexOf(l);a!==-1&&this.workers.splice(a,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{_.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&_.warn({workerIndex:t,code:c},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=32,n){if(this.initialized||await this.initialize(),e.length===0)return[];let i=[];for(let a=0;a<e.length;a+=t)i.push(e.slice(a,a+t));let r=new Array(i.length),o=0,l=i.map((a,p)=>new Promise((d,u)=>{let h={id:`task_${++this.taskIdCounter}`,texts:a,resolve:b=>{if(r[p]=b,o++,n){let E=Math.min(o*t,e.length);n(E,e.length)}d()},reject:b=>{if(r[p]=new Array(a.length).fill(null),o++,_.warn({err:b,chunkIndex:p},"Chunk embedding failed"),n){let E=Math.min(o*t,e.length);n(E,e.length)}d()}};this.taskQueue.push(h),this.processQueue()}));await Promise.all(l);let c=[];for(let a of r)c.push(...a);return _.info({total:e.length,successful:c.filter(a=>a!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),c}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}_.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,_.info("Embedding worker pool shutdown complete")}},it=null;function ti(s){return it||(it=new Tt(s)),it}async function cn(){it&&(await it.shutdown(),it=null)}var vt=null;async function Sa(){return vt||(vt=await import("@xenova/transformers"),vt.env.cacheDir="./.cache",vt.env.allowLocalModels=!1),vt}var _a=128,ms=!1;function ln(s){ms=s,_.info({useWorkerThreads:s},"Worker thread mode updated")}var ni=null;async function hs(){return ni||(ni=(async()=>{_.info("Loading embedding model (all-MiniLM-L6-v2)...");let{pipeline:s}=await Sa();return await s("feature-extraction","Xenova/all-MiniLM-L6-v2")})()),ni}async function ii(s){try{let t=await(await hs())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return _.error({err:e},"Failed to generate embedding"),null}}async function si(s,e=_a,t){return s.length===0?[]:ms?ti().generateEmbeddings(s,e,t):xa(s,e,t)}async function xa(s,e,t){let n=new Array(s.length).fill(null),i=await hs();for(let r=0;r<s.length;r+=e){let o=Math.min(r+e,s.length),l=s.slice(r,o);try{let c=await i(l,{pooling:"mean",normalize:!0}),[a,p]=c.dims;for(let d=0;d<a;d++){let u=d*p,m=u+p;n[r+d]=Array.from(c.data.slice(u,m))}}catch(c){_.error({err:c,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let a=0;a<l.length;a++)try{let p=l[a];if(!p||p.trim().length===0)continue;let d=await i(p,{pooling:"mean",normalize:!0});n[r+a]=Array.from(d.data)}catch{n[r+a]=null}}t&&t(o,s.length)}return _.debug({total:s.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function ri(s,e){let t=0,n=0,i=0;for(let r=0;r<s.length;r++)t+=s[r]*e[r],n+=s[r]*s[r],i+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(i))}Ve();N();async function G(s){_.info("Performing graceful shutdown...");try{await cn()}catch(e){_.error({err:e},"Error shutting down worker pool")}try{s&&qt(s)}catch(e){_.error({err:e},"Error closing database")}_.info("Shutdown complete")}async function fs(s){let e=Ra.resolve(s);try{await U(async()=>{let t=k.getInstance(e),n=we(e),i=n.ignore&&n.ignore.length>0,r=t.files.getCount(),o=t.exports.getCount(),l=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);te("Repo Status",`${f.bold("Files")}: ${f.cyan(r.toString())}
419
- ${f.bold("Symbols")}: ${f.cyan(o.toString())}
420
- ${f.bold("Last Scan")}: ${l?f.yellow(new Date(l).toLocaleString()):f.red("Never")}
421
- ${f.bold("Config")}: ${i?f.green("Active"):f.gray("Default")}`,"blue"),c.length>0&&(console.log(""),console.log(` ${f.bold("Symbol Distribution (Top 5) ")}`),os(c.map(a=>({label:a.kind,value:a.c,color:"cyan"})),30))})}finally{await G(e)}}F();Ve();import Ta from"path";N();import re from"fs";import Qe from"path";var st=_.child({module:"git-hooks"}),pn={"post-merge":`#!/bin/sh
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",d=this.getStatusIcon(p),u=this.getStatusClass(p),m=`${d} ${a.description}`;if(t.push(` ${l}["${this.escapeMermaid(m)}"]:::${u}`),t.push(` ${s} -.-> ${l}`),a.dependencies&&a.dependencies.length>0)for(let f of a.dependencies){let h=`S${e.id}_${f}`;t.push(` ${h} --> ${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 fl}from"clerc";P();import Fs from"fs";import Xo from"path";import Hs from"js-yaml";var Ws={ignore:[],include:[],maxDepth:10},Zo=[{name:".liquid-shadow.yaml",parse:i=>Hs.load(i)??{}},{name:".liquid-shadow.yml",parse:i=>Hs.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 Ce(i){for(let{name:e,parse:t}of Zo){let n=Xo.join(i,e);if(Fs.existsSync(n))try{let s=Fs.readFileSync(n,"utf8"),r=t(s);return _.info({repoPath:i,configFile:e},"Loaded repository configuration"),{...Ws,...r}}catch(s){_.error({repoPath:i,file:e,err:s},"Failed to parse configuration file")}}return Ws}function js(i,e){let n=Ce(i).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}U();import Ca from"path";var ne=Yo(ci(),1);import*as Se from"@clack/prompts";var G={red:ne.default.red,green:ne.default.green,yellow:ne.default.yellow,blue:ne.default.blue,magenta:ne.default.magenta,cyan:ne.default.cyan,white:ne.default.white,gray:ne.default.gray,bold:ne.default.bold,dim:ne.default.dim,italic:ne.default.italic,underline:ne.default.underline,inverse:ne.default.inverse},Pe=i=>i.replace(/\x1b\[[0-9;]*m/g,""),le=i=>Se.intro(ne.default.bgCyan(ne.default.black(ne.default.bold(` ${i} `)))),Tt=i=>Se.outro(ne.default.cyan(i)),se=(i,e,t="blue")=>{let n=e.split(`
425
+ `),s=Pe(i),r=Math.max(s.length+4,...n.map(a=>Pe(a).length))+2,o="\u2500".repeat(r),c=G[t];console.log(c(`\u250C${o}\u2510`)),console.log(c("\u2502 ")+G.bold(i).padEnd(r+(i.length-s.length)-1)+c("\u2502")),console.log(c(`\u251C${o}\u2524`)),n.forEach(a=>{let l=Pe(a),p=" ".repeat(r-l.length-1);console.log(c("\u2502 ")+a+p+c("\u2502"))}),console.log(c(`\u2514${o}\u2518`))},an=(i,e)=>{let t=i.map((s,r)=>Math.max(Pe(s).length,...e.map(o=>Pe(o[r]||"").length))+2),n=G.cyan("\u2502");console.log(n),console.log(n+" "+i.map((s,r)=>G.bold(G.cyan(s)).padEnd(t[r]+(s.length-Pe(s).length))).join(G.gray(" "))+" "),e.forEach(s=>{console.log(n+" "+s.map((r,o)=>(r||"").padEnd(t[o]+(r.length-Pe(r).length))).join(G.gray(" "))+" ")}),console.log(n)},li=(i,e="\u2022")=>{i.forEach(t=>{console.log(`${G.cyan("\u2502")} ${G.cyan(e)} ${t}`)})},pi=(i,e=40)=>{let t=Math.max(...i.map(s=>s.value)),n=Math.max(...i.map(s=>Pe(s.label).length));console.log(G.cyan("\u2502")),i.forEach(s=>{let r=Math.round(s.value/t*e),o="\u2588".repeat(r)+G.dim("\u2591".repeat(e-r)),c=s.color?G[s.color]:G.cyan,a=s.label.padEnd(n);console.log(`${G.cyan("\u2502")} ${G.bold(a)} ${c(o)} ${G.white(s.value.toString())}`)}),console.log(G.cyan("\u2502"))},ts=(i,e="")=>{i.forEach((t,n)=>{let s=n===i.length-1,r=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?G[t.color]:t.children?G.blue:G.white,c=t.info?` ${G.gray(`(${t.info})`)}`:"";if(console.log(`${G.cyan("\u2502")} ${e}${G.gray(r)}${o(t.name)}${c}`),t.children&&t.children.length>0){let a=e+(s?" ":"\u2502 ");ts(t.children,a)}})},de=()=>Se.spinner();async function cn(i,e,t){if(e.length===0)return;let n=await Se.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(!Se.isCancel(n))return n}var ha=i=>{console.error("");let e=i instanceof Error?i.message:String(i);console.error(` ${G.red("\u2716")} ${G.bold("Error: ")} ${e}`),i instanceof Error&&"cause"in i&&console.error(` ${G.dim("Cause: "+String(i.cause))}`),console.error(""),process.exit(1)},B=async i=>{try{await i()}catch(e){ha(e)}},E=G;P();P();import{Worker as Sa}from"node:worker_threads";import{cpus as _a}from"node:os";import{fileURLToPath as xa}from"node:url";import{dirname as Ta,join as mi}from"node:path";import{existsSync as hi}from"node:fs";import{fileURLToPath as fa}from"node:url";import{dirname as ns,join as di,resolve as ga}from"node:path";import{existsSync as ya}from"node:fs";var ba=fa(import.meta.url),ui=ns(ba);function Ea(){let i=ui;for(;i!==ns(i);){if(ya(di(i,"package.json")))return i;i=ns(i)}return ga(ui,"..","..")}function ln(...i){return di(Ea(),...i)}var gi=xa(import.meta.url),fi=Ta(gi);function Ra(){if(gi.endsWith(".ts")){let e=mi(fi,"worker.ts");if(hi(e))return e}let i=mi(fi,"worker.js");return hi(i)?i:ln("dist/logic/domain/embeddings/worker.js")}var Rt=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,_a().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{_.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,_.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,_.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=Ra();_.debug({workerPath:e},"Resolved worker path");for(let t=0;t<this.numWorkers;t++)await this.createWorker(e,t),await new Promise(n=>setTimeout(n,50))}async createWorker(e,t){return new Promise((n,s)=>{let r=setTimeout(()=>{s(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new Sa(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){_.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(c),_.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),_.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=>{_.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",a=>{a!==0&&!this.shutdownRequested&&_.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=32,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((d,u)=>{let f={id:`task_${++this.taskIdCounter}`,texts:l,resolve:h=>{if(r[p]=h,o++,n){let b=Math.min(o*t,e.length);n(b,e.length)}d()},reject:h=>{if(r[p]=new Array(l.length).fill(null),o++,_.warn({err:h,chunkIndex:p},"Chunk embedding failed"),n){let b=Math.min(o*t,e.length);n(b,e.length)}d()}};this.taskQueue.push(f),this.processQueue()}));await Promise.all(c);let a=[];for(let l of r)a.push(...l);return _.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}_.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,_.info("Embedding worker pool shutdown complete")}},it=null;function ss(i){return it||(it=new Rt(i)),it}async function pn(){it&&(await it.shutdown(),it=null)}var vt=null;async function va(){return vt||(vt=await import("@xenova/transformers"),vt.env.cacheDir="./.cache",vt.env.allowLocalModels=!1),vt}var wa=128,yi=!1;function un(i){yi=i,_.info({useWorkerThreads:i},"Worker thread mode updated")}var is=null;async function bi(){return is||(is=(async()=>{_.info("Loading embedding model (all-MiniLM-L6-v2)...");let{pipeline:i}=await va();return await i("feature-extraction","Xenova/all-MiniLM-L6-v2")})()),is}async function rs(i){try{let t=await(await bi())(i,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return _.error({err:e},"Failed to generate embedding"),null}}async function os(i,e=wa,t){return i.length===0?[]:yi?ss().generateEmbeddings(i,e,t):Ia(i,e,t)}async function Ia(i,e,t){let n=new Array(i.length).fill(null),s=await bi();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 d=0;d<l;d++){let u=d*p,m=u+p;n[r+d]=Array.from(a.data.slice(u,m))}}catch(a){_.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 d=await s(p,{pooling:"mean",normalize:!0});n[r+l]=Array.from(d.data)}catch{n[r+l]=null}}t&&t(o,i.length)}return _.debug({total:i.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function as(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))}Qe();P();async function q(i){_.info("Performing graceful shutdown...");try{await pn()}catch(e){_.error({err:e},"Error shutting down worker pool")}try{i&&Yt(i)}catch(e){_.error({err:e},"Error closing database")}_.info("Shutdown complete")}async function Ei(i){let e=Ca.resolve(i);try{await B(async()=>{let t=C.getInstance(e),n=Ce(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);se("Repo Status",`${E.bold("Files")}: ${E.cyan(r.toString())}
426
+ ${E.bold("Symbols")}: ${E.cyan(o.toString())}
427
+ ${E.bold("Last Scan")}: ${c?E.yellow(new Date(c).toLocaleString()):E.red("Never")}
428
+ ${E.bold("Config")}: ${s?E.green("Active"):E.gray("Default")}`,"blue"),a.length>0&&(console.log(""),console.log(` ${E.bold("Symbol Distribution (Top 5) ")}`),pi(a.map(l=>({label:l.kind,value:l.c,color:"cyan"})),30))})}finally{await q(e)}}U();Qe();import $a from"path";P();import oe from"fs";import Ke from"path";var rt=_.child({module:"git-hooks"}),dn={"post-merge":`#!/bin/sh
422
429
  # Liquid Shadow: Auto-refresh index after merge/pull
423
430
  # Generated by liquid-shadow
424
431
 
@@ -452,22 +459,22 @@ REPO_PATH="$(git rev-parse --show-toplevel)"
452
459
  nohup npx @precisionutilityguild/liquid-shadow sync "$REPO_PATH" > /dev/null 2>&1 &
453
460
 
454
461
  exit 0
455
- `};function gs(s){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=s,i=Qe.join(e,".git","hooks"),r=[],o=[],l=[];if(!re.existsSync(Qe.join(e,".git")))return l.push("Not a git repository"),{installed:r,skipped:o,errors:l};re.existsSync(i)||re.mkdirSync(i,{recursive:!0});let c=[];t&&c.push("post-merge","post-checkout"),n&&c.push("post-commit");for(let a of c){let p=Qe.join(i,a),d=pn[a];if(!d){l.push(`No template found for hook: ${a}`);continue}try{if(re.existsSync(p)){let u=re.readFileSync(p,"utf-8");if(u.includes("liquid-shadow")||u.includes("mcp-liquid-shadow")){o.push(a),st.info({hookName:a},"Hook already installed, skipping");continue}let m=`${p}.backup-${Date.now()}`;re.copyFileSync(p,m),st.info({hookName:a,backupPath:m},"Backed up existing hook")}re.writeFileSync(p,d,{mode:493}),r.push(a),st.info({hookName:a},"Installed git hook")}catch(u){l.push(`Failed to install ${a}: ${u}`),st.error({hookName:a,err:u},"Failed to install hook")}}return{installed:r,skipped:o,errors:l}}function ys(s){let e=Qe.join(s,".git","hooks"),t=[],n=[];if(!re.existsSync(e))return{removed:t,errors:n};let i=Object.keys(pn);for(let r of i){let o=Qe.join(e,r);try{if(re.existsSync(o)){let l=re.readFileSync(o,"utf-8");(l.includes("liquid-shadow")||l.includes("mcp-liquid-shadow"))&&(re.unlinkSync(o),t.push(r),st.info({hookName:r},"Removed git hook"))}}catch(l){n.push(`Failed to remove ${r}: ${l}`),st.error({hookName:r,err:l},"Failed to remove hook")}}return{removed:t,errors:n}}function un(s){let e=Qe.join(s,".git","hooks"),t=[],n=[];if(!re.existsSync(e))return{installed:t,notInstalled:Object.keys(pn)};let i=Object.keys(pn);for(let r of i){let o=Qe.join(e,r);if(re.existsSync(o)){let l=re.readFileSync(o,"utf-8");l.includes("liquid-shadow")||l.includes("mcp-liquid-shadow")?t.push(r):n.push(r)}else n.push(r)}return{installed:t,notInstalled:n}}var oi=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];searchHistoryFailureCount=0;recordIndexStart(){this.indexRuns+=1}recordIndexCacheHit(){this.indexCacheHits+=1}recordIndexEnd(e){this.lastIndexDurationMs=e,this.lastIndexCompletedAt=Date.now()}recordIndexPhase(e,t){this.lastRunPhases.push({phase:e,durationMs:t})}clearIndexPhases(){this.lastRunPhases=[]}recordQueryStart(){let e=performance.now();return()=>{this.queryCount+=1;let t=performance.now()-e;if(this.lastQueryLatencyMs=t,this.recentLatencies.push(t),this.recentLatencies.length>100){let n=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-n+t}else this.recentLatencySumMs+=t,this.recentLatencyCount=this.recentLatencies.length}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((n,i)=>n+i,0)/e:null;return{index:{runs:this.indexRuns,cacheHits:this.indexCacheHits,lastDurationMs:this.lastIndexDurationMs,lastCompletedAt:this.lastIndexCompletedAt,lastRunPhases:[...this.lastRunPhases]},query:{count:this.queryCount,lastLatencyMs:this.lastQueryLatencyMs,recentLatencySumMs:this.recentLatencySumMs,recentLatencyCount:e,avgLatencyMs:t,searchHistoryFailures:this.searchHistoryFailureCount},uptimeMs:Date.now()-this.startTime}}reset(){this.indexRuns=0,this.indexCacheHits=0,this.lastIndexDurationMs=null,this.lastIndexCompletedAt=null,this.lastRunPhases=[],this.queryCount=0,this.lastQueryLatencyMs=null,this.recentLatencySumMs=0,this.recentLatencyCount=0,this.recentLatencies=[],this.searchHistoryFailureCount=0}},De=new oi;function bs(){De.recordIndexStart()}function ai(){De.recordIndexCacheHit()}function Es(s){De.recordIndexEnd(s)}function dn(s,e){De.recordIndexPhase(s,e)}function Ss(){De.clearIndexPhases()}function mn(){return De.recordQueryStart()}function rt(){De.recordSearchHistoryFailure()}function _s(){return De.getSnapshot()}async function xs(s){let e=Ta.resolve(s);try{await U(async()=>{let t=k.getInstance(e),n=un(e),i=_s(),r=Math.floor(i.uptimeMs/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=l>0?`${l}h ${o%60}m`:o>0?`${o}m ${r%60}s`:`${r}s`,a=i.index.lastCompletedAt?new Date(i.index.lastCompletedAt).toLocaleString():"Never",p=i.index.lastDurationMs?`${(i.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",d=i.query.avgLatencyMs?`${i.query.avgLatencyMs.toFixed(2)}ms`:"N/A",u=i.query.lastLatencyMs?`${i.query.lastLatencyMs.toFixed(2)}ms`:"N/A",m=i.index.runs>0?(i.index.cacheHits/i.index.runs*100).toFixed(1):"0.0";te("Performance Metrics",`${f.bold("Uptime")}: ${f.cyan(c)}
456
- ${f.bold("Indexed")}: ${Ye(e)?f.green("Yes"):f.red("No")}
457
- ${f.bold("Files")}: ${f.cyan(t.files.getCount().toString())}
458
- ${f.bold("Exports")}: ${f.cyan(t.exports.getCount().toString())}
459
- ${f.bold("Imports")}: ${f.cyan(t.imports.getCount().toString())}
460
- ${f.bold("Last Indexed Commit")}: ${xt(e)?f.yellow(xt(e).substring(0,7)):f.red("None")}
461
- ${f.bold("Git Hooks")}: ${n.installed?f.green("Installed"):f.yellow("Not Installed")}`,"blue"),console.log(""),te("Index Metrics",`${f.bold("Total Runs")}: ${f.cyan(i.index.runs.toString())}
462
- ${f.bold("Cache Hits")}: ${f.cyan(i.index.cacheHits.toString())}
463
- ${f.bold("Cache Hit Rate")}: ${f.cyan(`${m}%`)}
464
- ${f.bold("Last Duration")}: ${f.yellow(p)}
465
- ${f.bold("Last Completed")}: ${f.yellow(a)}`,"cyan"),i.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${f.bold("Last Index Run Phases:")}`),i.index.lastRunPhases.forEach(h=>{let b=`${(h.durationMs/1e3).toFixed(2)}s`;console.log(` ${f.gray(h.phase.padEnd(20))} ${f.cyan(b)}`)})),console.log(""),te("Query Metrics",`${f.bold("Total Queries")}: ${f.cyan(i.query.count.toString())}
466
- ${f.bold("Avg Latency")}: ${f.yellow(d)}
467
- ${f.bold("Last Latency")}: ${f.yellow(u)}
468
- ${f.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?f.red(i.query.searchHistoryFailures.toString()):f.green("0")}`,"green")})}finally{await G(e)}}import Xs from"path";N();import Qs from"path";import Qa from"ignore";import Ks from"fs";import hn from"path";var va=50;function wt(s,e,t,n){let i={name:hn.basename(e)||e,type:"directory",path:e,children:[]};return s.forEach(r=>{let l=hn.relative(e,r.path).split(hn.sep),c=i;for(let a=0;a<l.length;a++){let p=l[a];if(n!==void 0&&a>=n)return;let d=a===l.length-1;if(n===1&&a===0&&d)return;let u=n!==void 0&&a===n-1&&!d,m=hn.join(e,...l.slice(0,a+1)),h=c.children?.find(b=>b.name===p);if(!h){if(c.children&&c.children.length>=va){c.children.find(g=>g.type==="truncated")||c.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}h={name:p,type:d?"file":"directory",path:m,children:d||u?void 0:[],summary:d?{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),c.children?.push(h)}c=h}}),i}import wa from"fast-glob";import li from"fs";import Ia from"ignore";import Ts from"path";var fn=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],Rs=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],ot={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},oe={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},ci={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},gn={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function pi(s,e=[]){let t=Ia(),n=Ts.join(s,".gitignore");return li.existsSync(n)&&t.add(li.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await wa(Rs,{cwd:s,absolute:!0,ignore:fn})).filter(o=>{let l=Ts.relative(s,o);return!t.ignores(l)}).map(o=>({path:o,mtime:li.statSync(o).mtimeMs}))}import Na from"@swc/core";import mi from"fs";function vs(s){let e=s.split(`
469
- `),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function J(s,e){for(let t=0;t<e.length;t++)if(e[t+1]>s||t===e.length-1)return t+1;return 1}function Y(s,e){return e.slice(0,s).toString("utf8").length}function ws(s,e,t){let n=s.start-e,i=s.end-e;return n<0||i>t.length?"":t.slice(n,i).toString("utf8")}function Is(s){let e=[],t=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=t.exec(s))!==null;)e.push({start:n.index,end:n.index+n[0].length,text:n[0]});return e}function Se(s,e,t){for(let n of e){if(n.start===s)return n.text;if(n.start>s&&n.start<s+50){let i=t.substring(s,n.start);if(/^\s*$/.test(i))return n.text}if(n.end<=s&&n.end>s-50){let i=t.substring(n.end,s);if(/^\s*$/.test(i))return n.text}}return""}function ks(s){if(!s)return"";let t=s.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
470
- `)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function yn(s,e,t){let n=s.toLowerCase(),i=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||i.startsWith("use")?"Hook":n.includes("models/")||i.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||i.endsWith("service")||i.endsWith("controller")||i.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||i.endsWith("repository")||i.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function It(s){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(s)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(s)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(s)||/\.query\s*\(|\.execute\s*\(/i.test(s)&&/db|database|client|pool/i.test(s))&&e.push("Database"),(/\bfs\./i.test(s)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(s)||/import\s+.*\bfs\b/.test(s))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(s)||/\bdocument\.cookie\b/.test(s))&&e.push("Browser Storage"),e}function Ce(s,e){if(!s)return"";let t=s.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,i=0,r=t.length;for(let o=0;o<t.length;o++){let l=t[o];if(l==="(")n++;else if(l===")")n--;else if(l==="<")i++;else if(l===">")i--;else if(l==="{"){if(n===0&&i===0){r=o;break}}else if(l==="; "&&n===0&&i===0){r=o;break}else if(l==="="&&t[o+1]===">"&&n===0&&i===0){r=o+2;break}}return t.substring(0,r).trim()}function Cs(s){let e=[];for(let t of s)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join("","")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function Ls(s,e,t,n,i,r,o,l){let c=[];for(let a of s){if(a.type==="ExportDeclaration"){let p=a.declaration,d=p.type,u="";d==="VariableDeclaration"?u=p.declarations.map(y=>y.id.value).join("",""):u=p.id?.value||p.identifier?.value||"anonymous";let m=Y(a.span.start-e,t),h=Y(a.span.end-e,t),b=Se(m,r,n),E=l(a.span),g=[];if(a.type==="ExportDeclaration"&&(d==="ClassDeclaration"||d==="ClassExpression")){let y=p.body||[];for(let S of y)if(S.type==="ClassMethod"||S.type==="ClassProperty"){let w=S.key.value;if(!w)continue;let C=Y(S.span.start-e,t),T=Y(S.span.end-e,t),I=l(S.span),x=Se(C,r,n);g.push({name:w,kind:S.type,signature:Ce(I,S.type),line:J(C,i),endLine:J(T,i),doc:x,classification:S.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(d==="FunctionDeclaration"&&p.body?.type==="BlockStatement")g=ui(p.body.stmts,e,t,n,i,r,l);else if(d==="VariableDeclaration"){for(let y of p.declarations)if(y.init&&(y.init.type==="ArrowFunctionExpression"||y.init.type==="FunctionExpression")&&y.init.body?.type==="BlockStatement"){g=ui(y.init.body.stmts,e,t,n,i,r,l);break}}c.push({name:u,kind:d,signature:Ce(E,d),line:J(m,i),endLine:J(h,i),doc:b,classification:yn(o,u,d),capabilities:JSON.stringify(It(E)),members:g})}if(a.type==="ExportNamedDeclaration"){for(let p of a.specifiers)if(p.type==="ExportSpecifier"){let d=Y(a.span.start-e,t),u=Y(a.span.end-e,t),m=Se(d,r,n);c.push({name:p.exported?.value||p.orig.value,kind:"ExportSpecifier",signature:`export { ${p.orig.value} }`,line:J(d,i),endLine:J(u,i),doc:m,classification:"Export mapping",capabilities:"[]"})}}if(a.type==="ExportDefaultDeclaration"){let p=Y(a.span.start-e,t),d=Y(a.span.end-e,t),u=Se(p,r,n),m=l(a.span),h=[];if(a.decl.type==="ClassExpression"||a.decl.type==="ClassDeclaration"){let b=a.decl.body||[];for(let E of b)if(E.type==="ClassMethod"||E.type==="ClassProperty"){let g=E.key.value;if(!g)continue;let y=Y(E.span.start-e,t),S=Y(E.span.end-e,t),w=l(E.span),C=Se(y,r,n);h.push({name:g,kind:E.type,signature:Ce(w,E.type),line:J(y,i),endLine:J(S,i),doc:C,classification:E.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(a.decl.type==="FunctionExpression"||a.decl.type==="FunctionDeclaration"||a.decl.type==="ArrowFunctionExpression")&&a.decl.body?.type==="BlockStatement"&&(h=ui(a.decl.body.stmts,e,t,n,i,r,l));c.push({name:"default",kind:"DefaultExport",signature:Ce(m,"DefaultExport"),line:J(p,i),endLine:J(d,i),doc:u,classification:"Default Export",capabilities:JSON.stringify(It(m)),members:h})}if(a.type==="ExportAllDeclaration"){let p=Y(a.span.start-e,t),d=Y(a.span.end-e,t),u=a.source.value,m=Se(p,r,n);c.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${u}"`,line:J(p,i),endLine:J(d,i),doc:m,classification:"Re-export",capabilities:"[]"})}}return c}function ui(s,e,t,n,i,r,o){let l=[];for(let c of s){if(c.type==="VariableDeclaration")for(let a of c.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(a.id);for(let u of p){let m=Y(u.span.start-e,t),h=Y(u.span.end-e,t),b=o(u.span),E=Se(m,r,n);l.push({name:u.name,kind:"VariableDeclaration",signature:Ce(b,"VariableDeclaration"),line:J(m,i),endLine:J(h,i),doc:E,classification:"Internal Variable",capabilities:"[]"})}}if(c.type==="FunctionDeclaration"){let a=c.identifier?.value||c.ident?.value||"anonymous",p=Y(c.span.start-e,t),d=Y(c.span.end-e,t),u=o(c.span),m=Se(p,r,n);l.push({name:a,kind:"FunctionDeclaration",signature:Ce(u,"FunctionDeclaration"),line:J(p,i),endLine:J(d,i),doc:m,classification:"Internal Function",capabilities:"[]"})}if(c.type==="ReturnStatement"&&c.argument?.type==="ObjectExpression")for(let a of c.argument.properties){let p="",d=a.span||a.key?.span||a.ident?.span;if(a.type==="KeyValueProperty"){let u=a.key;p=u?.value||u?.raw||(u?.type==="Identifier"?u.value:"")}else a.type==="MethodProperty"?p=a.key?.value||a.key?.raw||"":a.type==="ShorthandProperty"?p=a.ident?.value||"":a.type==="Identifier"&&(p=a.value||"");if(p&&d){let u=Y(d.start-e,t),m=Y(d.end-e,t),h=o(d),b=Se(u,r,n);l.push({name:p,kind:"ReturnProperty",signature:Ce(h,"ReturnProperty"),line:J(u,i),endLine:J(m,i),doc:b,classification:"Return Member",capabilities:"[]"})}}if(c.type==="ExpressionStatement"&&c.expression.type==="CallExpression"){let a=c.expression;if(a.callee.type==="MemberExpression"&&(a.callee.property?.value==="on"||a.callee.property?.value==="once")){let p=a.arguments[0]?.expression?.value,d=a.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),h=o(d.span);l.push({name:`on:${p}`,kind:d.type,signature:Ce(h,d.type),line:J(u,i),endLine:J(m,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}}}return l}function $s(s,e,t,n,i){let r=[];function o(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let c=ka(l);if(c){let a=Y(l.span.start-e,t);r.push({...c,line:J(a,n),snippet:i(l.span)})}}for(let c of Object.keys(l)){if(c==="span")continue;let a=l[c];Array.isArray(a)?a.forEach(o):typeof a=="object"&&o(a)}}}return s.forEach(o),r}function ka(s){let{callee:e,arguments:t}=s;if(!t||t.length===0)return null;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"};let i=["get","post","put","delete","patch"];if(i.includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value;if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}if(i.includes(n)&&t[0].expression.type==="StringLiteral"&&e.object.type==="Identifier"&&["axios","http","request"].includes(e.object.value))return{type:"api_route",name:t[0].expression.value,direction:"produce"}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function kt(s){let{classification:e,capabilities:t,exports:n,fileName:i}=s,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(h=>r[h]).filter(Boolean).join(" and "),c={Component:(h,b)=>{let E=b.find(y=>y.kind==="FunctionDeclaration"||y.kind==="ClassDeclaration")?.name,g=E?`React component: ${E}`:"React UI component";return h?`${g} with ${h}`:g},Hook:(h,b)=>{let E=b.find(y=>y.name.startsWith("use"))?.name,g=E?`Custom React hook: ${E}`:"Custom React hook";return h?`${g} for ${h}`:g},Service:(h,b)=>{let g=`Service layer: ${b[0]?.name||"Service"}`;return h?`${g} handling ${h}`:g},Repository:(h,b)=>`Data repository: ${b[0]?.name||"Repository"} for ${h||"data access"}`,"Type Definition":(h,b)=>`Type definitions: ${b.slice(0,3).map(g=>g.name).join("")}${b.length>3?"...":""}`,Model:(h,b)=>`Data model: ${b[0]?.name||"Model"}`,"HTTP Route":(h,b)=>{let E=b.filter(g=>g.classification==="Service Boundary");return E.length>0?`API endpoints: ${E.slice(0,3).map(g=>g.name).join("")}`:"API route handler"},"Micro IR (PHP)":(h,b)=>{let E=b.some(y=>y.classification==="Service Boundary"),g=b.find(y=>y.kind==="ClassDeclaration")?.name;return E?"PHP controller with API routes":g?`PHP class: ${g}`:"PHP module"},"Micro IR (Python)":(h,b)=>{let E=b.some(y=>y.classification==="Service Boundary"),g=b.find(y=>y.kind==="ClassDeclaration")?.name;return E?"Python API handler with routes":g?`Python class: ${g}`:"Python module"},"Micro IR (Go/TS) ":(h,b)=>{let E=b.some(y=>y.kind==="TypeDeclaration"),g=b.filter(y=>y.kind==="FunctionDeclaration");return E&&g.length>0?`Go package: types and ${g.length} function(s)`:E?"Go package: type definitions":g.length>0?`Go package: ${g[0].name} and ${g.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(h,b)=>{let E=b.find(S=>S.kind==="TraitDeclaration")?.name,g=b.find(S=>S.kind==="StructDeclaration")?.name,y=b.filter(S=>S.kind==="FunctionDeclaration");return E?h.includes("Rust trait")?`Rust module: trait ${E}`:`Rust module: ${E}`:g?`Rust module: struct ${g}`:y.length>0?`Rust module: ${y.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return i?`Module: ${i}`:"Module with no exports";let a=n.filter(h=>h.kind==="FunctionDeclaration"),p=n.filter(h=>h.kind==="ClassDeclaration"),d=n.filter(h=>h.kind==="TsInterfaceDeclaration"||h.kind==="TsTypeAliasDeclaration"),u=[];if(p.length>0&&u.push(`Class: ${p[0].name}`),a.length>0){let h=a.slice(0,2).map(b=>b.name).join("");u.push(`Functions: ${h}`)}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 Ns(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&Q(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&Q(n,e);for(let i in n){if(i==="span"||i==="comments"||i==="interpreter")continue;let r=n[i];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return s.forEach(n=>t(n)),Array.from(e)}function Q(s,e){if(s){if(s.type==="TsTypeAnnotation"){Q(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&As(s.typeName,e),s.typeParams&&Q(s.typeParams,e)),s.type==="TsArrayType"&&Q(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>Q(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>Q(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>Q(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>Q(t.typeAnnotation,e)),s.typeAnnotation&&Q(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&Q(t.constraint,e),t.default&&Q(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>Q(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&Q(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(Q(s.objectType,e),Q(s.indexType,e)),s.type==="TsConditionalType"&&(Q(s.checkType,e),Q(s.extendsType,e),Q(s.trueType,e),Q(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&Q(t.typeAnnotation,e)})}}function As(s,e){s.type==="TsQualifiedName"?(s.left&&As(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}import Os from"path";import di from"path";N();import Ps from"path";import Ca from"fs";import{fileURLToPath as La}from"url";import*as Ke from"web-tree-sitter";var Ru=Ps.dirname(La(import.meta.url)),Ms=_.child({module:"parser:tree-sitter"}),bn=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=Ke.Parser||Ke;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=an("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!Ca.existsSync(t))return Ms.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await Ke.Language.load(t);return this.languages.set(e,n),n}catch(n){return Ms.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`
462
+ `};function Si(i){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=i,s=Ke.join(e,".git","hooks"),r=[],o=[],c=[];if(!oe.existsSync(Ke.join(e,".git")))return c.push("Not a git repository"),{installed:r,skipped:o,errors:c};oe.existsSync(s)||oe.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=Ke.join(s,l),d=dn[l];if(!d){c.push(`No template found for hook: ${l}`);continue}try{if(oe.existsSync(p)){let u=oe.readFileSync(p,"utf-8");if(u.includes("liquid-shadow")||u.includes("mcp-liquid-shadow")){o.push(l),rt.info({hookName:l},"Hook already installed, skipping");continue}let m=`${p}.backup-${Date.now()}`;oe.copyFileSync(p,m),rt.info({hookName:l,backupPath:m},"Backed up existing hook")}oe.writeFileSync(p,d,{mode:493}),r.push(l),rt.info({hookName:l},"Installed git hook")}catch(u){c.push(`Failed to install ${l}: ${u}`),rt.error({hookName:l,err:u},"Failed to install hook")}}return{installed:r,skipped:o,errors:c}}function _i(i){let e=Ke.join(i,".git","hooks"),t=[],n=[];if(!oe.existsSync(e))return{removed:t,errors:n};let s=Object.keys(dn);for(let r of s){let o=Ke.join(e,r);try{if(oe.existsSync(o)){let c=oe.readFileSync(o,"utf-8");(c.includes("liquid-shadow")||c.includes("mcp-liquid-shadow"))&&(oe.unlinkSync(o),t.push(r),rt.info({hookName:r},"Removed git hook"))}}catch(c){n.push(`Failed to remove ${r}: ${c}`),rt.error({hookName:r,err:c},"Failed to remove hook")}}return{removed:t,errors:n}}function mn(i){let e=Ke.join(i,".git","hooks"),t=[],n=[];if(!oe.existsSync(e))return{installed:t,notInstalled:Object.keys(dn)};let s=Object.keys(dn);for(let r of s){let o=Ke.join(e,r);if(oe.existsSync(o)){let c=oe.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}}var cs=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}},De=new cs;function xi(){De.recordIndexStart()}function ls(){De.recordIndexCacheHit()}function Ti(i){De.recordIndexEnd(i)}function hn(i,e){De.recordIndexPhase(i,e)}function Ri(){De.clearIndexPhases()}function fn(){return De.recordQueryStart()}function ot(){De.recordSearchHistoryFailure()}function vi(){return De.getSnapshot()}async function wi(i){let e=$a.resolve(i);try{await B(async()=>{let t=C.getInstance(e),n=mn(e),s=vi(),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",d=s.query.avgLatencyMs?`${s.query.avgLatencyMs.toFixed(2)}ms`:"N/A",u=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";se("Performance Metrics",`${E.bold("Uptime")}: ${E.cyan(a)}
463
+ ${E.bold("Indexed")}: ${Ve(e)?E.green("Yes"):E.red("No")}
464
+ ${E.bold("Files")}: ${E.cyan(t.files.getCount().toString())}
465
+ ${E.bold("Exports")}: ${E.cyan(t.exports.getCount().toString())}
466
+ ${E.bold("Imports")}: ${E.cyan(t.imports.getCount().toString())}
467
+ ${E.bold("Last Indexed Commit")}: ${xt(e)?E.yellow(xt(e).substring(0,7)):E.red("None")}
468
+ ${E.bold("Git Hooks")}: ${n.installed?E.green("Installed"):E.yellow("Not Installed")}`,"blue"),console.log(""),se("Index Metrics",`${E.bold("Total Runs")}: ${E.cyan(s.index.runs.toString())}
469
+ ${E.bold("Cache Hits")}: ${E.cyan(s.index.cacheHits.toString())}
470
+ ${E.bold("Cache Hit Rate")}: ${E.cyan(`${m}%`)}
471
+ ${E.bold("Last Duration")}: ${E.yellow(p)}
472
+ ${E.bold("Last Completed")}: ${E.yellow(l)}`,"cyan"),s.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${E.bold("Last Index Run Phases:")}`),s.index.lastRunPhases.forEach(f=>{let h=`${(f.durationMs/1e3).toFixed(2)}s`;console.log(` ${E.gray(f.phase.padEnd(20))} ${E.cyan(h)}`)})),console.log(""),se("Query Metrics",`${E.bold("Total Queries")}: ${E.cyan(s.query.count.toString())}
473
+ ${E.bold("Avg Latency")}: ${E.yellow(d)}
474
+ ${E.bold("Last Latency")}: ${E.yellow(u)}
475
+ ${E.bold("Search History Failures")}: ${s.query.searchHistoryFailures>0?E.red(s.query.searchHistoryFailures.toString()):E.green("0")}`,"green")})}finally{await q(e)}}import nr from"path";P();import er from"path";import tc from"ignore";import tr from"fs";import gn from"path";var ka=50;function wt(i,e,t,n){let s={name:gn.basename(e)||e,type:"directory",path:e,children:[]};return i.forEach(r=>{let c=gn.relative(e,r.path).split(gn.sep),a=s;for(let l=0;l<c.length;l++){let p=c[l];if(n!==void 0&&l>=n)return;let d=l===c.length-1;if(n===1&&l===0&&d)return;let u=n!==void 0&&l===n-1&&!d,m=gn.join(e,...c.slice(0,l+1)),f=a.children?.find(h=>h.name===p);if(!f){if(a.children&&a.children.length>=ka){a.children.find(y=>y.type==="truncated")||a.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}f={name:p,type:d?"file":"directory",path:m,children:d||u?void 0:[],summary:d?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},f.summary&&(t==="structure"||t==="signatures")&&(delete f.summary.chunks,delete f.summary.imports),a.children?.push(f)}a=f}}),s}import La from"fast-glob";import us from"fs";import Na from"ignore";import Ci from"path";var yn=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],Ii=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],at={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},ae={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},ps={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},bn={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function ds(i,e=[]){let t=Na(),n=Ci.join(i,".gitignore");return us.existsSync(n)&&t.add(us.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await La(Ii,{cwd:i,absolute:!0,ignore:yn})).filter(o=>{let c=Ci.relative(i,o);return!t.ignores(c)}).map(o=>({path:o,mtime:us.statSync(o).mtimeMs}))}import Oa from"@swc/core";import fs from"fs";function $i(i){let e=i.split(`
476
+ `),t=[],n=0;for(let s of e)t.push(n),n+=s.length+1;return t}function J(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 Y(i,e){return e.slice(0,i).toString("utf8").length}function ki(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 Li(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 _e(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 Ni(i){if(!i)return"";let t=i.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
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`
471
478
  (function_definition name: (name) @name) @func
472
479
  (class_declaration name: (name) @name) @class
473
480
  (interface_declaration name: (name) @name) @interface
@@ -491,190 +498,229 @@ ${f.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?f.red(i.
491
498
  (trait_item name: (_type_identifier) @name) @trait
492
499
  (type_item name: (_type_identifier) @name) @type
493
500
  (use_declaration argument: (_) @name) @import
494
- `;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=Ps.extname(e).toLowerCase(),i=await this.getLanguage(n);if(!i||!this.parser)return[];this.parser.setLanguage(i);let r=this.parser.parse(t),o=t.split(`
495
- `),l=this.getQueries(n);if(!l)return[];let a=new Ke.Query(i,l).matches(r.rootNode),p=[];for(let d of a){let u=d.captures.find(b=>b.name==="name")?.node,m=d.captures[0].node,h=d.captures[0].name;if(u){let b=m.startPosition.row+1,E=m.endPosition.row+1,g=o[m.startPosition.row].trim();p.push({name:u.text,kind:this.mapKind(h,n),classification:this.mapClassification(h),signature:g,line:b,endLine:E,doc:"",capabilities:"{}"})}}return p}};var En=class{parse(e,t=!1){let n=[],i=[],r=e.split(`
496
- `),o="",l="",c=0,a=0,p=-1,d=-1,u=[],m=[],h=!1,b=t?"api":"",E="",g=/^namespace\s+([a-zA-Z0-9_\\]+);/,y=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,S=/^interface\s+([a-zA-Z0-9_]+)/,w=/^trait\s+([a-zA-Z0-9_]+)/,C=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,T=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,I=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,x=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,$=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let R=0;R<r.length;R++){let v=r[R].trim();if(!v)continue;let P=(v.match(/{/g)||[]).length,L=(v.match(/}/g)||[]).length,H=a;if(a+=P-L,l&&a<=d){let O=n.find(A=>A.name===l&&A.line===c);O&&(O.endLine=R+1),l="",d=-1}if(o&&a<=p){let O=n.find(A=>A.name===o&&(A.kind==="ClassDeclaration"||A.kind==="TraitDeclaration"||A.kind==="InterfaceDeclaration"));O&&(O.endLine=R+1),o="",p=-1}let B=v.match($);if(B&&(b=B[1]),v.includes("});")&&(b=""),v.startsWith("/**")){h=!0,m=[];continue}if(h){v.endsWith("*/")?h=!1:m.push(v.replace(/^\*\s?/,""));continue}let ne=v.match(I);if(ne){u.push(ne[1]);continue}let W=v.match(g);if(W){E=W[1]||"",u=[],m=[];continue}let D=v.match(y);if(D){o=D[1],p=a-P;let O={attributes:u};E&&(O.namespace=E),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:R+1,endLine:R+1,doc:m.join(`
497
- `).trim(),capabilities:JSON.stringify(O),members:[]}),u=[],m=[];continue}let M=v.match(S);if(M){let O=M[1];o=O,p=a-P,n.push({name:O,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${O}`,line:R+1,endLine:R+1,doc:m.join(`
498
- `).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let ce=v.match(w);if(ce){let O=ce[1];o=O,p=a-P,n.push({name:O,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${O}`,line:R+1,endLine:R+1,doc:m.join(`
499
- `).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let Et=v.match(C);if(Et){let O=Et[1],A=!!o;l=O,c=R+1,d=a-P;let Je=!1,Te={};for(let ie of u)ie.toLowerCase().includes("route")&&(Je=!0,Te={type:"route",method:"GET",path:"/"});let ve=m.join(`
500
- `).trim();if(Je){let ie=Te.path||"/";n.push({name:ie,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${O}`,line:R+1,endLine:R+1,doc:ve,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${O}`:O,...Te})}),i.push({type:"api_route",name:ie,direction:"consume",line:R+1,snippet:v})}n.push({name:O,kind:A?"MethodDeclaration":"FunctionDeclaration",classification:A?"Method":"Function",signature:`${A?o+":: ":""}${O}`,line:R+1,endLine:R+1,doc:ve,capabilities:JSON.stringify({attributes:u})}),u=[],m=[];continue}let Ge=v.match(T);if(Ge){let O=Ge[1]||"",A=Ge[2]||O.split("\\").pop()||"";n.push({name:A,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${O}`,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:O})}),u=[],m=[];continue}let nt=v.match(x);if(nt){let O=nt[1].toUpperCase(),A=nt[2];if(v.includes("Route::")||v.includes("router->")||v.includes("action")||v.includes(",")&&!v.includes("view(")){if(b){let Ae=b.startsWith("/")?b:`/${b}`,qn=A.startsWith("/")?A:`/${A}`;A=(Ae+qn).replace(/\/+/g,"/")}let Te=null,ve=v.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(ve)Te=`${ve[1]}@${ve[2]}`;else if(v.includes("::class")){let Ae=v.match(/([a-zA-Z0-9_]+)::class/);Ae&&(Te=Ae[1])}let ie=v;!v.endsWith(");")&&R+1<r.length&&(ie+=" "+r[R+1].trim(),!ie.endsWith(");")&&R+2<r.length&&(ie+=" "+r[R+2].trim())),n.push({name:A,kind:"HTTP Route",classification:"Service Boundary",signature:ie,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"route",method:O,path:A,handler:Te})}),i.push({type:"api_route",name:A,direction:"consume",line:R+1,snippet:ie,method:O,url:A}),m=[];continue}}let jt=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,qe=v.match(jt);if(qe){let O=(qe[1]||qe[3]).toUpperCase(),A=(qe[2]||qe[4]).trim();(A.startsWith("'")&&A.endsWith("'")||A.startsWith('"')&&A.endsWith('"'))&&(A=A.substring(1,A.length-1)),i.push({type:"api_route",name:A,direction:"produce",line:R+1,snippet:v,method:O,url:A})}!v.startsWith("#[")&&!v.startsWith("//")&&!v.startsWith("*")&&!h&&(u=[],m=[])}return{nodes:n,events:i}}};var Sn=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],i=e.split(`
501
- `),r=[{indent:-1,name:"root",type:"root"}],o=[],l=/^class\s+([a-zA-Z0-9_]+)/,c=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,a=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,p=/^@(.*)/;function d(g){return g.trim().split(/[.(]/)[0]?.trim()||g}function u(g){let y=g.decorators.map(w=>d(w.raw)),S={decorators:g.decorators,decoratorNames:y};return g.async===!0&&(S.async=!0),JSON.stringify(S)}let m=!1,h="",b=[],E=[];for(let g=0;g<i.length;g++){let y=i[g],S=y.trim();if(!S||S.startsWith("#"))continue;let w=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,C=S.match(w);if(C&&(this.currentRoutePrefix=C[2]),m){if(S.endsWith(h)||S.includes(h)){m=!1;let D=S.replace(h,"").trim();D&&b.push(D);let M=r[r.length-1];M.node&&(M.node.doc=b.join(`
502
- `).trim()),b=[]}else b.push(S);continue}let T=y.search(/\S/),I=y.trim(),x=I.match(/^(['"]{3})/);if(x){let D=x[1],M=r[r.length-1];if(M.node&&!M.node.doc){if(I.substring(3).includes(D)){let ce=I.replace(new RegExp(D,"g"),"").trim();M.node.doc=ce}else{m=!0,h=D;let ce=I.substring(3).trim();ce&&b.push(ce)}continue}}for(;r.length>1&&r[r.length-1].indent>=T;)r.pop();let $=r[r.length-1],R=I.match(p);if(R){o.push({raw:R[1].trim(),line:g+1});continue}let v=I.match(l);if(v){let D=v[1],M={name:D,kind:"ClassDeclaration",classification:"Class",signature:`class ${D}`,line:g+1,endLine:g+1,doc:"",capabilities:u({decorators:o}),members:[]};E.push(M),$.node?($.node.members||($.node.members=[]),$.node.members.push(M)):t.push(M),r.push({indent:T,name:D,type:"class",node:M}),o=[];continue}let P=I.match(c);if(P){let D=!!P[1],M=P[1]||P[2],ce=$.type==="class",Et=!1,Ge={};for(let A of o)if(A.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){Et=!0;let Te=["get","post","put","delete","patch"].find(Ae=>A.raw.toLowerCase().includes(`.${Ae}`))?.toUpperCase()||"GET",ve=A.raw.match(/['"]([^'"]+)['"]/),ie=ve?ve[1]:"/";if(this.currentRoutePrefix){let Ae=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,qn=ie.startsWith("/")?ie:`/${ie}`;ie=Ae+qn}Ge={type:"route",method:Te,path:ie}}if(Et){let A=Ge.path||"",Je={name:A||M,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${M}`,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({handler:ce?`${$.name}.${M}`:M,async:D,...Ge})};E.push(Je),t.push(Je),n.push({type:"api_route",name:A,direction:"consume",line:g+1,snippet:I})}let nt=o.some(A=>A.raw==="staticmethod"),jt=o.some(A=>A.raw==="classmethod"),qe=`${D?"async ":""}${ce?(nt?"@staticmethod ":jt?"@classmethod ":"")+$.name+".":""}${M}`,O={name:M,kind:D&&ce?"AsyncMethodDeclaration":D?"AsyncFunctionDeclaration":ce?"MethodDeclaration":"FunctionDeclaration",classification:ce?nt||jt?"Static Method":"Method":"Function",signature:qe,line:g+1,endLine:g+1,doc:"",capabilities:u({decorators:o,async:D}),members:[]};E.push(O),$.node?($.node.members||($.node.members=[]),$.node.members.push(O)):t.push(O),r.push({indent:T,name:M,type:"function",node:O}),o=[];continue}let L=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,H=I.match(L);if(H){let D=H[1].replace(/^\^/,""),M={name:D,kind:"HTTP Route",classification:"Service Boundary",signature:I.trim(),line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:D})};E.push(M),t.push(M),n.push({type:"api_route",name:D,direction:"consume",line:g+1,snippet:I});continue}let B=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,ne=I.match(B);if(ne){let D=ne[1].toUpperCase(),M=ne[2].trim();(M.startsWith("'")&&M.endsWith("'")||M.startsWith('"')&&M.endsWith('"'))&&(M=M.substring(1,M.length-1)),n.push({type:"api_route",name:M,direction:"produce",line:g+1,snippet:I,method:D,url:M})}let W=I.match(a);if(W){let D=W[1]||W[2],M={name:D,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${D}`,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"import",module:D})};E.push(M),t.push(M),o=[];continue}o=[],$.node&&($.node.endLine=g+1)}return{nodes:E,events:n}}};var Ds=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function",signature:s[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:s=>({name:s[1],kind:"MethodDeclaration",classification:"Method",signature:s[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:s=>({name:s[1],kind:"ImportSpecifier",classification:"Dependency",signature:s[0],meta:{type:"import",path:s[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function",signature:s[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"StructDeclaration",classification:"Class",signature:s[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"EnumDeclaration",classification:"Class",signature:s[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"TraitDeclaration",classification:"Class",signature:s[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:s=>({name:s[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:s[0],meta:{type:"import",path:s[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:s=>({name:s[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:s=>({name:s[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:s[1]}})}]}];function $a(s,e){let t=[];if(s===".go"&&e.some(n=>n.kind==="TypeDeclaration")&&t.push("Go type"),s===".rs"&&(e.some(n=>n.kind==="TraitDeclaration")&&t.push("Rust trait"),e.some(n=>n.kind==="StructDeclaration")&&t.push("Rust struct"),e.some(n=>n.kind==="EnumDeclaration")&&t.push("Rust enum")),s===".py"){for(let n of e)if(n.capabilities)try{if(JSON.parse(n.capabilities).decoratorNames?.length){t.push("Python decorators");break}}catch{}e.some(n=>n.kind==="AsyncFunctionDeclaration"||n.kind==="AsyncMethodDeclaration")&&t.push("Async")}return t}var _n=class{phpParser=new En;pythonParser=new Sn;treeSitterParser=new bn;supports(e){return Ds.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=di.extname(e).toLowerCase(),i=[],r=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let c=this.pythonParser.parse(t);i=c.nodes,r=c.events}else if(n===".php"){let c=e.toLowerCase().endsWith("api.php"),a=this.phpParser.parse(t,c);i=a.nodes,r=a.events}else try{i=await this.treeSitterParser.parse(e,t)}catch{}if(i.length>0){let c=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",a=i.filter(m=>m.classification!=="Dependency"),p=i.filter(m=>m.classification==="Dependency"),d=$a(n,i),u=kt({classification:c,capabilities:d,exports:a.map(m=>({name:m.name,kind:m.kind,classification:m.classification})),fileName:di.basename(e)});return{exports:a,imports:p.map(m=>({module:m.name,name:m.name,kind:m.kind,classification:m.classification})),events:r,classification:c,summary:u||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Ds.find(c=>c.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};for(let c of o.rules){c.regex.lastIndex=0;let a;for(;(a=c.regex.exec(t))!==null;){let p=c.onMatch(a),d=t.substring(0,a.index).split(`
503
- `).length;i.push({name:p.name||"anonymous",kind:p.kind||"Unknown",classification:p.classification||"Other",signature:p.signature||a[0],line:d,endLine:d,doc:"",capabilities:JSON.stringify(p.meta||{})})}}let l=kt({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:i.map(c=>({name:c.name,kind:c.kind,classification:c.classification})),fileName:di.basename(e)});return{exports:i,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:l||"Module",parseStatus:i.length>0?"success":"partial"}}};N();var hi=new _n;async function Ct(s){let e=Os.extname(s);if(hi.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=mi.readFileSync(s,"utf-8");return await hi.parse(s,r)}catch(r){return _.error({filePath:s,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:r.message}}let t;try{t=mi.readFileSync(s)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),i=vs(n);try{let r=s.endsWith(".tsx"),o=Na.parseSync(n,{syntax:"typescript",tsx:r,decorators:!0,comments:!0}),l=o.span.start,c=Is(n),a=g=>ws(g,l,t),p=Cs(o.body),d=Ns(o.body);d.length>0&&_.debug({filePath:s,count:d.length},"Extracted type references"),d.forEach(g=>{p.push({module:"__type_reference__",name:g})});let u=Ls(o.body,l,t,n,i,c,s,a),m=$s(o.body,l,t,i,a),h=yn(s,"","Module"),b=c.length>0&&c[0].start===0?c[0].text:u.find(g=>g.doc)?.doc||"",E=ks(b);if(!E&&u.length>0){let g=It(n);E=kt({classification:h,capabilities:g,exports:u.map(y=>({name:y.name,kind:y.kind,classification:y.classification})),fileName:Os.basename(s)})}return{exports:u,imports:p,events:m,classification:h,summary:E,parseStatus:"success"}}catch(r){_.warn({filePath:s,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=mi.readFileSync(s,"utf-8"),l=await hi.parse(s,o);return{...l,classification:l.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return _.error({filePath:s,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}N();import Vs from"p-limit";Ve();import Ja from"path";import yi from"fs";import Ya from"os";import he from"path";import ct from"fs";import{loadConfig as Ma,createMatchPath as Pa}from"tsconfig-paths";import Oe from"path";import Lt from"fs";var Fe=class extends Error{constructor(t,n,i){super(n);this.code=t;this.cause=i;this.name="FileSystemError"}};function Fs(s){let e;try{e=Lt.statSync(s).isDirectory()?s:Oe.dirname(s)}catch(t){throw t.code==="ENOENT"?new Fe("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new Fe("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new Fe("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==Oe.dirname(e);){let t=Oe.join(e,"tsconfig.json");if(Lt.existsSync(t))return e;e=Oe.dirname(e)}return null}function Hs(s){let e;try{e=Lt.statSync(s).isDirectory()?s:Oe.dirname(s)}catch(t){throw t.code==="ENOENT"?new Fe("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new Fe("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new Fe("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==Oe.dirname(e);){let t=Oe.join(e,"package.json");if(Lt.existsSync(t))try{if(JSON.parse(Lt.readFileSync(t,"utf8")).workspaces)return e}catch{}e=Oe.dirname(e)}return null}import at from"path";import Xe from"fs";function Ws(s,e){let t=new Map,n=e.workspaces||[];for(let i of n){let r=i.replace("/*",""),o=at.join(s,r);if(!Xe.existsSync(o))continue;let l=Xe.readdirSync(o);for(let c of l){let a=at.join(o,c,"package.json");if(Xe.existsSync(a))try{let p=JSON.parse(Xe.readFileSync(a,"utf8"));p.name&&t.set(p.name,{name:p.name,path:at.dirname(a),main:p.main||"dist/index.js"})}catch{}}}return t}function Us(s){let e=new Map;try{let t=JSON.parse(Xe.readFileSync(s,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[i,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),l=at.dirname(s),c=at.resolve(l,o),a=at.join(c,"package.json");if(Xe.existsSync(a))try{let p=JSON.parse(Xe.readFileSync(a,"utf8"));e.set(i,{name:i,path:c,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import js from"path";import me from"fs";var Aa=[".ts",".tsx",".d.ts",".js",".jsx"];function He(s){let e=js.extname(s);if(e===".js"||e===".jsx"){let t=s.slice(0,-e.length),n=e===".jsx"?[".tsx",".ts"]:[".ts",".tsx"];for(let i of n){let r=t+i;if(me.existsSync(r)&&me.statSync(r).isFile())return r}if(me.existsSync(s)&&me.statSync(s).isFile())return s}if(me.existsSync(s)&&me.statSync(s).isFile())return s;for(let t of Aa){let n=s+t;if(me.existsSync(n)&&me.statSync(n).isFile())return n}if(me.existsSync(s)&&me.statSync(s).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=js.join(s,"index"+t);if(me.existsSync(n))return n}return""}var Rn=new Map;function xn(s){let e=Fs(s);if(!e)return null;if(Rn.has(e))return Rn.get(e)||null;let t=Ma(e);if(t.resultType==="failed")return Rn.set(e,null),null;let n=t,i=n.absoluteBaseUrl;!i&&n.paths&&Object.keys(n.paths).length>0&&(i=n.configFileAbsolutePath?he.dirname(n.configFileAbsolutePath):e);let r=Pa(i,n.paths,n.mainFields,n.addMatchAll),o=Hs(e),l=new Map;if(o){let d=he.join(o,"package.json");if(ct.existsSync(d))try{let u=JSON.parse(ct.readFileSync(d,"utf8"));l=Ws(o,u)}catch{}}let c=he.join(e,"package.json");ct.existsSync(c)&&Us(c).forEach((u,m)=>l.set(m,u));let a={baseUrl:i||"",paths:n.paths,matchPath:r,workspacePackages:l,imports:new Map},p=he.join(e,"package.json");if(ct.existsSync(p))try{let d=JSON.parse(ct.readFileSync(p,"utf8"));if(d.imports){for(let[u,m]of Object.entries(d.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"&&a.imports.set(u,h)}}}catch{}return Rn.set(e,a),a}function $t(s,e,t){if(!s)return"";if(s.includes(".")&&!s.startsWith(".")&&!s.startsWith("/")&&!s.endsWith(".js")&&!s.endsWith(".ts")&&!s.endsWith(".json")){let i=s.split(".")[0];if(i&&i!==s){let r=$t(i,e,t);if(r)return r}}if(s.startsWith(".")){let i=he.dirname(e),r=he.resolve(i,s);return He(r)}let n=xn(e);if(n){let i=n.matchPath(s);if(i)return He(i);if(!s.startsWith("@")||s.startsWith("@/")){let o=he.resolve(n.baseUrl,s),l=He(o);if(l)return l}for(let[o,l]of n.imports.entries())if(o.includes("*")){let c="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",a=new RegExp(c),p=s.match(a);if(p){let d=p[1],u=l.replace("*",d),m=he.resolve(n.baseUrl,u);return He(m)}}else if(o===s){let c=he.resolve(n.baseUrl,l);return He(c)}let r=n.workspacePackages.get(s);if(r){let o=he.join(r.path,"src/index.ts");if(ct.existsSync(o))return o;let l=he.join(r.path,r.main),c=He(l);if(c)return c}}return""}import Da from"fs";import Oa from"path";import zs from"js-yaml";function Bs(s){let e=Oa.basename(s),t=Da.readFileSync(s,"utf8"),n=[];if(e.endsWith(".prisma"))return Ua(t,s);if(e.endsWith(".graphql")||e.endsWith(".gql"))return ja(t,s);let i="Configuration";return e==="lerna.json"?za(t,s):e==="turbo.json"?Ga(t,s):e==="pnpm-workspace.yaml"?qa(t,s):(e.includes("Dockerfile")?(i="Infrastructure (Docker) ",Fa(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(i="Infrastructure (YAML) ",Ha(t,n)):e.startsWith(".env")?(i="Configuration (Env) ",Wa(t,n)):e==="package.json"&&(i="Project Manifest",Ba(t,n)),{configs:n,classification:i})}function Fa(s,e){let t=s.split(`
504
- `);for(let n of t){let i=n.trim();if(i.startsWith("FROM "))e.push({key:"base_image",value:i.substring(5).trim(),kind:"Image"});else if(i.startsWith("EXPOSE "))e.push({key:"port",value:i.substring(7).trim(),kind:"Port"});else if(i.startsWith("ENV ")){let r=i.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],l=r.slice(1).join("= ").trim()||"undefined",c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function Ha(s,e){try{let t=zs.load(s);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[i,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${i}`,value:i,kind:"Service"}),o.image&&e.push({key:`service:${i}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(l=>{e.push({key:`service:${i}:port`,value:String(l),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(l=>{let[c,...a]=l.split("= ");c&&a.length>0&&e.push({key:`service:${i}:env:${c}`,value:a.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[l,c]of Object.entries(o.environment))e.push({key:`service:${i}:env:${l}`,value:String(c),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(l=>{e.push({key:`service:${i}:depends_on`,value:l,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let l of Object.keys(o.depends_on))e.push({key:`service:${i}:depends_on`,value:l,kind:"Dependency"})}let n=(i,r="")=>{if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,l]of Object.entries(i)){let c=r?`${r}.${o}`:o;if(t.services&&(c.startsWith("services.")||c==="services")){l&&typeof l=="object"&&!Array.isArray(l)&&n(l,c);continue}if(l&&typeof l=="object"&&!Array.isArray(l))n(l,c);else{let a=String(l),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:c,value:a.length>100?a.substring(0,97)+"...":a,kind:p})}}};n(t)}catch{let n=s.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(i=>{let r=i.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function Wa(s,e){let t=s.split(`
505
- `);for(let n of t){let i=n.trim();if(i&&!i.startsWith("#")){let r=i.split("=");if(r[0]){let o=r[0].trim(),l=r.slice(1).join("=");l=l.trim().replace(/^['"](.*)['"]$/,"$1");let c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function Ua(s,e){let t=[],n="Contract (Prisma) ",i=/^model\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(s))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let l=/provider\s*=\s*"([^"]+)"/,c=s.match(l);return c&&t.push({key:"datasource_provider",value:c[1],kind:"Database Config"}),{classification:n,configs:t}}function ja(s,e){let t=[],n="Contract (GraphQL) ",i=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;){let o=r[0],l="GraphQL Type";o.startsWith("input")&&(l="GraphQL Input"),o.startsWith("interface")&&(l="GraphQL Interface"),o.startsWith("enum")&&(l="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:l})}return{classification:n,configs:t}}function Ba(s,e){try{let t=JSON.parse(s);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"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(l=>o.includes(l))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},i=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(i.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Service"})}}catch{}}function za(s,e){let t=[],n="Monorepo (Lerna) ";try{let i=JSON.parse(s);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),i.version&&t.push({key:"lerna_version",value:i.version,kind:"Monorepo"}),i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),i.npmClient&&t.push({key:"npm_client",value:i.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n}}function Ga(s,e){let t=[],n="Monorepo (Turborepo) ";try{let i=JSON.parse(s);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),i.pipeline)for(let r of Object.keys(i.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=i.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(i.tasks)for(let r of Object.keys(i.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n}}function qa(s,e){let t=[],n="Monorepo (pnpm) ";try{let i=zs.load(s);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),i&&i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n}}F();import{execSync as Ze}from"child_process";import fi from"path";import gi from"fs";function se(s){try{if(!gi.existsSync(fi.join(s,".git")))return null;let e=Ze("git rev-parse --abbrev-ref HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return e==="HEAD"?Ze("git rev-parse --short HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():e.replace(/[\/\\:*"<>|?]/g,"-")}catch{return null}}function fe(s){try{return gi.existsSync(fi.join(s,".git"))?Ze("git rev-parse HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function Gs(s,e=50){try{let t=Ze(`git rev-list --max-count=${e} HEAD`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return t?t.split(`
506
- `):[]}catch{return[]}}function qs(s,e,t){try{return Ze(`git merge-tree --write-tree ${e} ${t}`,{cwd:s,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}function Js(s,e){try{if(!gi.existsSync(fi.join(s,".git")))return!0;let t=fe(s);return!t||e&&e!==t&&Ze(`git diff --name-only ${e} ${t}`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()?!0:Ze("git status --porcelain",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim().length>0}catch{return!0}}F();N();import{execSync as Ys}from"child_process";var et=_.child({module:"nano-repair"}),_e=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:i}=k.getInstance(e);this.intentLogs=t,this.exports=n,this.missions=i,this.repoPath=e}detectAndRepairShifts(){let e=this.intentLogs.findRepairableOrphans();if(e.length===0)return{repaired:0,failed:0};et.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let i of e){let r=this.exports.findByNameAndFile(i.symbol_name,i.file_path);if(r.length>0){let l=r.find(c=>c.signature===i.signature)||r[0];this.intentLogs.update(i.id,{symbol_id:l.id}),et.info({logId:i.id,symbol:i.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(i.symbol_name);if(o.length>0){let l=o.filter(c=>c.file_path!==i.file_path);if(l.length>0){let c=l.find(a=>a.signature===i.signature)||l[0];this.intentLogs.update(i.id,{symbol_id:c.id,file_path:c.file_path}),et.info({logId:i.id,symbol:i.symbol_name,oldPath:i.file_path,newPath:c.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&et.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(){let e="HEAD";try{e=Ys("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"),et.info({missionId:o.id,branch:o.git_branch,current:e},"Context Pivot: Suspended mission"),n++);this.missions.resumeByBranch(e);let i=[];try{i=Ys(`git branch --merged "${e}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
507
- `).map(l=>l.trim().replace(/^\* /,"")).filter(l=>l&&l!==e)}catch{}let r=0;if(i.length>0){let o=this.missions.findMergedMissions(e,i);for(let l of o)this.missions.updateStatus(l.id,"completed"),et.info({missionId:l.id,branch:l.git_branch},"Merge Sentinel: Auto-completed mission"),r++}return(n>0||r>0)&&et.info({suspended:n,completed:r},"Git-Native Lifecycle Sync complete"),{suspended:n,resumed:-1,completed:r}}};var Gd=Ya.cpus().length||4,Va=gn.DEFAULT_CONCURRENCY;async function j(s,e=Va,t=!1,n=!0,i){let r=k.getInstance(s),o=r.files.database,l=we(s),c=l.concurrency??e;if(bs(),!t&&Ye(s)){let g=xt(s),y=fe(s);if(g&&!Js(s,g))return ai(),_.debug({repoPath:s,commit:y},"Index is current, skipping re-index (fast-path)"),o}xn(s);let a=r.files.findAll(),p=new Map(a.map(g=>[g.path,{mtime:g.mtime,hash:g.content_hash}])),d=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let u=await pi(s,l.ignore),m=new Map(u.map(g=>[g.path,g.mtime])),h=a.filter(g=>!m.has(g.path)).map(g=>g.path),b=a.length===0,E=[];if(t||b)E.push(...u);else{let g=u.filter(C=>{let T=p.get(C.path);return!T||T.mtime!==C.mtime}),y=Vs(c*4),S=g.map(C=>y(async()=>{let T=p.get(C.path);if(!T||!T.hash)return C;try{let I=await yi.promises.readFile(C.path,"utf8");return Ui(I,T.hash)?C:(r.files.updateMtime(C.path,C.mtime),null)}catch{return null}})),w=await Promise.all(S);E.push(...w.filter(C=>C!==null))}if(h.length===0&&E.length===0){if(ai(),b){let g=fe(s);Kn(s,g||void 0)}return o}if(b?_.info({totalFiles:u.length},"Starting initial repository indexing..."):_.info({toDelete:h.length,toProcess:E.length},"Syncing repository updates..."),h.length>0&&r.files.deletePaths(h),E.length>0){Ss(),n?ln(!0):ln(!1);let g=Vs(c),y=0,S=E.length,w=E.map($=>g(async()=>{try{let R=Ja.basename($.path);if(/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/.test(R)){let P=await Ct($.path),L=yi.readFileSync($.path,"utf8");return y++,(y%50===0||y===S)&&_.info({completed:y,total:S},"Parsing files..."),i?.({phase:"parse",current:y,total:S,message:`Parsing ${R}`}),{meta:$,...P,content:L,embedding:null,kind:"code"}}else{let P=Bs($.path),L=yi.readFileSync($.path,"utf8");return y++,(y%50===0||y===S)&&_.info({completed:y,total:S},"Parsing configs..."),i?.({phase:"parse",current:y,total:S,message:`Parsing config ${R}`}),{meta:$,...P,content:L,embedding:null,kind:"config"}}}catch(R){return y++,_.error({path:$.path,error:R},"Failed to parse file"),{meta:$,exports:[],imports:[],content:"",kind:"error"}}}));_.info({total:S},"Phase 1: Parsing all files...");let C=Date.now(),T=(await Promise.all(w)).filter(Boolean),I=Date.now()-C;if(dn("parse",I),_.info({count:T.length,time:`${(I/1e3).toFixed(1)}s`},"Phase 1 complete"),n){_.info("Phase 2: Generating file semantic embeddings..."),i?.({phase:"embed",current:0,total:T.length,message:"Generating embeddings..."});let $=Date.now(),R=[];if(T.forEach((P,L)=>{"summary"in P&&P.summary&&R.push({fileIdx:L,text:P.summary})}),R.length>0){_.info({count:R.length}," \u2192 Generating file summary embeddings...");let P=R.map(H=>H.text),L=await si(P,128);R.forEach((H,B)=>{T[H.fileIdx].embedding=L[B]}),_.info({count:R.length}," \u2713 File summaries complete")}let v=Date.now()-$;dn("embed",v),_.info({time:`${(v/1e3).toFixed(1)}s`},"Phase 2 complete")}i?.({phase:"persist",current:0,total:T.length,message:"Saving to database..."});let x=Date.now();r.files.batchSaveIndexResults(T,s,Qn,$t),dn("persist",Date.now()-x)}if(b||E.length>0){let g=fe(s);Kn(s,g||void 0)}return(E.length>0||h.length>0)&&new _e(s).detectAndRepairShifts(),Es(Date.now()-d),i?.({phase:"complete",current:E.length,total:E.length,message:"Indexing complete"}),o}F();async function Nt(s,e=gn.DEFAULT_CONCURRENCY,t="detailed",n,i){_.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await j(s,e);let{files:r,exports:o,imports:l}=k.getInstance(s),c=n?r.findInSubPath(s,n):r.findAll(),a=we(s),p=Qa(),d=Qs.join(s,".gitignore");if(Ks.existsSync(d)&&p.add(Ks.readFileSync(d,"utf8")),a.ignore&&a.ignore.length>0&&p.add(a.ignore),p.add(fn),c=c.filter(y=>{let S=Qs.relative(s,y.path);return!p.ignores(S)}),_.info({count:c.length},"Fetching data from DB..."),t==="lite"){let y=c.map(S=>({path:S.path,mtime:S.mtime}));return wt(y,s,t,i)}if(t==="summaries"){let y=c.map(S=>({path:S.path,mtime:S.mtime,classification:S.classification||void 0,summary:S.summary||void 0}));return wt(y,s,t,i)}let u=c.map(y=>y.path),m=o.findByFiles(u),h=t==="detailed"?l.findByFiles(u):[],b=new Map;for(let y of m){let S=b.get(y.file_path)||[];S.push(y),b.set(y.file_path,S)}let E=new Map;for(let y of h){let S=E.get(y.file_path)||[];S.push(y),E.set(y.file_path,S)}let g=c.map(y=>{let w=(b.get(y.path)||[]).map(T=>({name:T.name,kind:T.kind,signature:T.signature,line:T.start_line}));t==="structure"?w=w.map(T=>({name:T.name,kind:T.kind,line:T.line})):t==="signatures"&&(w=w.map(T=>({name:T.name,kind:T.kind,signature:T.signature,line:T.line})));let C=[];return t==="detailed"&&(C=(E.get(y.path)||[]).map(I=>({module:I.module_specifier,resolved_path:I.resolved_path}))),{path:y.path,mtime:y.mtime,classification:y.classification||void 0,summary:y.summary||void 0,exports:w,imports:C.length>0?C:void 0,chunks:[]}});return _.info({count:g.length},"Building hierarchical project tree..."),wt(g,s,t,i)}async function Zs(s,e){let t=Xs.resolve(s),n=parseInt(e.depth);try{await U(async()=>{let i=await Nt(t,5,"lite",e.subPath,n);console.log(""),console.log(` ${f.bold("Repository Structure: ")} ${f.cyan(Xs.basename(t))}`),e.subPath&&console.log(` ${f.bold("Sub-path: ")} ${f.dim(e.subPath)}`),console.log("");let r=o=>{let l=o.type==="truncated",c=o.type==="directory"&&o.children===void 0;return{name:o.name,color:o.type==="directory"?"blue":l?"gray":"white",info:o.type==="file"?o.summary?.classification:c?"truncated":void 0,children:o.children?.map(r)}};Zn([r(i)]),console.log(""),n<10&&(console.log(f.gray(` (Showing depth ${n}. Use --depth to see more)`)),console.log(""))})}finally{await G(t)}}import tr from"path";import Ka from"fs";N();import X from"path";import bi from"fs";var Tn=_.child({module:"path-resolver"}),At=class{repoPath;constructor(e){this.repoPath=X.isAbsolute(e)?X.normalize(e):X.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw Tn.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(X.isAbsolute(e)?t=X.normalize(e):t=X.join(this.repoPath,e),t=X.normalize(t),!this.isWithinRoot(t))throw Tn.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 bi.existsSync(t)?t:(Tn.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return Tn.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=X.resolve(e),n=X.resolve(this.repoPath),i=X.relative(n,t);if(i.startsWith("..")||X.isAbsolute(i))return!1;if(bi.existsSync(t)){let o=bi.realpathSync(t),l=X.relative(n,o);if(l.startsWith("..")||X.isAbsolute(l))return!1}return!0}catch{return!1}}getRelative(e){let t=X.normalize(e);return X.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return X.normalize(e)}static isPathWithinRoot(e,t){let n=X.resolve(e),i=X.resolve(t),r=X.relative(n,i);return r===""||!r.startsWith("..")&&!X.isAbsolute(r)}};function er(s){return new At(s)}async function nr(s,e){let t=tr.resolve(s);await U(async()=>{if(le("MCP Liquid Shadow"),console.log(` ${f.bold("Target")}: ${f.cyan(t)}`),console.log(` ${f.bold("Mode")}: ${e.output?f.magenta("File Export"):f.green("Indexing")}`),console.log(""),!e.output){let i=ue();i.start("Indexing repository...");let r="",o=l=>{if(l.phase!==r){r=l.phase;let c={scan:"Scanning",parse:"Parsing",embed:"Generating embeddings",persist:"Saving to database",complete:"Complete"}[l.phase]||l.phase;i.message(`${c}...`)}if(l.total>0&&l.current>0){let c=Math.round(l.current/l.total*100);i.message(`${r==="parse"?"Parsing":"Processing"}: ${l.current}/${l.total} (${c}%)`)}};try{await j(t,void 0,e.force,e.deep??!0,o),i.message("Running symbol healing...");let c=new _e(t).detectAndRepairShifts();i.stop("Indexing complete!"),Rt("Ready to serve AI requests.")}catch(l){throw i.stop(`Indexing failed: ${l.message}`),l}finally{await G(t)}return}let n=ue();n.start(`Generating export (${f.bold(e.level)})...`);try{let i=await Nt(t,5,e.level,e.subPath),r=tr.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!At.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");Ka.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Export saved to ${f.bold(f.cyan(r))}`),Rt("Export complete.")}catch(i){throw n.stop(`Export failed: ${i.message}`),i}finally{await G(t)}})}import{performance as ir}from"perf_hooks";import Xa from"path";F();async function sr(s){let e=Xa.resolve(s);await U(async()=>{console.log(`
508
- ${f.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${f.gray("Repository: ")} ${e}`),console.log(` ${f.yellow("Starting fresh index (DB deleted)...")}
509
- `);let t=ir.now();try{await j(e,10,!0);let n=ir.now()-t,i=k.getInstance(e),r=i.files.getCount(),o=i.exports.getCount(),l=i.exports.getWithEmbeddingsCount();te("Benchmark Results",`${f.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
510
- ${f.bold("Files Processed")}: ${f.cyan(r.toString())}
511
- ${f.bold("Symbols Extracted")}: ${f.cyan(o.toString())}
512
- ${f.bold("Symbols Embedded")}: ${f.cyan(l.toString())} (${(l/o*100).toFixed(1)}%)
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=Hi.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(`
502
+ `),c=this.getQueries(n);if(!c)return[];let l=new Xe.Query(s,c).matches(r.rootNode),p=[];for(let d of l){let u=d.captures.find(h=>h.name==="name")?.node,m=d.captures[0].node,f=d.captures[0].name;if(u){let h=m.startPosition.row+1,b=m.endPosition.row+1,y=o[m.startPosition.row].trim();p.push({name:u.text,kind:this.mapKind(f,n),classification:this.mapClassification(f),signature:y,line:h,endLine:b,doc:"",capabilities:"{}"})}}return p}};var _n=class{parse(e,t=!1){let n=[],s=[],r=e.split(`
503
+ `),o="",c="",a=0,l=0,p=-1,d=-1,u=[],m=[],f=!1,h=t?"api":"",b="",y=/^namespace\s+([a-zA-Z0-9_\\]+);/,g=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,S=/^interface\s+([a-zA-Z0-9_]+)/,R=/^trait\s+([a-zA-Z0-9_]+)/,w=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,T=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,v=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,k=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,F=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let x=0;x<r.length;x++){let I=r[x].trim();if(!I)continue;let M=(I.match(/{/g)||[]).length,$=(I.match(/}/g)||[]).length,j=l;if(l+=M-$,c&&l<=d){let W=n.find(O=>O.name===c&&O.line===a);W&&(W.endLine=x+1),c="",d=-1}if(o&&l<=p){let W=n.find(O=>O.name===o&&(O.kind==="ClassDeclaration"||O.kind==="TraitDeclaration"||O.kind==="InterfaceDeclaration"));W&&(W.endLine=x+1),o="",p=-1}let H=I.match(F);if(H&&(h=H[1]),I.includes("});")&&(h=""),I.startsWith("/**")){f=!0,m=[];continue}if(f){I.endsWith("*/")?f=!1:m.push(I.replace(/^\*\s?/,""));continue}let N=I.match(v);if(N){u.push(N[1]);continue}let L=I.match(y);if(L){b=L[1]||"",u=[],m=[];continue}let A=I.match(g);if(A){o=A[1],p=l-M;let W={attributes:u};b&&(W.namespace=b),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:x+1,endLine:x+1,doc:m.join(`
504
+ `).trim(),capabilities:JSON.stringify(W),members:[]}),u=[],m=[];continue}let D=I.match(S);if(D){let W=D[1];o=W,p=l-M,n.push({name:W,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${W}`,line:x+1,endLine:x+1,doc:m.join(`
505
+ `).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let te=I.match(R);if(te){let W=te[1];o=W,p=l-M,n.push({name:W,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${W}`,line:x+1,endLine:x+1,doc:m.join(`
506
+ `).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let Et=I.match(w);if(Et){let W=Et[1],O=!!o;c=W,a=x+1,d=l-M;let Ye=!1,we={};for(let ie of u)ie.toLowerCase().includes("route")&&(Ye=!0,we={type:"route",method:"GET",path:"/"});let Ie=m.join(`
507
+ `).trim();if(Ye){let ie=we.path||"/";n.push({name:ie,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${W}`,line:x+1,endLine:x+1,doc:Ie,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${W}`:W,...we})}),s.push({type:"api_route",name:ie,direction:"consume",line:x+1,snippet:I})}n.push({name:W,kind:O?"MethodDeclaration":"FunctionDeclaration",classification:O?"Method":"Function",signature:`${O?o+":: ":""}${W}`,line:x+1,endLine:x+1,doc:Ie,capabilities:JSON.stringify({attributes:u})}),u=[],m=[];continue}let qe=I.match(T);if(qe){let W=qe[1]||"",O=qe[2]||W.split("\\").pop()||"";n.push({name:O,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${W}`,line:x+1,endLine:x+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:W})}),u=[],m=[];continue}let st=I.match(k);if(st){let W=st[1].toUpperCase(),O=st[2];if(I.includes("Route::")||I.includes("router->")||I.includes("action")||I.includes(",")&&!I.includes("view(")){if(h){let Ae=h.startsWith("/")?h:`/${h}`,Yn=O.startsWith("/")?O:`/${O}`;O=(Ae+Yn).replace(/\/+/g,"/")}let we=null,Ie=I.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(Ie)we=`${Ie[1]}@${Ie[2]}`;else if(I.includes("::class")){let Ae=I.match(/([a-zA-Z0-9_]+)::class/);Ae&&(we=Ae[1])}let ie=I;!I.endsWith(");")&&x+1<r.length&&(ie+=" "+r[x+1].trim(),!ie.endsWith(");")&&x+2<r.length&&(ie+=" "+r[x+2].trim())),n.push({name:O,kind:"HTTP Route",classification:"Service Boundary",signature:ie,line:x+1,endLine:x+1,doc:"",capabilities:JSON.stringify({type:"route",method:W,path:O,handler:we})}),s.push({type:"api_route",name:O,direction:"consume",line:x+1,snippet:ie,method:W,url:O}),m=[];continue}}let zt=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,Je=I.match(zt);if(Je){let W=(Je[1]||Je[3]).toUpperCase(),O=(Je[2]||Je[4]).trim();(O.startsWith("'")&&O.endsWith("'")||O.startsWith('"')&&O.endsWith('"'))&&(O=O.substring(1,O.length-1)),s.push({type:"api_route",name:O,direction:"produce",line:x+1,snippet:I,method:W,url:O})}!I.startsWith("#[")&&!I.startsWith("//")&&!I.startsWith("*")&&!f&&(u=[],m=[])}return{nodes:n,events:s}}};var xn=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],s=e.split(`
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 d(y){return y.trim().split(/[.(]/)[0]?.trim()||y}function u(y){let g=y.decorators.map(R=>d(R.raw)),S={decorators:y.decorators,decoratorNames:g};return y.async===!0&&(S.async=!0),JSON.stringify(S)}let m=!1,f="",h=[],b=[];for(let y=0;y<s.length;y++){let g=s[y],S=g.trim();if(!S||S.startsWith("#"))continue;let R=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,w=S.match(R);if(w&&(this.currentRoutePrefix=w[2]),m){if(S.endsWith(f)||S.includes(f)){m=!1;let A=S.replace(f,"").trim();A&&h.push(A);let D=r[r.length-1];D.node&&(D.node.doc=h.join(`
509
+ `).trim()),h=[]}else h.push(S);continue}let T=g.search(/\S/),v=g.trim(),k=v.match(/^(['"]{3})/);if(k){let A=k[1],D=r[r.length-1];if(D.node&&!D.node.doc){if(v.substring(3).includes(A)){let te=v.replace(new RegExp(A,"g"),"").trim();D.node.doc=te}else{m=!0,f=A;let te=v.substring(3).trim();te&&h.push(te)}continue}}for(;r.length>1&&r[r.length-1].indent>=T;)r.pop();let F=r[r.length-1],x=v.match(p);if(x){o.push({raw:x[1].trim(),line:y+1});continue}let I=v.match(c);if(I){let A=I[1],D={name:A,kind:"ClassDeclaration",classification:"Class",signature:`class ${A}`,line:y+1,endLine:y+1,doc:"",capabilities:u({decorators:o}),members:[]};b.push(D),F.node?(F.node.members||(F.node.members=[]),F.node.members.push(D)):t.push(D),r.push({indent:T,name:A,type:"class",node:D}),o=[];continue}let M=v.match(a);if(M){let A=!!M[1],D=M[1]||M[2],te=F.type==="class",Et=!1,qe={};for(let O of o)if(O.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){Et=!0;let we=["get","post","put","delete","patch"].find(Ae=>O.raw.toLowerCase().includes(`.${Ae}`))?.toUpperCase()||"GET",Ie=O.raw.match(/['"]([^'"]+)['"]/),ie=Ie?Ie[1]:"/";if(this.currentRoutePrefix){let Ae=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,Yn=ie.startsWith("/")?ie:`/${ie}`;ie=Ae+Yn}qe={type:"route",method:we,path:ie}}if(Et){let O=qe.path||"",Ye={name:O||D,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${D}`,line:y+1,endLine:y+1,doc:"",capabilities:JSON.stringify({handler:te?`${F.name}.${D}`:D,async:A,...qe})};b.push(Ye),t.push(Ye),n.push({type:"api_route",name:O,direction:"consume",line:y+1,snippet:v})}let st=o.some(O=>O.raw==="staticmethod"),zt=o.some(O=>O.raw==="classmethod"),Je=`${A?"async ":""}${te?(st?"@staticmethod ":zt?"@classmethod ":"")+F.name+".":""}${D}`,W={name:D,kind:A&&te?"AsyncMethodDeclaration":A?"AsyncFunctionDeclaration":te?"MethodDeclaration":"FunctionDeclaration",classification:te?st||zt?"Static Method":"Method":"Function",signature:Je,line:y+1,endLine:y+1,doc:"",capabilities:u({decorators:o,async:A}),members:[]};b.push(W),F.node?(F.node.members||(F.node.members=[]),F.node.members.push(W)):t.push(W),r.push({indent:T,name:D,type:"function",node:W}),o=[];continue}let $=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,j=v.match($);if(j){let A=j[1].replace(/^\^/,""),D={name:A,kind:"HTTP Route",classification:"Service Boundary",signature:v.trim(),line:y+1,endLine:y+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:A})};b.push(D),t.push(D),n.push({type:"api_route",name:A,direction:"consume",line:y+1,snippet:v});continue}let H=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,N=v.match(H);if(N){let A=N[1].toUpperCase(),D=N[2].trim();(D.startsWith("'")&&D.endsWith("'")||D.startsWith('"')&&D.endsWith('"'))&&(D=D.substring(1,D.length-1)),n.push({type:"api_route",name:D,direction:"produce",line:y+1,snippet:v,method:A,url:D})}let L=v.match(l);if(L){let A=L[1]||L[2],D={name:A,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${A}`,line:y+1,endLine:y+1,doc:"",capabilities:JSON.stringify({type:"import",module:A})};b.push(D),t.push(D),o=[];continue}o=[],F.node&&(F.node.endLine=y+1)}return{nodes:b,events:n}}};var Wi=[{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 Da(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 Tn=class{phpParser=new _n;pythonParser=new xn;treeSitterParser=new Sn;supports(e){return Wi.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=hs.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"),d=Da(n,s),u=Ct({classification:a,capabilities:d,exports:l.map(m=>({name:m.name,kind:m.kind,classification:m.classification})),fileName:hs.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:u||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Wi.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),d=t.substring(0,l.index).split(`
510
+ `).length;s.push({name:p.name||"anonymous",kind:p.kind||"Unknown",classification:p.classification||"Other",signature:p.signature||l[0],line:d,endLine:d,doc:"",capabilities:JSON.stringify(p.meta||{})})}}let c=Ct({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:s.map(a=>({name:a.name,kind:a.kind,classification:a.classification})),fileName:hs.basename(e)});return{exports:s,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:c||"Module",parseStatus:s.length>0?"success":"partial"}}};P();var gs=new Tn;async function $t(i){let e=ji.extname(i);if(gs.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=fs.readFileSync(i,"utf-8");return await gs.parse(i,r)}catch(r){return _.error({filePath:i,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:r.message}}let t;try{t=fs.readFileSync(i)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),s=$i(n);try{let r=i.endsWith(".tsx"),o=Oa.parseSync(n,{syntax:"typescript",tsx:r,decorators:!0,comments:!0}),c=o.span.start,a=Li(n),l=y=>ki(y,c,t),p=Ai(o.body),d=Di(o.body);d.length>0&&_.debug({filePath:i,count:d.length},"Extracted type references"),d.forEach(y=>{p.push({module:"__type_reference__",name:y})});let u=Mi(o.body,c,t,n,s,a,i,l),m=Pi(o.body,c,t,s,l),f=En(i,"","Module"),h=a.length>0&&a[0].start===0?a[0].text:u.find(y=>y.doc)?.doc||"",b=Ni(h);if(!b&&u.length>0){let y=It(n);b=Ct({classification:f,capabilities:y,exports:u.map(g=>({name:g.name,kind:g.kind,classification:g.classification})),fileName:ji.basename(i)})}return{exports:u,imports:p,events:m,classification:f,summary:b,parseStatus:"success"}}catch(r){_.warn({filePath:i,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=fs.readFileSync(i,"utf-8"),c=await gs.parse(i,o);return{...c,classification:c.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return _.error({filePath:i,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}P();import Zi from"p-limit";Qe();import Xa from"path";import Es from"fs";import Za from"os";import he from"path";import lt from"fs";import{loadConfig as Ha,createMatchPath as Wa}from"tsconfig-paths";import Oe from"path";import kt from"fs";var Fe=class extends Error{constructor(t,n,s){super(n);this.code=t;this.cause=s;this.name="FileSystemError"}};function Ui(i){let e;try{e=kt.statSync(i).isDirectory()?i:Oe.dirname(i)}catch(t){throw t.code==="ENOENT"?new Fe("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new Fe("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new Fe("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==Oe.dirname(e);){let t=Oe.join(e,"tsconfig.json");if(kt.existsSync(t))return e;e=Oe.dirname(e)}return null}function Bi(i){let e;try{e=kt.statSync(i).isDirectory()?i:Oe.dirname(i)}catch(t){throw t.code==="ENOENT"?new Fe("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new Fe("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new Fe("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==Oe.dirname(e);){let t=Oe.join(e,"package.json");if(kt.existsSync(t))try{if(JSON.parse(kt.readFileSync(t,"utf8")).workspaces)return e}catch{}e=Oe.dirname(e)}return null}import ct from"path";import Ze from"fs";function zi(i,e){let t=new Map,n=e.workspaces||[];for(let s of n){let r=s.replace("/*",""),o=ct.join(i,r);if(!Ze.existsSync(o))continue;let c=Ze.readdirSync(o);for(let a of c){let l=ct.join(o,a,"package.json");if(Ze.existsSync(l))try{let p=JSON.parse(Ze.readFileSync(l,"utf8"));p.name&&t.set(p.name,{name:p.name,path:ct.dirname(l),main:p.main||"dist/index.js"})}catch{}}}return t}function Gi(i){let e=new Map;try{let t=JSON.parse(Ze.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=ct.dirname(i),a=ct.resolve(c,o),l=ct.join(a,"package.json");if(Ze.existsSync(l))try{let p=JSON.parse(Ze.readFileSync(l,"utf8"));e.set(s,{name:s,path:a,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import qi from"path";import me from"fs";var Fa=[".ts",".tsx",".d.ts",".js",".jsx"];function He(i){let e=qi.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(me.existsSync(r)&&me.statSync(r).isFile())return r}if(me.existsSync(i)&&me.statSync(i).isFile())return i}if(me.existsSync(i)&&me.statSync(i).isFile())return i;for(let t of Fa){let n=i+t;if(me.existsSync(n)&&me.statSync(n).isFile())return n}if(me.existsSync(i)&&me.statSync(i).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=qi.join(i,"index"+t);if(me.existsSync(n))return n}return""}var vn=new Map;function Rn(i){let e=Ui(i);if(!e)return null;if(vn.has(e))return vn.get(e)||null;let t=Ha(e);if(t.resultType==="failed")return vn.set(e,null),null;let n=t,s=n.absoluteBaseUrl;!s&&n.paths&&Object.keys(n.paths).length>0&&(s=n.configFileAbsolutePath?he.dirname(n.configFileAbsolutePath):e);let r=Wa(s,n.paths,n.mainFields,n.addMatchAll),o=Bi(e),c=new Map;if(o){let d=he.join(o,"package.json");if(lt.existsSync(d))try{let u=JSON.parse(lt.readFileSync(d,"utf8"));c=zi(o,u)}catch{}}let a=he.join(e,"package.json");lt.existsSync(a)&&Gi(a).forEach((u,m)=>c.set(m,u));let l={baseUrl:s||"",paths:n.paths,matchPath:r,workspacePackages:c,imports:new Map},p=he.join(e,"package.json");if(lt.existsSync(p))try{let d=JSON.parse(lt.readFileSync(p,"utf8"));if(d.imports){for(let[u,m]of Object.entries(d.imports))if(typeof m=="string"||typeof m=="object"&&m!==null){let f=m;Array.isArray(m)&&(f=m[0]),typeof f=="object"&&(f=f.default||f.node),typeof f=="string"&&l.imports.set(u,f)}}}catch{}return vn.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=he.dirname(e),r=he.resolve(s,i);return He(r)}let n=Rn(e);if(n){let s=n.matchPath(i);if(s)return He(s);if(!i.startsWith("@")||i.startsWith("@/")){let o=he.resolve(n.baseUrl,i),c=He(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 d=p[1],u=c.replace("*",d),m=he.resolve(n.baseUrl,u);return He(m)}}else if(o===i){let a=he.resolve(n.baseUrl,c);return He(a)}let r=n.workspacePackages.get(i);if(r){let o=he.join(r.path,"src/index.ts");if(lt.existsSync(o))return o;let c=he.join(r.path,r.main),a=He(c);if(a)return a}}return""}import ja from"fs";import Ua from"path";import Yi from"js-yaml";function Ji(i){let e=Ua.basename(i),t=ja.readFileSync(i,"utf8"),n=[];if(e.endsWith(".prisma"))return qa(t,i);if(e.endsWith(".graphql")||e.endsWith(".gql"))return Ja(t,i);let s="Configuration";return e==="lerna.json"?Va(t,i):e==="turbo.json"?Qa(t,i):e==="pnpm-workspace.yaml"?Ka(t,i):(e.includes("Dockerfile")?(s="Infrastructure (Docker) ",Ba(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(s="Infrastructure (YAML) ",za(t,n)):e.startsWith(".env")?(s="Configuration (Env) ",Ga(t,n)):e==="package.json"&&(s="Project Manifest",Ya(t,n)),{configs:n,classification:s})}function Ba(i,e){let t=i.split(`
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 za(i,e){try{let t=Yi.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 Ga(i,e){let t=i.split(`
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 qa(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}}function Ja(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}}function Ya(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 Va(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}}function Qa(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}}function Ka(i,e){let t=[],n="Monorepo (pnpm) ";try{let s=Yi.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}}U();import{execSync as et}from"child_process";import ys from"path";import bs from"fs";function re(i){try{if(!bs.existsSync(ys.join(i,".git")))return null;let e=et("git rev-parse --abbrev-ref HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return e==="HEAD"?et("git rev-parse --short HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():e.replace(/[\/\\:*"<>|?]/g,"-")}catch{return null}}function fe(i){try{return bs.existsSync(ys.join(i,".git"))?et("git rev-parse HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function Vi(i,e=50){try{let t=et(`git rev-list --max-count=${e} HEAD`,{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return t?t.split(`
513
+ `):[]}catch{return[]}}function Qi(i,e,t){try{return et(`git merge-tree --write-tree ${e} ${t}`,{cwd:i,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}function Ki(i,e){try{if(!bs.existsSync(ys.join(i,".git")))return!0;let t=fe(i);return!t||e&&e!==t&&et(`git diff --name-only ${e} ${t}`,{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()?!0:et("git status --porcelain",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim().length>0}catch{return!0}}U();P();import{execSync as Xi}from"child_process";var tt=_.child({module:"nano-repair"}),Te=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};tt.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}),tt.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}),tt.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&&tt.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(){let e="HEAD";try{e=Xi("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"),tt.info({missionId:o.id,branch:o.git_branch,current:e},"Context Pivot: Suspended mission"),n++);this.missions.resumeByBranch(e);let s=[];try{s=Xi(`git branch --merged "${e}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
514
+ `).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"),tt.info({missionId:c.id,branch:c.git_branch},"Merge Sentinel: Auto-completed mission"),r++}return(n>0||r>0)&&tt.info({suspended:n,completed:r},"Git-Native Lifecycle Sync complete"),{suspended:n,resumed:-1,completed:r}}};var Xd=Za.cpus().length||4,ec=bn.DEFAULT_CONCURRENCY;async function z(i,e=ec,t=!1,n=!0,s){let r=C.getInstance(i),o=r.files.database,c=Ce(i),a=c.concurrency??e;if(xi(),!t&&Ve(i)){let y=xt(i),g=fe(i);if(y&&!Ki(i,y))return ls(),_.debug({repoPath:i,commit:g},"Index is current, skipping re-index (fast-path)"),o}Rn(i);let l=r.files.findAll(),p=new Map(l.map(y=>[y.path,{mtime:y.mtime,hash:y.content_hash}])),d=Date.now();s?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let u=await ds(i,c.ignore),m=new Map(u.map(y=>[y.path,y.mtime])),f=l.filter(y=>!m.has(y.path)).map(y=>y.path),h=l.length===0,b=[];if(t||h)b.push(...u);else{let y=u.filter(w=>{let T=p.get(w.path);return!T||T.mtime!==w.mtime}),g=Zi(a*4),S=y.map(w=>g(async()=>{let T=p.get(w.path);if(!T||!T.hash)return w;try{let v=await Es.promises.readFile(w.path,"utf8");return Gs(v,T.hash)?w:(r.files.updateMtime(w.path,w.mtime),null)}catch{return null}})),R=await Promise.all(S);b.push(...R.filter(w=>w!==null))}if(f.length===0&&b.length===0){if(ls(),h){let y=fe(i);Zn(i,y||void 0)}return o}if(h?_.info({totalFiles:u.length},"Starting initial repository indexing..."):_.info({toDelete:f.length,toProcess:b.length},"Syncing repository updates..."),f.length>0&&r.files.deletePaths(f),b.length>0){Ri(),n?un(!0):un(!1);let y=Zi(a),g=0,S=b.length,R=b.map(F=>y(async()=>{try{let x=Xa.basename(F.path);if(/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/.test(x)){let M=await $t(F.path),$=Es.readFileSync(F.path,"utf8");return g++,(g%50===0||g===S)&&_.info({completed:g,total:S},"Parsing files..."),s?.({phase:"parse",current:g,total:S,message:`Parsing ${x}`}),{meta:F,...M,content:$,embedding:null,kind:"code"}}else{let M=Ji(F.path),$=Es.readFileSync(F.path,"utf8");return g++,(g%50===0||g===S)&&_.info({completed:g,total:S},"Parsing configs..."),s?.({phase:"parse",current:g,total:S,message:`Parsing config ${x}`}),{meta:F,...M,content:$,embedding:null,kind:"config"}}}catch(x){return g++,_.error({path:F.path,error:x},"Failed to parse file"),{meta:F,exports:[],imports:[],content:"",kind:"error"}}}));_.info({total:S},"Phase 1: Parsing all files...");let w=Date.now(),T=(await Promise.all(R)).filter(Boolean),v=Date.now()-w;if(hn("parse",v),_.info({count:T.length,time:`${(v/1e3).toFixed(1)}s`},"Phase 1 complete"),n){_.info("Phase 2: Generating file semantic embeddings..."),s?.({phase:"embed",current:0,total:T.length,message:"Generating embeddings..."});let F=Date.now(),x=[];if(T.forEach((M,$)=>{"summary"in M&&M.summary&&x.push({fileIdx:$,text:M.summary})}),x.length>0){_.info({count:x.length}," \u2192 Generating file summary embeddings...");let M=x.map(j=>j.text),$=await os(M,128);x.forEach((j,H)=>{T[j.fileIdx].embedding=$[H]}),_.info({count:x.length}," \u2713 File summaries complete")}let I=Date.now()-F;hn("embed",I),_.info({time:`${(I/1e3).toFixed(1)}s`},"Phase 2 complete")}s?.({phase:"persist",current:0,total:T.length,message:"Saving to database..."});let k=Date.now();r.files.batchSaveIndexResults(T,i,Xn,Lt),hn("persist",Date.now()-k)}if(h||b.length>0){let y=fe(i);Zn(i,y||void 0)}return(b.length>0||f.length>0)&&new Te(i).detectAndRepairShifts(),Ti(Date.now()-d),s?.({phase:"complete",current:b.length,total:b.length,message:"Indexing complete"}),o}U();async function Nt(i,e=bn.DEFAULT_CONCURRENCY,t="detailed",n,s){_.info({repo:i,level:t,subPath:n},"Ensuring cache is up-to-date..."),await z(i,e);let{files:r,exports:o,imports:c}=C.getInstance(i),a=n?r.findInSubPath(i,n):r.findAll(),l=Ce(i),p=tc(),d=er.join(i,".gitignore");if(tr.existsSync(d)&&p.add(tr.readFileSync(d,"utf8")),l.ignore&&l.ignore.length>0&&p.add(l.ignore),p.add(yn),a=a.filter(g=>{let S=er.relative(i,g.path);return!p.ignores(S)}),_.info({count:a.length},"Fetching data from DB..."),t==="lite"){let g=a.map(S=>({path:S.path,mtime:S.mtime}));return wt(g,i,t,s)}if(t==="summaries"){let g=a.map(S=>({path:S.path,mtime:S.mtime,classification:S.classification||void 0,summary:S.summary||void 0}));return wt(g,i,t,s)}let u=a.map(g=>g.path),m=o.findByFiles(u),f=t==="detailed"?c.findByFiles(u):[],h=new Map;for(let g of m){let S=h.get(g.file_path)||[];S.push(g),h.set(g.file_path,S)}let b=new Map;for(let g of f){let S=b.get(g.file_path)||[];S.push(g),b.set(g.file_path,S)}let y=a.map(g=>{let R=(h.get(g.path)||[]).map(T=>({name:T.name,kind:T.kind,signature:T.signature,line:T.start_line}));t==="structure"?R=R.map(T=>({name:T.name,kind:T.kind,line:T.line})):t==="signatures"&&(R=R.map(T=>({name:T.name,kind:T.kind,signature:T.signature,line:T.line})));let w=[];return t==="detailed"&&(w=(b.get(g.path)||[]).map(v=>({module:v.module_specifier,resolved_path:v.resolved_path}))),{path:g.path,mtime:g.mtime,classification:g.classification||void 0,summary:g.summary||void 0,exports:R,imports:w.length>0?w:void 0,chunks:[]}});return _.info({count:y.length},"Building hierarchical project tree..."),wt(y,i,t,s)}async function sr(i,e){let t=nr.resolve(i),n=parseInt(e.depth);try{await B(async()=>{let s=await Nt(t,5,"lite",e.subPath,n);console.log(""),console.log(` ${E.bold("Repository Structure: ")} ${E.cyan(nr.basename(t))}`),e.subPath&&console.log(` ${E.bold("Sub-path: ")} ${E.dim(e.subPath)}`),console.log("");let r=o=>{let c=o.type==="truncated",a=o.type==="directory"&&o.children===void 0;return{name:o.name,color:o.type==="directory"?"blue":c?"gray":"white",info:o.type==="file"?o.summary?.classification:a?"truncated":void 0,children:o.children?.map(r)}};ts([r(s)]),console.log(""),n<10&&(console.log(E.gray(` (Showing depth ${n}. Use --depth to see more)`)),console.log(""))})}finally{await q(t)}}import rr from"path";import nc from"fs";P();import Z from"path";import Ss from"fs";var wn=_.child({module:"path-resolver"}),At=class{repoPath;constructor(e){this.repoPath=Z.isAbsolute(e)?Z.normalize(e):Z.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw wn.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(Z.isAbsolute(e)?t=Z.normalize(e):t=Z.join(this.repoPath,e),t=Z.normalize(t),!this.isWithinRoot(t))throw wn.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 Ss.existsSync(t)?t:(wn.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return wn.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=Z.resolve(e),n=Z.resolve(this.repoPath),s=Z.relative(n,t);if(s.startsWith("..")||Z.isAbsolute(s))return!1;if(Ss.existsSync(t)){let o=Ss.realpathSync(t),c=Z.relative(n,o);if(c.startsWith("..")||Z.isAbsolute(c))return!1}return!0}catch{return!1}}getRelative(e){let t=Z.normalize(e);return Z.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return Z.normalize(e)}static isPathWithinRoot(e,t){let n=Z.resolve(e),s=Z.resolve(t),r=Z.relative(n,s);return r===""||!r.startsWith("..")&&!Z.isAbsolute(r)}};function ir(i){return new At(i)}async function or(i,e){let t=rr.resolve(i);await B(async()=>{if(le("MCP Liquid Shadow"),console.log(` ${E.bold("Target")}: ${E.cyan(t)}`),console.log(` ${E.bold("Mode")}: ${e.output?E.magenta("File Export"):E.green("Indexing")}`),console.log(""),!e.output){let s=de();s.start("Indexing repository...");let r="",o=c=>{if(c.phase!==r){r=c.phase;let a={scan:"Scanning",parse:"Parsing",embed:"Generating embeddings",persist:"Saving to database",complete:"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 z(t,void 0,e.force,e.deep??!0,o),s.message("Running symbol healing...");let a=new Te(t).detectAndRepairShifts();s.stop("Indexing complete!"),Tt("Ready to serve AI requests.")}catch(c){throw s.stop(`Indexing failed: ${c.message}`),c}finally{await q(t)}return}let n=de();n.start(`Generating export (${E.bold(e.level)})...`);try{let s=await Nt(t,5,e.level,e.subPath),r=rr.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!At.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");nc.writeFileSync(r,JSON.stringify(s,null,2)),n.stop(`Export saved to ${E.bold(E.cyan(r))}`),Tt("Export complete.")}catch(s){throw n.stop(`Export failed: ${s.message}`),s}finally{await q(t)}})}import{performance as ar}from"perf_hooks";import sc from"path";U();async function cr(i){let e=sc.resolve(i);await B(async()=>{console.log(`
515
+ ${E.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${E.gray("Repository: ")} ${e}`),console.log(` ${E.yellow("Starting fresh index (DB deleted)...")}
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
+ ${E.bold("Files Processed")}: ${E.cyan(r.toString())}
518
+ ${E.bold("Symbols Extracted")}: ${E.cyan(o.toString())}
519
+ ${E.bold("Symbols Embedded")}: ${E.cyan(c.toString())} (${(c/o*100).toFixed(1)}%)
513
520
  `+"\u2500".repeat(40)+`
514
- ${f.bold("Files/sec")}: ${f.green((r/(n/1e3)).toFixed(2))}
515
- ${f.bold("Symbols/sec")}: ${f.green((o/(n/1e3)).toFixed(2))}
516
- ${f.bold("ms per file")}: ${f.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
517
- Benchmark failed during execution:`,n),n}finally{await G(e)}})}import In from"path";import pe from"path";import Si from"fs";var Za=/[\x00-\x1f\x7f]/g,ec=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Ei(s){if(typeof s!="string")throw new Error("Invalid path: expected string");if(s.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(s.replace(Za,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function vn(s,e=4096){if(typeof s!="string")return"";let t=s.replace(ec,"").trim();return t.length>e?t.slice(0,e):t}Ve();function tc(s){let e=pe.isAbsolute(s)?pe.normalize(s):pe.resolve(process.cwd(),s),t=pe.parse(e).root;for(;e!==t;){if(Si.existsSync(pe.join(e,".liquid-shadow.db"))||Si.existsSync(pe.join(e,".git"))||Si.existsSync(pe.join(e,"package.json")))return e;let n=pe.dirname(e);if(n===e)break;e=n}return null}function xe(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=Ei(e)),t&&(t=Ei(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=tc(pe.dirname(o))||process.cwd()}else n=process.cwd();n=pe.normalize(n);let i=er(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}F();N();import or from"@swc/core";import Mt from"fs";import ge from"path";import{Visitor as nc}from"@swc/core/Visitor.js";var wn=class extends nc{calls=new Set;apiCalls=[];imports=new Map;axiosInstances=new Map;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),l=r.property.value||"?";return`${o}.${l}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},i=n(e.callee.object);if(i!=="?"&&t){if(this.calls.add(`${i}.${t}`),i==="axios"||i==="http"||this.axiosInstances.has(i)){let r=this.axiosInstances.get(i)||"";this.extractApiCall(t,e.arguments,r)}if((i.toLowerCase().includes("pubsub")||i==="pubSubClient"||i.endsWith(".pubSubClient"))&&t!=="subscribe"){let r=t;if((t==="publish"||t==="publishMessage"||t==="publishTaskByNameAndPayload")&&e.arguments.length>0)for(let o of e.arguments){let l=o.expression;if(l.type==="ObjectExpression"){let c=l.properties.find(a=>a.key?.type==="Identifier"&&(a.key.value==="action"||a.key.value==="type")||a.key?.type==="StringLiteral"&&(a.key.value==="action"||a.key.value==="type"));if(c&&c.value?.type==="StringLiteral"){r=c.value.value;break}}if(l.type==="CallExpression"&&l.callee.type==="MemberExpression"&&l.callee.object.value==="JSON"&&l.callee.property.value==="stringify"&&l.arguments.length>0){let c=l.arguments[0].expression;if(c.type==="ObjectExpression"){let a=c.properties.find(p=>p.key?.type==="Identifier"&&(p.key.value==="action"||p.key.value==="type")||p.key?.type==="StringLiteral"&&(p.key.value==="action"||p.key.value==="type"));if(a&&a.value?.type==="StringLiteral"){r=a.value.value;break}}}}this.apiCalls.push({method:"PUBSUB",url:r})}}}return e.callee.type==="Identifier"&&e.callee.value==="fetch"&&this.extractApiCall("GET",e.arguments),super.visitCallExpression(e)}visitNewExpression(e){return e.callee.type==="Identifier"&&this.calls.add(e.callee.value),super.visitNewExpression(e)}visitVariableDeclarator(e){if(e.init&&e.init.type==="CallExpression"){let t=e.init.callee;if(t.type==="MemberExpression"&&t.property.value==="create"&&t.object.value==="axios"){let i=e.init.arguments[0]?.expression;if(i&&i.type==="ObjectExpression"){let r=i.properties.find(o=>o.key.value==="baseURL");if(r){let o="?";r.value.type==="StringLiteral"?o=r.value.value:r.value.type==="Identifier"&&(o=`\${${r.value.value}}`),e.id.type==="Identifier"&&this.axiosInstances.set(e.id.value,o)}}}}return super.visitVariableDeclarator(e)}extractApiCallFromConfig(e){if(e&&e.type==="ObjectExpression"){let t=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="url"||i.key.type==="StringLiteral"&&i.key.value==="url"),n=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="method"||i.key.type==="StringLiteral"&&i.key.value==="method");if(t&&t.value){let i=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:i.toUpperCase(),url:r})}}}resolveUrlValue(e){return e.type==="StringLiteral"?e.value:e.type==="TemplateLiteral"?e.quasis.map(t=>t.cooked).join("*"):"?"}visitTsType(e){return e}extractApiCall(e,t,n=""){if(t.length>0){let i=t[0].expression,r=this.resolveUrlValue(i);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},lt=class{calls=new Set;apiCalls=[];imports=new Map;visit(e,t){if(t===".php"){let n=/(?:([a-zA-Z0-9_$->:\(\)]*)?(?:->|::))?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],l=i[3];if(this.calls.add(o),r&&!["$this","self","parent"].includes(r)&&this.calls.add(`${r}${r.includes("::")?"::":"->"}${o}`),["save","delete","update","create","first","all","where","get","find"].includes(o)&&r&&!["Log","Route","Cache","Config","Http"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}->${o}()`}),o==="publish"&&r&&(r.includes("topic")||r.includes("pubSub"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="Http"||r==="client"||r.endsWith("request")||r.includes("Client")||!r)){let p=l.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),d=p?p[1]:l.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,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],l=i[3];if(this.calls.add(o),r&&r!=="self"&&r!=="cls"&&this.calls.add(`${r}.${o}`),["save","delete","update","create","first","all","filter","get"].includes(o)&&r&&!["logger","os","sys"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}.${o}()`}),o==="publish"&&r&&(r.includes("publisher")||r.includes("client"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="requests"||r==="httpx"||r==="client"||r==="http"||!r)){let p=l.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),d=p?p[1]:l.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,i;for(;(i=n.exec(e))!==null;)this.imports.set("*",i[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let l=o[1],c=o[2];l?(this.calls.add(`${l}.${c}`),(l.toLowerCase().includes("pubsub")||l==="pubSubClient")&&c!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:c})):this.calls.add(c)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,i;for(;(i=n.exec(e))!==null;)this.calls.add(i[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,i;for(;(i=n.exec(e))!==null;){let r=i[1],o=r.split("\\"),l=i[2]||o[o.length-1];this.imports.set(l,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,i;for(;(i=n.exec(e))!==null;){let l=i[1];i[2].split(",").map(a=>a.trim()).forEach(a=>{this.imports.set(a,l)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let l=o[1],c=l.split("."),a=c[c.length-1];this.imports.set(a,l)}}}};var ic=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 rr(s,e){let t=e,n=e.match(/\$\{([^}]+)\}/g);if(n)for(let p of n){let d=p.substring(2,p.length-1),u=s.configs.findEnvValue(d);u&&(t=t.replace(p,u))}let i=t.split("?")[0];try{i.includes("://")&&(i=new URL(i).pathname)}catch{}let r=[],o=i.split("?")[0],l=s.files.findSynapses({type:"api_route",name:o,direction:"consume"});for(let p of l)r.push({file_path:p.file_path,start_line:p.line_number||0,signature:`[Synapse] ${p.name}`,score:1e3});let c=i.split(/[^a-zA-Z0-9-_]/).filter(p=>p.length>=3&&!ic.has(p.toLowerCase())&&!/^\d+$/.test(p));if(c.length>0){let d=[...c].sort((m,h)=>h.length-m.length)[0],u=s.exports.findRoutesByToken(d);for(let m of u){let h=50,b=(m.signature||m.name||"").toLowerCase();for(let E of c)b.includes(E.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=c.map(u=>u.replace(/[^a-zA-Z0-9_]/g,"")).filter(u=>u.length>0).join(" AND ");if(p.length===0)return r;let d=s.content.search(p);for(let u of d){let m=0,h=u.file_path.toLowerCase(),b=u.snippet.toLowerCase();(h.includes("route")||h.includes("controller")||h.includes("handler"))&&(m+=10),(h.includes("src/api")||h.includes("services/api"))&&(m+=5),(b.includes("addroute")||b.includes("@get")||b.includes("router."))&&(m+=15),(b.includes("axios.")||b.includes("fetch("))&&(m-=10),(h.includes(".spec.")||h.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 a=new Map;return r.sort((p,d)=>d.score-p.score).forEach(p=>{a.has(p.file_path)||a.set(p.file_path,p)}),Array.from(a.values()).slice(0,3)}var sc=4,Pt=50,rc=2;async function ar(s){let{repoPath:e,filePath:t,symbolName:n}=xe(s);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let i=t;await j(e);let r=k.getInstance(e);if(!Mt.existsSync(i))return{isError:!0,content:[{type:"text",text:`File not found: ${i}`}]};let o,l=ge.basename(i),c;if(n){let u=r.exports.findByNameAndFile(n,i);if(u.length>0){let m=u[0];o={start:m.start_line,end:m.end_line},l=m.name,c=m.start_line}}let a={type:o?"function":"file",name:l,path:ge.relative(e,i),line:c,children:[]},p=new Set;p.add(i+(n?`:${n}`:""));let d={count:0,truncated:!1};return await pt(i,a,e,r,p,1,d,o),d.truncated&&a.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(a,null,2)}]}}async function pt(s,e,t,n,i,r,o,l){if(!(r>sc)){if(o.count>=Pt){o.truncated=!0;return}try{let c=Mt.readFileSync(s,"utf8"),a=ge.extname(s).toLowerCase(),d=(c.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
518
- `);l&&(c=c.split(`
519
- `).slice(l.start-1,l.end).join(`
520
- `));let u;if(a===".ts"||a===".tsx"||a===".js"||a===".jsx"){u=new wn;let E={syntax:"typescript",tsx:s.endsWith(".tsx"),target:"es2020"};try{let g=l?`${d}
521
- ${c}`:c,y=await or.parse(g,E);u.visitModule(y)}catch{if(l)try{let y=`${d}
521
+ ${E.bold("Files/sec")}: ${E.green((r/(n/1e3)).toFixed(2))}
522
+ ${E.bold("Symbols/sec")}: ${E.green((o/(n/1e3)).toFixed(2))}
523
+ ${E.bold("ms per file")}: ${E.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
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(`
525
+ `);c&&(a=a.split(`
526
+ `).slice(c.start-1,c.end).join(`
527
+ `));let u;if(l===".ts"||l===".tsx"||l===".js"||l===".jsx"){u=new Cn;let b={syntax:"typescript",tsx:i.endsWith(".tsx"),target:"es2020"};try{let y=c?`${d}
528
+ ${a}`:a,g=await pr.parse(y,b);u.visitModule(g)}catch{if(c)try{let g=`${d}
522
529
  class TraceContext {
523
- ${c}
524
- }`,S=await or.parse(y,E);u.visitModule(S)}catch{let S=new lt,w=a;S.visit(c,w),u.calls=S.calls,u.apiCalls=S.apiCalls,u.imports=S.imports}else{let y=new lt;y.visit(c,a),u.calls=y.calls,u.apiCalls=y.apiCalls,u.imports=y.imports}}}else u=new lt,u.visit(c,a);_.info({file:ge.basename(s),calls:u.calls.size,apiCalls:u.apiCalls.length,depth:r},"Analyzed file");let m=u.apiCalls.slice(0,10);for(let E of m){if(o.count>=Pt)break;if(o.count++,E.method==="PUBSUB"){let w={type:"event_trigger",name:`PubSub Event: ${E.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(w);let C=n.exports.findByNameGlobal(E.url).concat(n.exports.findByMethodName(E.url));if(E.url.length>10){let I=E.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(I!==E.url){let x=n.exports.findByNameGlobal(I).concat(n.exports.findByMethodName(I));C.push(...x)}}let T=new Set;for(let I of C){if(T.has(I.file_path)||I.file_path===s)continue;if(T.add(I.file_path),o.count>=Pt)break;o.count++;let x={type:"subscriber",name:`${I.name} (${ge.basename(I.file_path)})`,path:ge.relative(t,I.file_path),line:I.start_line,details:"Potential Subscriber / Handler",children:[]};w.children.push(x),Mt.existsSync(I.file_path)&&!i.has(I.file_path)&&(i.add(I.file_path),await pt(I.file_path,x,t,n,i,r+1,o))}continue}let g={type:"api_call",name:`${E.method} ${E.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(g);let S=rr(n,E.url).slice(0,rc);for(let w of S){if(o.count>=Pt)break;o.count++;let C={type:"route",name:w.signature||"Route Handler",path:w.file_path,line:w.start_line,children:[]};if(g.children.push(C),Mt.existsSync(w.file_path)&&!i.has(w.file_path)&&(i.add(w.file_path),await pt(w.file_path,C,t,n,i,r+1,o)),w.capabilities)try{let T=JSON.parse(w.capabilities);if(T.handler){let[I,x]=T.handler.split("@");if(I){let R=I.split("\\").pop();if(R){let v=n.exports.findClassByName(R);if(v){let P=n.exports.findByNameAndFile(x||"",v.file_path),L,H=v.start_line;P.length>0&&(L={start:P[0].start_line,end:P[0].end_line},H=P[0].start_line);let B={type:"component",name:`${R}${x?" :: "+x:""}`,path:ge.relative(t,v.file_path),line:H,details:"Controller Logic (Macro IR)",children:[]};C.children.push(B),i.has(v.file_path+(x?`:${x}`:""))||(i.add(v.file_path+(x?`:${x}`:"")),await pt(v.file_path,B,t,n,i,r+1,o,L))}}}}}catch{}}}let h=u.calls,b=Array.from(h).sort();for(let E of b)if(u.imports.has(E)){let g=u.imports.get(E);if(!g.startsWith(".")){if(["react","react-dom"].includes(g))continue;e.children.push({type:"function",name:E,details:`External: ${g}`,children:[]});continue}let y=$t(g,s,t);if(y&&Mt.existsSync(y))if(i.has(y))e.children.push({type:"function",name:E,details:"Circular / Already Visited",path:ge.relative(t,y),children:[]});else{i.add(y);let S={type:"file",name:E,details:`Imported from ${ge.basename(y)}`,path:ge.relative(t,y),children:[]};e.children.push(S),await pt(y,S,t,n,i,r+1,o)}}else if(!["log","info","error","warn","print"].includes(E)){let g=n.exports.findByNameGlobal(E);if(g.length===0){let y=E.split(/(?:\.|->|::)+/);if(y.length>1){let S=y[y.length-1];g=n.exports.findByMethodName(S)}}if(g.length>0){let y=g.find(w=>w.file_path===s),S=y||(g.length===1?g[0]:null);if(S){let w=`${S.file_path}:${S.name}`;if(!i.has(w)){i.add(w);let C={type:"component",name:E,details:`Resolved via global index${y?" (local)":""}`,path:ge.relative(t,S.file_path),line:S.start_line,children:[]};e.children.push(C),await pt(S.file_path,C,t,n,i,r+1,o,{start:S.start_line,end:S.end_line})}}}}}catch(c){_.error({filePath:s,error:c.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:c.message,children:[]})}}}async function cr(s,e){let t=In.resolve(e.dir),n=In.isAbsolute(s)?s:In.resolve(t,s);await U(async()=>{le("Execution Trace");let i=ue();i.start(`Tracing ${f.cyan(e.symbolName||In.basename(n))}...`);try{let r=await ar({repoPath:t,filePath:n,symbolName:e.symbolName});i.stop("Trace complete."),r.isError?console.error(f.red(r.content[0].text)):te("Flow Results",r.content[0].text,"magenta")}catch(r){throw i.stop(`Trace failed: ${r.message}`),r}finally{await G(t)}})}import fc from"path";F();dt();N();import{execSync as Hr}from"child_process";import hc from"path";var kn=_.child({module:"shadow-trace"}),mt=class{intentLogs;exports;repoPath;hologramService;constructor(e){let{intentLogs:t,exports:n}=k.getInstance(e);this.intentLogs=t,this.exports=n,this.repoPath=e,this.hologramService=new de(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=Hr(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
525
- `).filter(o=>o.trim()!=="");if(r.length===0)return;kn.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let l=hc.join(this.repoPath,o),a=Hr(`git diff -U0 ${t} -- ${o}`,{cwd:this.repoPath,encoding:"utf-8"}).matchAll(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/g);for(let p of a){let d=parseInt(p[2],10),u=this.exports.findAtLine(l,d);u&&(this.intentLogs.create({mission_id:0,file_path:l,symbol_id:u.id,type:"discovery",content:`Shadow Trace: Modified externally in ${t}`,confidence:.8,symbol_name:u.name,signature:u.signature,commit_sha:null}),kn.debug({symbol:u.name},"Logged ghost change"),n.push({from:"external",to:`${o}:${u.name}`,pattern:"git-delta",confidence:.8}))}}n.length>0&&this.hologramService.updateGhostBridges(n),kn.info("Shadow Trace complete.")}catch(i){kn.warn({err:i.message},"Shadow Trace failed: git diff error.")}}};F();import{execSync as ht}from"child_process";var Cn=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{ht(`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 ht(`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=ht(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
526
- `);for(let i of n){let[r,o]=i.split(" ");if(o){let l=this.getNote(o);l&&e.set(o,l)}}}catch{}return e}removeNote(e){try{ht(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{ht(`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{ht(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};N();var ft=_.child({module:"persistence-service"}),Re=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new Cn(e)}async syncMissionToGitNotes(e){let{missions:t,intentLogs:n}=k.getInstance(this.repoPath),i=t.findById(e);if(!i)throw new Error(`Mission ${e} not found`);if(!i.commit_sha){ft.warn({missionId:e},"Cannot sync mission without commit_sha");return}ft.info({missionId:e,commitSha:i.commit_sha},"Syncing mission to Git Notes");let r=t.getArtifacts(e),o=n.findByMission(e,1e3),l=o.find(p=>p.type==="adr"),c=o.filter(p=>p.type==="decision").map(p=>({content:p.content,symbol_name:p.symbol_name,created_at:p.created_at})),a={version:"1.0",mission:{name:i.name,goal:i.goal,status:i.status,strategy_graph:i.strategy_graph,git_branch:i.git_branch,commit_sha:i.commit_sha,parent_id:i.parent_id,verification_context:i.verification_context,outcome_contract:i.outcome_contract,created_at:i.created_at,updated_at:i.updated_at},artifacts:r,adr:l?l.content:null,decisions:c};this.gitNotes.addNote(i.commit_sha,JSON.stringify(a,null,2))}async syncAllToGitNotes(){let{missions:e}=k.getInstance(this.repoPath),t=e.findActive(),n=e.findRecentCompleted(10),i=[...t,...n];for(let r of i)try{await this.syncMissionToGitNotes(r.id)}catch(o){ft.error({missionId:r.id,error:o},"Failed to sync mission")}}async recoverFromGitNotes(){let e=this.gitNotes.listNotes(),{missions:t,intentLogs:n}=k.getInstance(this.repoPath),i=0,r=0;for(let[o,l]of e.entries())try{let c=JSON.parse(l);if(c.version!=="1.0")continue;if(t.findByCommitShas([o]).some(u=>u.name===c.mission.name)){ft.debug({commitSha:o,missionName:c.mission.name},"Mission already exists, skipping recovery");continue}let d=t.create({name:c.mission.name,goal:c.mission.goal,status:c.mission.status,strategy_graph:c.mission.strategy_graph,git_branch:c.mission.git_branch,commit_sha:o,parent_id:c.mission.parent_id,verification_context:c.mission.verification_context,outcome_contract:c.mission.outcome_contract});if(i++,c.adr&&(n.create({mission_id:Number(d),symbol_id:null,file_path:null,type:"adr",content:c.adr,confidence:1,symbol_name:null,signature:null,commit_sha:o}),r++),c.decisions&&c.decisions.length>0)for(let u of c.decisions)n.create({mission_id:Number(d),symbol_id:null,file_path:null,type:"decision",content:u.content,confidence:1,symbol_name:u.symbol_name,signature:null,commit_sha:o}),r++;ft.info({commitSha:o,missionName:c.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(c){ft.error({commitSha:o,error:c},"Failed to parse Git Note for recovery")}return{missionsRecovered:i,logsRecovered:r}}};F();Ot();async function Wr(s){let{repoPath:e,sinceCommit:t}=s;try{await j(e),new mt(e).analyzeGhostChanges(t);let i=new _e(e),r=i.detectAndRepairShifts(),o=i.syncLifecycle(),c=await new Re(e).recoverFromGitNotes(),{HologramService:a}=await Promise.resolve().then(()=>(dt(),Fr)),p=new a(e),d=ut(k.getInstance(e),e);p.updateTopography(d);let u=p.computeGravityZones();p.updateGravityZones(u);let m="Shadow Sync complete. Code changes indexed and intent logs updated.";return m+=`
527
- \u269B\uFE0F Hologram: Refreshed architectural map (${u.length} hotspots).`,r.repaired>0&&(m+=`
528
- \u2728 Nano-Repair: Fixed ${r.repaired} links.`),c.missionsRecovered>0&&(m+=`
529
- \u{1F9EC} Re-hydration: Recovered ${c.missionsRecovered} missions.`),{content:[{type:"text",text:m}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}async function Ur(s,e){let t=fc.resolve(s);await U(async()=>{le("Shadow Sync");let n=ue();n.start("Synchronizing intelligence lifecycle...");try{let i=await Wr({repoPath:t,sinceCommit:e.sinceCommit});n.stop("Sync complete."),i.isError?console.error(f.red(i.content[0].text)):(console.log(""),console.log(i.content[0].text),console.log(""))}catch(i){throw n.stop(`Sync failed: ${i.message}`),i}finally{await G(t)}})}Ot();F();N();dt();import Br from"path";F();Ot();dt();import Le from"path";async function jr(s){let{repoPath:e}=s;await j(e);let t=k.getInstance(e),n=ut(t,e),r=new de(e).getSnapshot(),o=[],l=[],c=Object.values(n.layers.Entry.topFiles).map(u=>u.path),a=new Set(Object.values(n.layers.Data.topFiles).map(u=>u.path));for(let u of c){let m=Le.isAbsolute(u)?u:Le.join(e,u),h=t.imports.findByFile(m);for(let b of h)b.resolved_path&&a.has(Le.relative(e,b.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${Le.relative(e,u)}\` directly imports Data layer \`${Le.relative(e,b.resolved_path)}\`. Should go through Logic.`)}let p=r.gravity?.hotspots||[];for(let u of p){let m=Dt(u.filePath,t);(m.layer==="Utility"||m.layer==="Unknown")&&u.gravity>50&&l.push(`\u{1F6A8} GRAVITY ANOMALY: \`${Le.relative(e,u.filePath)}\` has high gravity (${u.gravity.toFixed(0)}) but is classified as ${m.layer}. Consider promoting to Core Logic.`)}for(let u of c){let m=Le.isAbsolute(u)?u:Le.join(e,u),h=t.exports.findByFile(m);h.length>10&&l.push(`\u{1F388} ENTRY BLOAT: \`${Le.relative(e,u)}\` exports ${h.length} symbols. Entry handlers should be thin interfaces.`)}let d=`# \u{1F575}\uFE0F Architectural Scout Report
530
-
531
- `;return o.length===0&&l.length===0?d+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
530
+ ${a}
531
+ }`,S=await pr.parse(g,b);u.visitModule(S)}catch{let S=new pt,R=l;S.visit(a,R),u.calls=S.calls,u.apiCalls=S.apiCalls,u.imports=S.imports}else{let g=new pt;g.visit(a,l),u.calls=g.calls,u.apiCalls=g.apiCalls,u.imports=g.imports}}}else u=new pt,u.visit(a,l);_.info({file:ge.basename(i),calls:u.calls.size,apiCalls:u.apiCalls.length,depth:r},"Analyzed file");let m=u.apiCalls.slice(0,10);for(let b of m){if(o.count>=Pt)break;if(o.count++,b.method==="PUBSUB"){let R={type:"event_trigger",name:`PubSub Event: ${b.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(R);let w=n.exports.findByNameGlobal(b.url).concat(n.exports.findByMethodName(b.url));if(b.url.length>10){let v=b.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(v!==b.url){let k=n.exports.findByNameGlobal(v).concat(n.exports.findByMethodName(v));w.push(...k)}}let T=new Set;for(let v of w){if(T.has(v.file_path)||v.file_path===i)continue;if(T.add(v.file_path),o.count>=Pt)break;o.count++;let k={type:"subscriber",name:`${v.name} (${ge.basename(v.file_path)})`,path:ge.relative(t,v.file_path),line:v.start_line,details:"Potential Subscriber / Handler",children:[]};R.children.push(k),Mt.existsSync(v.file_path)&&!s.has(v.file_path)&&(s.add(v.file_path),await ut(v.file_path,k,t,n,s,r+1,o))}continue}let y={type:"api_call",name:`${b.method} ${b.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(y);let S=lr(n,b.url).slice(0,pc);for(let R of S){if(o.count>=Pt)break;o.count++;let w={type:"route",name:R.signature||"Route Handler",path:R.file_path,line:R.start_line,children:[]};if(y.children.push(w),Mt.existsSync(R.file_path)&&!s.has(R.file_path)&&(s.add(R.file_path),await ut(R.file_path,w,t,n,s,r+1,o)),R.capabilities)try{let T=JSON.parse(R.capabilities);if(T.handler){let[v,k]=T.handler.split("@");if(v){let x=v.split("\\").pop();if(x){let I=n.exports.findClassByName(x);if(I){let M=n.exports.findByNameAndFile(k||"",I.file_path),$,j=I.start_line;M.length>0&&($={start:M[0].start_line,end:M[0].end_line},j=M[0].start_line);let H={type:"component",name:`${x}${k?" :: "+k:""}`,path:ge.relative(t,I.file_path),line:j,details:"Controller Logic (Macro IR)",children:[]};w.children.push(H),s.has(I.file_path+(k?`:${k}`:""))||(s.add(I.file_path+(k?`:${k}`:"")),await ut(I.file_path,H,t,n,s,r+1,o,$))}}}}}catch{}}}let f=u.calls,h=Array.from(f).sort();for(let b of h)if(u.imports.has(b)){let y=u.imports.get(b);if(!y.startsWith(".")){if(["react","react-dom"].includes(y))continue;e.children.push({type:"function",name:b,details:`External: ${y}`,children:[]});continue}let g=Lt(y,i,t);if(g&&Mt.existsSync(g))if(s.has(g))e.children.push({type:"function",name:b,details:"Circular / Already Visited",path:ge.relative(t,g),children:[]});else{s.add(g);let S={type:"file",name:b,details:`Imported from ${ge.basename(g)}`,path:ge.relative(t,g),children:[]};e.children.push(S),await ut(g,S,t,n,s,r+1,o)}}else if(!["log","info","error","warn","print"].includes(b)){let y=n.exports.findByNameGlobal(b);if(y.length===0){let g=b.split(/(?:\.|->|::)+/);if(g.length>1){let S=g[g.length-1];uc.has(S)||(y=n.exports.findByMethodName(S))}}if(y.length>0){let g=y.find(R=>R.file_path===i),S=g||(y.length===1?y[0]:null);if(S){let R=`${S.file_path}:${S.name}`;if(!s.has(R)){s.add(R);let w={type:"component",name:b,details:`Resolved via global index${g?" (local)":""}`,path:ge.relative(t,S.file_path),line:S.start_line,children:[]};e.children.push(w),await ut(S.file_path,w,t,n,s,r+1,o,{start:S.start_line,end:S.end_line})}}}}}catch(a){_.error({filePath:i,error:a.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:a.message,children:[]})}}}async function dr(i,e){let t=$n.resolve(e.dir),n=$n.isAbsolute(i)?i:$n.resolve(t,i);await B(async()=>{le("Execution Trace");let s=de();s.start(`Tracing ${E.cyan(e.symbolName||$n.basename(n))}...`);try{let r=await ur({repoPath:t,filePath:n,symbolName:e.symbolName});s.stop("Trace complete."),r.isError?console.error(E.red(r.content[0].text)):se("Flow Results",r.content[0].text,"magenta")}catch(r){throw s.stop(`Trace failed: ${r.message}`),r}finally{await q(t)}})}import _c from"path";U();dt();P();import{execSync as Br}from"child_process";import Sc from"path";var kn=_.child({module:"shadow-trace"}),mt=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 ue(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=Br(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
532
+ `).filter(o=>o.trim()!=="");if(r.length===0)return;kn.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let c=Sc.join(this.repoPath,o),l=Br(`git diff -U0 ${t} -- ${o}`,{cwd:this.repoPath,encoding:"utf-8"}).matchAll(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/g);for(let p of l){let d=parseInt(p[2],10),u=this.exports.findAtLine(c,d);u&&(this.intentLogs.create({mission_id:0,file_path:c,symbol_id:u.id,type:"discovery",content:`Shadow Trace: Modified externally in ${t}`,confidence:.8,symbol_name:u.name,signature:u.signature,commit_sha:null}),kn.debug({symbol:u.name},"Logged ghost change"),n.push({from:"external",to:`${o}:${u.name}`,pattern:"git-delta",confidence:.8}))}}n.length>0&&this.hologramService.updateGhostBridges(n),kn.info("Shadow Trace complete.")}catch(s){kn.warn({err:s.message},"Shadow Trace failed: git diff error.")}}};U();import{execSync as ht}from"child_process";var Ln=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{ht(`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 ht(`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=ht(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
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{ht(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{ht(`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{ht(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};P();var ft=_.child({module:"persistence-service"}),ve=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new Ln(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){ft.warn({missionId:e},"Cannot sync mission without commit_sha");return}ft.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){ft.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(u=>u.name===a.mission.name)){ft.debug({commitSha:o,missionName:a.mission.name},"Mission already exists, skipping recovery");continue}let d=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(d),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 u of a.decisions)n.create({mission_id:Number(d),symbol_id:null,file_path:null,type:"decision",content:u.content,confidence:1,symbol_name:u.symbol_name,signature:null,commit_sha:o}),r++;ft.info({commitSha:o,missionName:a.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(a){ft.error({commitSha:o,error:a},"Failed to parse Git Note for recovery")}return{missionsRecovered:s,logsRecovered:r}}};U();Ot();async function zr(i){let{repoPath:e}=i;try{await z(e),new mt(e).analyzeGhostChanges();let n=new Te(e),s=n.detectAndRepairShifts(),r=n.syncLifecycle(),c=await new ve(e).recoverFromGitNotes(),{HologramService:a}=await Promise.resolve().then(()=>(dt(),Ur)),l=new a(e),p=je(C.getInstance(e),e);l.updateTopography(p);let d=l.computeGravityZones();l.updateGravityZones(d);let u="Shadow Sync complete. Code changes indexed and intent logs updated.";return u+=`
534
+ \u269B\uFE0F Hologram: Refreshed architectural map (${d.length} hotspots).`,s.repaired>0&&(u+=`
535
+ \u2728 Nano-Repair: Fixed ${s.repaired} links.`),c.missionsRecovered>0&&(u+=`
536
+ \u{1F9EC} Re-hydration: Recovered ${c.missionsRecovered} missions.`),{content:[{type:"text",text:u}]}}catch(t){return{content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}}}async function Gr(i,e){let t=_c.resolve(i);await B(async()=>{le("Shadow Sync");let n=de();n.start("Synchronizing intelligence lifecycle...");try{let s=await zr({repoPath:t});n.stop("Sync complete."),s.isError?console.error(E.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 q(t)}})}Ot();U();P();dt();import Jr from"path";U();Ot();dt();import Le from"path";async function qr(i){let{repoPath:e}=i;await z(e);let t=C.getInstance(e),n=je(t,e),r=new ue(e).getSnapshot(),o=[],c=[],a=Object.values(n.layers.Entry.topFiles).map(u=>u.path),l=new Set(Object.values(n.layers.Data.topFiles).map(u=>u.path));for(let u of a){let m=Le.isAbsolute(u)?u:Le.join(e,u),f=t.imports.findByFile(m);for(let h of f)h.resolved_path&&l.has(Le.relative(e,h.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${Le.relative(e,u)}\` directly imports Data layer \`${Le.relative(e,h.resolved_path)}\`. Should go through Logic.`)}let p=r.gravity?.hotspots||[];for(let u of p){let m=Dt(u.filePath,t);(m.layer==="Utility"||m.layer==="Unknown")&&u.gravity>50&&c.push(`\u{1F6A8} GRAVITY ANOMALY: \`${Le.relative(e,u.filePath)}\` has high gravity (${u.gravity.toFixed(0)}) but is classified as ${m.layer}. Consider promoting to Core Logic.`)}for(let u of a){let m=Le.isAbsolute(u)?u:Le.join(e,u),f=t.exports.findByFile(m);f.length>10&&c.push(`\u{1F388} ENTRY BLOAT: \`${Le.relative(e,u)}\` exports ${f.length} symbols. Entry handlers should be thin interfaces.`)}let d=`# \u{1F575}\uFE0F Architectural Scout Report
537
+
538
+ `;return o.length===0&&c.length===0?d+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
532
539
  `:(o.length>0&&(d+=`## \u274C Structural Violations
533
540
  `,o.forEach(u=>d+=`- ${u}
534
541
  `),d+=`
535
- `),l.length>0&&(d+=`## \u26A0\uFE0F Architectural Warnings
536
- `,l.forEach(u=>d+=`- ${u}
542
+ `),c.length>0&&(d+=`## \u26A0\uFE0F Architectural Warnings
543
+ `,c.forEach(u=>d+=`- ${u}
537
544
  `),d+=`
538
- `)),{content:[{type:"text",text:d}]}}async function zr(s,e,t){let n=e?Br.resolve(process.cwd(),e):process.cwd();if(s==="init"){_.info('Running full initialization (same as "index --force")...'),await j(n,void 0,!0,!0);return}if(s==="tree"){_.info('For tree view, please use the "tree" command.');return}if(s==="topography"){await j(n);let i=k.getInstance(n),r=ut(i,n);console.log(`
539
- \u{1F3D7}\uFE0F Architecture Summary for ${Br.basename(n)}
545
+ `)),{content:[{type:"text",text:d}]}}async function Yr(i,e,t){let n=e?Jr.resolve(process.cwd(),e):process.cwd();if(i==="init"){_.info('Running full initialization (same as "index --force")...'),await z(n,void 0,!0,!0);return}if(i==="tree"){_.info('For tree view, please use the "tree" command.');return}if(i==="topography"){await z(n);let s=C.getInstance(n),r=je(s,n);console.log(`
546
+ \u{1F3D7}\uFE0F Architecture Summary for ${Jr.basename(n)}
540
547
  `),console.log(`Detected Pattern: **${r.pattern}** (Confidence: ${r.patternConfidence.toFixed(0)}%)`),r.insights.length>0&&(console.log(`
541
- Insights:`),r.insights.forEach(a=>console.log(`- ${a}`))),console.log(`
542
- Layer Distribution:`);let o=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],l=Object.values(r.layers).reduce((a,p)=>a+p.count,0),c=a=>{switch(a){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(a=>{let p=r.layers[a],d=l>0?(p.count/l*100).toFixed(1):"0.0";console.log(`${c(a)} ${a.padEnd(14)} | ${p.count.toString().padStart(5)} files | ${d}%`)}),console.log(`
543
- Top Files by Layer:`),o.forEach(a=>{let p=r.layers[a];p.count!==0&&(console.log(`
544
- ${c(a)} ${a}`),p.topFiles.forEach(d=>{console.log(` - ${d.path} (${d.confidence}% conf)`),d.signals.length>0&&console.log(` \u2514\u2500 ${d.signals.slice(0,1).join(", ")}`)}))});return}if(s==="scout"){let i=await jr({repoPath:n});console.log(i.content[0].text);return}if(s==="hologram"){let i=new de(n);console.log(JSON.stringify(i.getSnapshot(),null,2));return}_.error(`Unknown recon mode: ${s}. Available: init, topography, scout, hologram`)}import Ht from"path";F();var Ft=class{static extractSnippet(e,t,n=300){if(!e||!t)return"";let i=t.toLowerCase().split(/\s+/).filter(u=>u.length>2&&!["the","and","for","with","from"].includes(u));if(i.length===0)return e.slice(0,n)+"...";let r=e.split(`
545
- `),o=new Array(r.length).fill(0);for(let u=0;u<r.length;u++){let m=r[u].toLowerCase(),h=0,b=0;for(let E of i)m.includes(E)&&(h++,b++);(m.includes("export ")||m.includes("class ")||m.includes("function ")||m.includes("interface "))&&(h+=1),o[u]=b*10+h}let l=0,c=-1,a=5;for(let u=0;u<=r.length-a;u++){let m=0;for(let h=0;h<a;h++)m+=o[u+h];m>c&&(c=m,l=u)}if(c<=0)return e.slice(0,n).trim()+"...";let d=r.slice(l,l+a).join(`
546
- `).trim();return l>0&&(d=`...
547
- `+d),l+a<r.length&&(d=d+`
548
- ...`),d.length>n?d.slice(0,n)+"...":d}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 i=0,r=e.toLowerCase();for(let o of n)if(r.includes(o)){i+=1;let l=new RegExp(`\\b${o}`,"gi"),c=r.match(l);c&&(i+=Math.min(c.length*.2,2)),new RegExp(`(class|function|export|interface|enum|type)\\s+${o}`,"i").test(e)&&(i+=1.5)}return i/n.length}};F();N();var Ue=_.child({module:"clean-sweep"}),xi=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=k.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){Ue.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();Ue.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++,Ue.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,Ue.debug({logId:o.id},"Deleted orphaned log"));let i=this.intentLogs.findLogsForMissingFiles();for(let o of i)this.intentLogs.delete(o.id),e++;let r=this.intentLogs.findRecentDecisionActivity(1e3).length;return Ue.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},Ri=class{lambda;constructor(e=.01){this.lambda=e}calculateScore(e,t){let i=(Math.floor(Date.now()/1e3)-t)/(3600*24),r=Math.exp(-this.lambda*i);return e*r}scoreResults(e){return e.map(t=>({...t,decayed_score:this.calculateScore(t.score,t.created_at)}))}},Ti=class{missions;constructor(e){let{missions:t}=k.getInstance(e);this.missions=t}findColdMissions(){let e=Math.floor(Date.now()/1e3)-604800,t=this.missions.findColdMissions(e,10);return Ue.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},Ln=class{pruner;scorer;compactor;constructor(e){this.pruner=new xi(e),this.scorer=new Ri,this.compactor=new Ti(e)}runMaintenance(){Ue.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return Ue.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};F();N();var Gr=_.child({module:"lineage-service"}),tt=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=Gs(this.repoPath,e);if(t.length===0)return[];let{missions:n}=k.getInstance(this.repoPath),r=n.findByCommitShas(t).map(o=>o.id);return r.length>0&&Gr.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return Gr.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var gc={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},$e=class{static classify(e,t){let n=e.toLowerCase();if(t?.content){let i=t.content;if(i.includes("describe(")||i.includes("test(")||i.includes("it(")||i.includes("expect(")||i.includes('from "@jest/globals"')||i.includes('from "vitest"'))return"Virtual"}return t?.exports&&(t.exports.some(r=>r.kind==="ClassDeclaration"||r.kind==="Class")||t.exports.length>5),n.includes("/dist/")||n.includes("/build/")||n.includes("/.generated/")||n.includes("/node_modules/")||n.endsWith(".map")||n.endsWith(".log")?"Phantom":n.includes("/test/")||n.includes("/tests/")||n.includes("/__tests__/")||n.includes("/__mocks__/")||n.includes(".spec.")||n.includes(".test.")||n.includes("/e2e/")||n.includes("/test-utils/")?"Virtual":n.includes("/examples/")||n.includes("/fixtures/")||n.includes("/mocks/")||n.includes("/stories/")||n.includes("/samples/")||n.includes("/docs/")?"Intel":n.includes("/src/")||n.includes("/lib/")||n.includes("/app/")||n.includes("/core/")||n.includes("/logic/")||n.includes("/domain/")||n.includes("/services/")||n.includes("/controllers/")||n.includes("/handlers/")||n.includes("/repositories/")||n.includes("/models/")||n.includes("/packages/")&&!n.includes("/packages/config/")||n.includes("/backends/")||t?.exports&&(t.exports.some(i=>i.kind==="ClassDeclaration"||i.kind==="Class")||t.exports.length>5)?"Solid":"Liquid"}static mapClassificationToTier(e){let t=e.toLowerCase();return t==="service"||t==="repository"||t==="model"||t==="controller"||t==="handler"||t==="component"||t==="hook"||t==="titanium"||t==="solid"?"Solid":t==="test"||t==="iron"||t==="virtual"?"Virtual":t==="lead"||t==="intel"?"Intel":t==="ghost"||t==="error"||t==="phantom"?"Phantom":"Liquid"}static getMultiplier(e,t){let n=t?this.mapClassificationToTier(t):this.classify(e);return gc[n]}};N();function yc(s,e){let t=[];for(let n=0;n<=e.length;n++)t[n]=[n];for(let n=0;n<=s.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=s.length;i++)e.charAt(n-1)===s.charAt(i-1)?t[n][i]=t[n-1][i-1]:t[n][i]=Math.min(t[n-1][i-1]+1,t[n][i-1]+1,t[n-1][i]+1);return t[e.length][s.length]}function bc(s,e){let t=yc(s.toLowerCase(),e.toLowerCase()),n=Math.max(s.length,e.length);return Math.round((n-t)/n*100)}function qr(s){let e=[],t="";for(let n=0;n<s.length;n++){let i=s[n],r=i>="A"&&i<="Z",o=i>="a"&&i<="z";r&&t.length>0?(e.push(t),t=i):o||r?t+=i:t.length>0&&(e.push(t),t="")}return t.length>0&&e.push(t),e}function Ec(s,e){let t=qr(e),n=s.toLowerCase();if(t.map(o=>o[0].toLowerCase()).join("")===n)return!0;let r=0;for(let o of t){if(r>=s.length)break;let l=o.toLowerCase();if(l.startsWith(n.slice(r))){r=s.length;break}l[0]===n[r]&&r++}return r===s.length}function Sc(s,e){return qr(e).map(i=>i[0].toLowerCase()).join("")===s.toLowerCase()}function _c(s,e){let t=s.toLowerCase(),n=e.toLowerCase();if(s===e)return{matchType:"exact",score:100};if(t===n)return{matchType:"exact-case-insensitive",score:98};if(n.startsWith(t))return{matchType:"prefix",score:90+s.length/e.length*8};if(n.endsWith(t))return{matchType:"suffix",score:80+s.length/e.length*8};if(n.includes(t)){let r=s.length/e.length,o=n.indexOf(t)/e.length;return{matchType:"substring",score:70+r*10-o*5}}return Sc(s,e)?{matchType:"acronym",score:75}:Ec(s,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:bc(s,e)*.6}}function $n(s,e,t=50,n=5){let i=[];for(let r of e){let{matchType:o,score:l}=_c(s,r);if(l>=t){let a={exact:1e3,"exact-case-insensitive":900,prefix:800,suffix:700,substring:600,acronym:550,"camel-case":500,levenshtein:100}[o]+l;i.push({match:r,score:l,matchType:o,rank:a})}}return i.sort((r,o)=>o.rank!==r.rank?o.rank-r.rank:o.score!==r.score?o.score-r.score:r.match.length-o.match.length),i.slice(0,n)}dt();var je=class s{constructor(e){this.repoPath=e}get filesRepo(){return k.getInstance(this.repoPath).files}get exportsRepo(){return k.getInstance(this.repoPath).exports}static normalizeFileType(e){if(e==null)return;let t=Array.isArray(e)?e:e.split(",").map(n=>n.trim().replace(/^\./,""));return t.filter(Boolean).length?t:void 0}static matchesFilters(e,t,n,i){if(t.fileType?.length){let r=e.replace(/^.*\./,"").toLowerCase();if(!t.fileType.some(o=>o.toLowerCase()===r))return!1}if(t.layer!=null||t.excludeLayers&&t.excludeLayers.length>0){let r=i!=null?$e.mapClassificationToTier(i):$e.classify(e);if(t.layer!=null&&r!==t.layer||t.excludeLayers?.includes(r))return!1}if(t.dateModifiedAfter!=null||t.dateModifiedBefore!=null){if(n==null)return!1;let r=n>1e10?n/1e3:n;if(t.dateModifiedAfter!=null&&r<t.dateModifiedAfter||t.dateModifiedBefore!=null&&r>t.dateModifiedBefore)return!1}return!0}async searchByPath(e,t,n,i,r){let o=e.toLowerCase().split(/\s+/).filter(Boolean),l=this.filesRepo.findByPathKeywords(o,Math.min((t??50)*(r?oe.FILTERED_QUERY_LIMIT_MULTIPLIER:1),ot.MAX_LIMIT));r&&(l=l.filter(p=>s.matchesFilters(p.path,i,p.mtime,p.classification)),l=l.slice(0,t??50));let c=p=>p.replace(this.repoPath,"").replace(/^\//,"");return{content:[{type:"text",text:l.length===0?`No indexed files match path/filename: "${e}".
548
+ 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],d=c>0?(p.count/c*100).toFixed(1):"0.0";console.log(`${a(l)} ${l.padEnd(14)} | ${p.count.toString().padStart(5)} files | ${d}%`)}),console.log(`
550
+ Top Files by Layer:`),o.forEach(l=>{let p=r.layers[l];p.count!==0&&(console.log(`
551
+ ${a(l)} ${l}`),p.topFiles.forEach(d=>{console.log(` - ${d.path} (${d.confidence}% conf)`),d.signals.length>0&&console.log(` \u2514\u2500 ${d.signals.slice(0,1).join(", ")}`)}))});return}if(i==="scout"){let s=await qr({repoPath:n});console.log(s.content[0].text);return}if(i==="hologram"){let s=new ue(n);console.log(JSON.stringify(s.getSnapshot(),null,2));return}_.error(`Unknown recon mode: ${i}. Available: init, topography, scout, hologram`)}import jt from"path";U();var Ft=class{static extractSnippet(e,t,n=300){if(!e||!t)return"";let s=t.toLowerCase().split(/\s+/).filter(u=>u.length>2&&!["the","and","for","with","from"].includes(u));if(s.length===0)return e.slice(0,n)+"...";let r=e.split(`
552
+ `),o=new Array(r.length).fill(0);for(let u=0;u<r.length;u++){let m=r[u].toLowerCase(),f=0,h=0;for(let b of s)m.includes(b)&&(f++,h++);(m.includes("export ")||m.includes("class ")||m.includes("function ")||m.includes("interface "))&&(f+=1),o[u]=h*10+f}let c=0,a=-1,l=5;for(let u=0;u<=r.length-l;u++){let m=0;for(let f=0;f<l;f++)m+=o[u+f];m>a&&(a=m,c=u)}if(a<=0)return e.slice(0,n).trim()+"...";let d=r.slice(c,c+l).join(`
553
+ `).trim();return c>0&&(d=`...
554
+ `+d),c+l<r.length&&(d=d+`
555
+ ...`),d.length>n?d.slice(0,n)+"...":d}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}};U();P();var Ue=_.child({module:"clean-sweep"}),Rs=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=C.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){Ue.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();Ue.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++,Ue.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,Ue.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 Ue.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},vs=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)}))}},ws=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 Ue.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},Nn=class{pruner;scorer;compactor;constructor(e){this.pruner=new Rs(e),this.scorer=new vs,this.compactor=new ws(e)}runMaintenance(){Ue.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return Ue.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};U();P();var Vr=_.child({module:"lineage-service"}),nt=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=Vi(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&&Vr.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return Vr.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var xc={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},be=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 xc[n]}};P();function Tc(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 Rc(i,e){let t=Tc(i.toLowerCase(),e.toLowerCase()),n=Math.max(i.length,e.length);return Math.round((n-t)/n*100)}function Qr(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 vc(i,e){let t=Qr(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 wc(i,e){return Qr(e).map(s=>s[0].toLowerCase()).join("")===i.toLowerCase()}function Ic(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 wc(i,e)?{matchType:"acronym",score:75}:vc(i,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:Rc(i,e)*.6}}function Ht(i,e,t=50,n=5){let s=[];for(let r of e){let{matchType:o,score:c}=Ic(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)}dt();var Be=class i{constructor(e){this.repoPath=e}get filesRepo(){return C.getInstance(this.repoPath).files}get exportsRepo(){return C.getInstance(this.repoPath).exports}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?be.mapClassificationToTier(s):be.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?ae.FILTERED_QUERY_LIMIT_MULTIPLIER:1),at.MAX_LIMIT));r&&(a=a.filter(d=>i.matchesFilters(d.path,s,d.mtime,d.classification)),a=a.slice(0,t??50));let l=d=>d.replace(this.repoPath,"").replace(/^\//,"");if(a.length===0)return{content:[{type:"text",text:`No indexed files match path/filename: "${e}".
556
+
557
+ If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};if(o){let u=new ue(this.repoPath).getSection("gravity"),m=new Map;if(u?.hotspots)for(let b of u.hotspots){let y=m.get(b.filePath)||0;m.set(b.filePath,y+b.gravity)}let f=a.map(b=>{let y=m.get(b.path)||0,g=b.classification?be.mapClassificationToTier(b.classification):be.classify(b.path);return{...b,gravity:y,layer:g}});return f.sort((b,y)=>y.gravity-b.gravity),{content:[{type:"text",text:`# Resolved paths: "${e}" (Ranked by Gravity)
558
+
559
+ ${f.length} file(s):
549
560
 
550
- If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`:`# Resolved paths: "${e}"
561
+ `+f.map((b,y)=>{let g=b.gravity>50?" \u269B\uFE0F":b.gravity>0?" \u2022":"",S=b.gravity>0?` [G:${Math.round(b.gravity)}]`:"";return`${y+1}. \`${l(b.path)}\` (${b.layer})${g}${S}`}).join(`
562
+ `)+`
563
+
564
+ > **Legend**: \u269B\uFE0F = High-gravity hotspot (>50), \u2022 = Has gravity, G = Gravity score`}]}}return{content:[{type:"text",text:`# Resolved paths: "${e}"
551
565
 
552
- ${l.length} file(s):
566
+ ${a.length} file(s):
553
567
 
554
- `+l.map((p,d)=>`${d+1}. \`${c(p.path)}\`${p.classification?` (${p.classification})`:""}`).join(`
555
- `)}]}}async searchByConcept(e,t,n,i,r,o=!1){_.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let l=await ii(e),c=y=>y.replace(this.repoPath,"").replace(/^\//,"");if(l){let y=await this.findConceptMatches(e,l,i,r,t*2);if(y.length>0){let S=y.length,w=y.slice(n,n+t),T=n+t<S?`
556
- > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",I=o?`
557
- > _Compact mode: snippets omitted_`:S>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",x=`# Semantic Concept Search: "${e}"
568
+ `+a.map((d,u)=>`${u+1}. \`${l(d.path)}\`${d.classification?` (${d.classification})`:""}`).join(`
569
+ `)}]}}async searchByConcept(e,t,n,s,r,o=!1){_.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let c=await rs(e),a=g=>g.replace(this.repoPath,"").replace(/^\//,"");if(c){let g=await this.findConceptMatches(e,c,s,r,t*2,0);if(g.length>0){let S=g.length,R=g.slice(n,n+t),T=n+t<S?`
570
+ > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",v=o?`
571
+ > _Compact mode: snippets omitted_`:S>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",k=`# Semantic Concept Search: "${e}"
558
572
 
559
- Showing ${w.length} of ${S} relevant file(s) (offset: ${n}, limit: ${t})${T}${I}
573
+ Showing ${R.length} of ${S} relevant file(s) (offset: ${n}, limit: ${t})${T}${v}
560
574
 
561
- `,R=new de(this.repoPath).getSection("gravity"),v=new Map;if(R?.hotspots)for(let L of R.hotspots)v.set(L.filePath,L.gravity);return{content:[{type:"text",text:o?x+w.map((L,H)=>{let B=c(L.path),ne=Math.round((L.decayedScore||0)*100),D=v.get(L.path)?" \u269B\uFE0F":"";return`${n+H+1}. \`${B}\`${D} (${ne}%) - ${L.summary||"No summary"}`}).join(`
562
- `):x+w.map((L,H)=>{let B=c(L.path),ne=Math.round((L.decayedScore||0)*100),W=v.get(L.path),D=W?" \u269B\uFE0F **CORE**":"",M=W&&W>50?`
563
- > \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${W.toFixed(0)}). Modifications may have significant architectural impact.`:"";return`## ${n+H+1}. ${B}${D} (${ne}% Match)
564
- > **Rationale**: ${L.rationale}${M}
575
+ `,x=new ue(this.repoPath).getSection("gravity"),I=new Map;if(x?.hotspots)for(let $ of x.hotspots)I.set($.filePath,$.gravity);return{content:[{type:"text",text:o?k+R.map(($,j)=>{let H=a($.path),N=Math.round(($.decayedScore||0)*100),A=I.get($.path)?" \u269B\uFE0F":"";return`${n+j+1}. \`${H}\`${A} (${N}%) - ${$.summary||"No summary"}`}).join(`
576
+ `):k+R.map(($,j)=>{let H=a($.path),N=Math.round(($.decayedScore||0)*100),L=I.get($.path),A=L?" \u269B\uFE0F **CORE**":"",D=L&&L>50?`
577
+ > \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${L.toFixed(0)}). Modifications may have significant architectural impact.`:"";return`## ${n+j+1}. ${H}${A} (${N}% Match)
578
+ > **Rationale**: ${$.rationale}${D}
565
579
 
566
- `+(L.snippet?`**Matched Snippet**:
580
+ `+($.snippet?`**Matched Snippet**:
567
581
  \`\`\`typescript
568
- ${L.snippet}
582
+ ${$.snippet}
569
583
  \`\`\`
570
584
 
571
- `:"")+`**Summary**: ${L.summary||"No summary available"}
585
+ `:"")+`**Summary**: ${$.summary||"No summary available"}
572
586
  `}).join(`
573
- `)}]}}}let a=e.replace(/[^\w\s]/g," ").trim(),p=this.filesRepo.findFts(a,(t+n)*(r?oe.FILTERED_QUERY_LIMIT_MULTIPLIER:1));r&&(p=p.filter(y=>s.matchesFilters(y.path,i,y.mtime,y.classification)));let d=p.slice(n,n+t);if(d.length===0&&n===0){let y=this.filesRepo.getStats(),S=e.toLowerCase().split(/\s+/),w=this.filesRepo.findByPathKeywords(S,t);return r&&(w=w.filter(C=>s.matchesFilters(C.path,i,C.mtime,C.classification))),w.length>0?{content:[{type:"text",text:`# Concept Search: "${e}"
587
+ `)}]}}}let l=e.replace(/[^\w\s]/g," ").trim(),p=this.filesRepo.findFts(l,(t+n)*(r?ae.FILTERED_QUERY_LIMIT_MULTIPLIER:1));r&&(p=p.filter(g=>i.matchesFilters(g.path,s,g.mtime,g.classification)));let d=p.slice(n,n+t);if(d.length===0&&n===0){let g=this.filesRepo.getStats(),S=e.toLowerCase().split(/\s+/),R=this.filesRepo.findByPathKeywords(S,t);return r&&(R=R.filter(w=>i.matchesFilters(w.path,s,w.mtime,w.classification))),R.length>0?{content:[{type:"text",text:`# Concept Search: "${e}"
574
588
 
575
- \u26A0\uFE0F No semantic matches in file summaries (${y.withSummary}/${y.total} indexed).
589
+ \u26A0\uFE0F No semantic matches in file summaries (${g.withSummary}/${g.total} indexed).
576
590
 
577
- Found ${w.length} file(s) with matching paths:
591
+ Found ${R.length} file(s) with matching paths:
578
592
 
579
- `+w.map((T,I)=>`${I+1}. \`${c(T.path)}\` (${T.classification||"Unknown"})`).join(`
593
+ `+R.map((T,v)=>`${v+1}. \`${a(T.path)}\` (${T.classification||"Unknown"})`).join(`
580
594
  `)}]}:{content:[{type:"text",text:`No files found matching concept: "${e}"
581
595
 
582
- Summary Stats: ${y.withSummary}/${y.total} summaries.
596
+ Summary Stats: ${g.withSummary}/${g.total} summaries.
583
597
 
584
- Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}let u=p.length,h=n+t<u?`
585
- > Use \`offset: ${n+t}\` for more results.`:"",b=o?`
586
- > _Compact mode_`:u>20&&!o?"\n> \u{1F4A1} Use `compact: true` to reduce output size.":"",E=`# Concept Search (FTS Fallback): "${e}"
598
+ Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}let u=p.length,f=n+t<u?`
599
+ > Use \`offset: ${n+t}\` for more results.`:"",h=o?`
600
+ > _Compact mode_`:u>20&&!o?"\n> \u{1F4A1} Use `compact: true` to reduce output size.":"",b=`# Concept Search (FTS Fallback): "${e}"
587
601
 
588
- Showing ${d.length} of ${u} relevant file(s)${h}${b}
602
+ Showing ${d.length} of ${u} relevant file(s)${f}${h}
589
603
 
590
- `;return{content:[{type:"text",text:o?E+d.map((y,S)=>`${n+S+1}. \`${c(y.path)}\``).join(`
591
- `):E+d.map((y,S)=>`## ${n+S+1}. ${c(y.path)}
604
+ `;return{content:[{type:"text",text:o?b+d.map((g,S)=>`${n+S+1}. \`${a(g.path)}\``).join(`
605
+ `):b+d.map((g,S)=>`## ${n+S+1}. ${a(g.path)}
592
606
 
593
- **Summary**: ${y.summary||"No summary available"}
607
+ **Summary**: ${g.summary||"No summary available"}
594
608
  `).join(`
595
- `)}]}}async searchBySymbol(e,t,n,i,r){let o=e.toLowerCase(),l=x=>x.replace(this.repoPath,"").replace(/^\//,""),c;try{c=this.exportsRepo.findFts(`"${e}" OR ${e}*`,t+50)}catch{c=this.exportsRepo.findByPartialName(e,t+50)}if(c.length===0){let x=this.exportsRepo.getAllNames(5e3),$=$n(e,x,50,5);if($.length>0){let R=$.map(v=>` \u2022 \`${v.match}\` (${Math.round(v.score)}% ${v.matchType} match)`).join(`
609
+ `)}]}}async searchBySymbol(e,t,n,s,r,o="any"){let c=e.toLowerCase(),a=x=>x.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 x=this.exportsRepo.getAllNames(5e3),I=e.trim().split(/\s+/).filter($=>$.length>0);if(I.length>1){let $=new Map;for(let H of I){let N=Ht(H,x,40,20);for(let L of N){let A=$.get(L.match);A?(A.terms.push(H),A.bestScore=Math.max(A.bestScore,L.score)):$.set(L.match,{terms:[H],bestScore:L.score})}}let j=Array.from($.entries()).sort((H,N)=>N[1].terms.length!==H[1].terms.length?N[1].terms.length-H[1].terms.length:N[1].bestScore-H[1].bestScore).slice(0,10);if(j.length>0){let H=j.map(([N,L])=>{let A=L.terms.join(", ");return` \u2022 \`${N}\` (matches: ${A}, ${Math.round(L.bestScore)}%)`}).join(`
610
+ `);return{content:[{type:"text",text:`No symbols found matching all terms: "${e}"
611
+
612
+ **Partial matches:**
613
+ ${H}
614
+
615
+ \u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let $=Ht(e,x,50,5);if($.length>0){let j=$.map(H=>` \u2022 \`${H.match}\` (${Math.round(H.score)}% ${H.matchType} match)`).join(`
596
616
  `);return{content:[{type:"text",text:`No symbols found matching: "${e}"
597
617
 
598
618
  **Did you mean?**
599
- ${R}
619
+ ${j}
600
620
 
601
- \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}"
621
+ \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}"
602
622
 
603
- \u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(c=c.filter(x=>{let $=this.filesRepo.findByPath(x.file_path);return s.matchesFilters(x.file_path,i,$?.mtime,$?.classification)}));let a=new tt(this.repoPath),p=new de(this.repoPath),d=a.getAncestorMissionIds(),u=se(this.repoPath)||void 0,m=this.exportsRepo.getGravityMap(d,u),h=p.getSection("gravity"),b=new Map;if(h?.hotspots)for(let x of h.hotspots)b.set(`${x.filePath}::${x.symbol}`,x.gravity);let E="\u{1F525}",g="\u26A1",y="\u269B\uFE0F",S=c.map((x,$)=>{let R=m[x.id],v=b.get(`${x.file_path}::${x.name}`),P=this.filesRepo.findByPath(x.file_path),L=$e.getMultiplier(x.file_path,P?.classification),H=(oe.SCORE_BASE-$)*L;R&&(H+=R.score*oe.SCORE_BASE),v&&(H+=v*oe.SCORE_BASE*oe.GRAVITY_STRUCTURAL_WEIGHT),x.name.toLowerCase()===o&&(H+=oe.EXACT_MATCH_BONUS*L);let B=P?.mtime;if(B!=null){let W=B>1e10?B/1e3:B,D=(Date.now()/1e3-W)/ci.SECONDS_PER_DAY;D<oe.RECENT_FILE_THRESHOLD_DAYS?H+=oe.RECENT_FILE_BOOST:D<oe.OLDER_FILE_THRESHOLD_DAYS&&(H+=oe.OLDER_FILE_BOOST)}let ne=[];return R&&ne.push(...R.reasons),v&&ne.push(`Structural Hotspot (Gravity: ${v.toFixed(1)})`),{...x,activeGravity:R,structuralGravity:v,sortScore:H,reasons:ne}}).sort((x,$)=>$.sortScore-x.sortScore).slice(n,n+t),w=c.length,C=n+t<w,T=S.map((x,$)=>{let R=l(x.file_path),v=this.filesRepo.getContent(x.file_path),P="";if(v){let B=v.split(`
604
- `);P=B.slice(Math.max(0,x.start_line-2),Math.min(B.length,x.start_line+3)).join(`
605
- `).trim()}let L=[];x.activeGravity&&(x.activeGravity.reasons.some(B=>B.includes("Working Set"))?L.push(E):x.activeGravity.reasons.some(B=>B.includes("Recent Intent"))&&L.push(g)),x.structuralGravity&&L.push(y);let H=L.length>0?` ${L.join("")}`:"";return{relPath:R,name:x.name,kind:x.kind,signature:x.signature,line:x.start_line,snippet:P,badgeStr:H,gravityReasons:x.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
623
+ \u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(x=>{let I=this.filesRepo.findByPath(x.file_path);return i.matchesFilters(x.file_path,s,I?.mtime,I?.classification)}));let d=new nt(this.repoPath),u=new ue(this.repoPath),m=d.getAncestorMissionIds(),f=re(this.repoPath)||void 0,h=this.exportsRepo.getGravityMap(m,f),b=u.getSection("gravity"),y=new Map;if(b?.hotspots)for(let x of b.hotspots)y.set(`${x.filePath}::${x.symbol}`,x.gravity);let g="\u{1F525}",S="\u26A1",R="\u269B\uFE0F",w=p.map((x,I)=>{let M=h[x.id],$=y.get(`${x.file_path}::${x.name}`),j=this.filesRepo.findByPath(x.file_path),H=be.getMultiplier(x.file_path,j?.classification),N=(ae.SCORE_BASE-I)*H;M&&(N+=M.score*ae.SCORE_BASE),$&&(N+=$*ae.SCORE_BASE*ae.GRAVITY_STRUCTURAL_WEIGHT),x.name.toLowerCase()===c&&(N+=ae.EXACT_MATCH_BONUS*H);let L=j?.mtime;if(L!=null){let D=L>1e10?L/1e3:L,te=(Date.now()/1e3-D)/ps.SECONDS_PER_DAY;te<ae.RECENT_FILE_THRESHOLD_DAYS?N+=ae.RECENT_FILE_BOOST:te<ae.OLDER_FILE_THRESHOLD_DAYS&&(N+=ae.OLDER_FILE_BOOST)}let A=[];return M&&A.push(...M.reasons),$&&A.push(`Structural Hotspot (Gravity: ${$.toFixed(1)})`),{...x,activeGravity:M,structuralGravity:$,sortScore:N,reasons:A}}).sort((x,I)=>I.sortScore-x.sortScore).slice(n,n+t),T=p.length,v=n+t<T,k=w.map((x,I)=>{let M=a(x.file_path),$=this.filesRepo.getContent(x.file_path),j="";if($){let L=$.split(`
624
+ `);j=L.slice(Math.max(0,x.start_line-2),Math.min(L.length,x.start_line+3)).join(`
625
+ `).trim()}let H=[];x.activeGravity&&(x.activeGravity.reasons.some(L=>L.includes("Working Set"))?H.push(g):x.activeGravity.reasons.some(L=>L.includes("Recent Intent"))&&H.push(S)),x.structuralGravity&&H.push(R);let N=H.length>0?` ${H.join("")}`:"";return{relPath:M,name:x.name,kind:x.kind,signature:x.signature,line:x.start_line,snippet:j,badgeStr:N,gravityReasons:x.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
606
626
 
607
- Showing ${T.length} matching symbol(s)${C?` (use offset=${n+t} for more)`:""}:
627
+ Showing ${k.length} matching symbol(s)${v?` (use offset=${n+t} for more)`:""}:
608
628
 
609
- `+T.map((x,$)=>{let R=`## ${n+$+1}. \`${x.name}\` (${x.kind})${x.badgeStr}
629
+ `+k.map((x,I)=>{let M=`## ${n+I+1}. \`${x.name}\` (${x.kind})${x.badgeStr}
610
630
  **File**: \`${x.relPath}:${x.line}\`
611
- `;return x.gravityReasons&&(R+=`> *${x.gravityReasons.join(", ")}*
612
- `),x.signature&&(R+=`**Signature**: \`${x.signature}\`
613
- `),x.snippet&&(R+=`
631
+ `;return x.gravityReasons&&(M+=`> *${x.gravityReasons.join(", ")}*
632
+ `),x.signature&&(M+=`**Signature**: \`${x.signature}\`
633
+ `),x.snippet&&(M+=`
614
634
  \`\`\`typescript
615
635
  ${x.snippet}
616
636
  \`\`\`
617
- `),R}).join(`
618
- `)}]}}async findConceptMatches(e,t,n,i,r,o=0){let l=se(this.repoPath)||void 0;if(!t)return[];let c=this.filesRepo.findWithEmbeddings(),p=new Ln(this.repoPath).getScorer(),u=new tt(this.repoPath).getAncestorMissionIds(),m=[];for(let h of c)try{let b=JSON.parse(h.embedding),E=ri(t,b),g=this.filesRepo.getContent(h.path),y=oe.ENABLE_LEXICAL_SCORING&&g?Ft.calculateLexicalScore(g,e):0,S=y>0?.1:.18;if(E>S){if(i&&!s.matchesFilters(h.path,n,h.mtime,h.classification))continue;let w=h.mtime>2e9?Math.floor(h.mtime/1e3):h.mtime,C=Math.floor(Date.now()/1e3)-ci.SECONDS_PER_YEAR,T=$e.getMultiplier(h.path,h.classification),I=p.calculateScore(E,w||C);I*=T;let $=this.filesRepo.getGravityMap(u,l)[h.path],R=h.classification?$e.mapClassificationToTier(h.classification):$e.classify(h.path,{content:g??void 0}),v=`Similarity: ${(E*100).toFixed(0)}%, Tier: ${R}${T!==1?` (${T}x)`:""}`;y>0&&(I+=y*oe.LEXICAL_WEIGHT,v+=` | Lexical: +${y.toFixed(1)}`),$&&(I+=$.score,v+=` | \u{1F525} Gravity: +${$.score.toFixed(1)} (${$.reasons.join(", ")})`);let P=g?Ft.extractSnippet(g,e):void 0;m.push({path:h.path,summary:h.summary||"",score:E,decayedScore:I,rationale:v,snippet:P})}}catch{}return m.sort((h,b)=>(b.decayedScore||0)-(h.decayedScore||0)),m}};N();F();function Nn(s){let{fileType:e,layer:t,dateModifiedAfter:n,dateModifiedBefore:i,includeTests:r}=s,o={fileType:je.normalizeFileType(e),layer:t,excludeLayers:r===!1?["Virtual"]:void 0,dateModifiedAfter:n,dateModifiedBefore:i},l=!!(o.fileType?.length||o.layer!=null||o.excludeLayers&&o.excludeLayers.length>0||o.dateModifiedAfter!=null||o.dateModifiedBefore!=null);return{filters:o,hasFilters:l}}async function Jr(s){let e=vn(s.query??""),t={...s,query:e},n=mn();try{let{repoPath:i}=xe(t),{query:r,limit:o=ot.DEFAULT_LIMIT,offset:l=0,skipSync:c=!1,compact:a=!1}=t;c||await j(i);let{filters:p,hasFilters:d}=Nn(t),m=await new je(i).searchByConcept(r,o,l,p,d,a);return xc(i,r,"concept"),n(),m}catch(i){return _.error({error:i,args:s},"Concept Search failed"),n(),await rt(),{content:[{type:"text",text:`Concept Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function xc(s,e,t){try{let n=k.getInstance(s),i=se(s);n.searchHistory.record(e,t,i)}catch(n){let i=se(s);_.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),rt()}}N();F();async function vi(s){let e=vn(s.query??""),t={...s,query:e},n=mn();try{let{repoPath:i}=xe(t),{query:r,limit:o=ot.DEFAULT_LIMIT,offset:l=0,skipSync:c=!1}=t;c||await j(i);let{filters:a,hasFilters:p}=Nn(t),u=await new je(i).searchBySymbol(r,o,l,a,p);return Rc(i,r,"symbol"),n(),u}catch(i){return _.error({error:i,args:s},"Symbol Search failed"),n(),await rt(),{content:[{type:"text",text:`Symbol Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Rc(s,e,t){try{let n=k.getInstance(s),i=se(s);n.searchHistory.record(e,t,i)}catch(n){let i=se(s);_.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),rt()}}F();N();import Yr from"path";async function Vr(s){let{repoPath:e,query:t,key:n="",kind:i,limit:r=50}=s,o=n||t;if(!o&&!i)return{content:[{type:"text",text:'Error: Either "key" or "kind" parameter is required.'}]};await j(e);let{configs:l}=k.getInstance(e);if(o){_.info({repoPath:e,key:o},"Searching for config key in DB...");let d=l.findByKey(o,r);if(d.length===0)return{content:[{type:"text",text:`No configuration found for key: ${o}`}]};let u=d.map(h=>({file:Yr.relative(e,h.file_path),key:h.key,value:h.value,kind:h.kind}));return{content:[{type:"text",text:`# Configuration Search: "${o}"
637
+ `),M}).join(`
638
+ `)}]}}async findConceptMatches(e,t,n,s,r,o=0){let c=re(this.repoPath)||void 0;if(!t)return[];let a=this.filesRepo.findWithEmbeddings(),p=new Nn(this.repoPath).getScorer(),u=new nt(this.repoPath).getAncestorMissionIds(),m=[];for(let h of a)try{let b=JSON.parse(h.embedding),y=as(t,b),g=this.filesRepo.getContent(h.path),S=ae.ENABLE_LEXICAL_SCORING&&g?Ft.calculateLexicalScore(g,e):0,R=S>0?.1:.18;if(y>R){if(s&&!i.matchesFilters(h.path,n,h.mtime,h.classification))continue;let w=h.mtime>2e9?Math.floor(h.mtime/1e3):h.mtime,T=Math.floor(Date.now()/1e3)-ps.SECONDS_PER_YEAR,v=be.getMultiplier(h.path,h.classification),k=p.calculateScore(y,w||T);k*=v;let x=this.filesRepo.getGravityMap(u,c)[h.path],I=h.classification?be.mapClassificationToTier(h.classification):be.classify(h.path,{content:g??void 0}),M=`Similarity: ${(y*100).toFixed(0)}%, Tier: ${I}${v!==1?` (${v}x)`:""}`;S>0&&(k+=S*ae.LEXICAL_WEIGHT,M+=` | Lexical: +${S.toFixed(1)}`),x&&(k+=x.score,M+=` | \u{1F525} Gravity: +${x.score.toFixed(1)} (${x.reasons.join(", ")})`);let $=g?Ft.extractSnippet(g,e):void 0;m.push({path:h.path,summary:h.summary||"",score:y,decayedScore:k,rationale:M,snippet:$})}}catch{}let f=new Map;for(let h of m){let b=h.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();b&&b.length>3&&(f.has(b)||f.set(b,[]),f.get(b).push(h))}for(let[h,b]of f.entries())if(new Set(b.map(g=>g.path.split(".").pop())).size>1)for(let g of b)g.decayedScore=(g.decayedScore||0)+.15,g.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${h}')`;return m.sort((h,b)=>(b.decayedScore||0)-(h.decayedScore||0)),m}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 ")}}};P();U();function An(i){let{fileType:e,layer:t}=i,n={fileType:Be.normalizeFileType(e),layer:t},s=!!(n.fileType?.length||n.layer!=null);return{filters:n,hasFilters:s}}async function Kr(i){let e=In(i.query??""),t={...i,query:e},n=fn();try{let{repoPath:s}=Re(t),{query:r,limit:o=at.DEFAULT_LIMIT,offset:c=0,compact:a=!1}=t;await z(s);let{filters:l,hasFilters:p}=An(t),u=await new Be(s).searchByConcept(r,o,c,l,p,a);return Cc(s,r,"concept"),n(),u}catch(s){return _.error({error:s,args:i},"Concept Search failed"),n(),await ot(),{content:[{type:"text",text:`Concept Search failed: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}function Cc(i,e,t){try{let n=C.getInstance(i),s=re(i);n.searchHistory.record(e,t,s)}catch(n){let s=re(i);_.error({module:"search",repoPath:i,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:s},"Failed to record search history"),ot()}}P();U();async function Is(i){let e=In(i.query??""),t={...i,query:e},n=fn();try{let{repoPath:s}=Re(t),{query:r,limit:o=at.DEFAULT_LIMIT,offset:c=0,matchMode:a="any"}=t;await z(s);let{filters:l,hasFilters:p}=An(t),u=await new Be(s).searchBySymbol(r,o,c,l,p,a);return $c(s,r,"symbol"),n(),u}catch(s){return _.error({error:s,args:i},"Symbol Search failed"),n(),await ot(),{content:[{type:"text",text:`Symbol Search failed: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}function $c(i,e,t){try{let n=C.getInstance(i),s=re(i);n.searchHistory.record(e,t,s)}catch(n){let s=re(i);_.error({module:"search",repoPath:i,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:s},"Failed to record search history"),ot()}}U();P();import Wt from"path";function Xr(i,e){let t=i.findContentByToken(e,100);return{count:t.length,files:t}}async function Zr(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 z(e);let a=C.getInstance(e),{configs:l,files:p}=a;if(c){_.info({repoPath:e,key:c},"Searching for config key in DB...");let f=l.findByKey(c,r);if(f.length===0)return{content:[{type:"text",text:`No configuration found for key: ${c}`}]};if(o){let y=f.map(w=>{let T=Xr(p,w.key),v=T.count===0?"\u26A0\uFE0F ORPHANED":`\u2713 ${T.count} usage(s)`;return{file:Wt.relative(e,w.file_path),key:w.key,value:w.value,kind:w.kind,usageCount:T.count,usageFiles:T.files.slice(0,5).map(k=>Wt.relative(e,k)),status:v}});y.sort((w,T)=>w.usageCount===0&&T.usageCount>0?-1:T.usageCount===0&&w.usageCount>0?1:w.usageCount-T.usageCount);let g=y.filter(w=>w.usageCount===0).length;return{content:[{type:"text",text:(g>0?`# Configuration Search: "${c}" (with Usage Analysis)
639
+
640
+ \u26A0\uFE0F **${g} orphaned var(s)** (defined but never used in code)
641
+
642
+ Found ${f.length} match(es):
643
+
644
+ `:`# Configuration Search: "${c}" (with Usage Analysis)
645
+
646
+ Found ${f.length} match(es), all in use:
647
+
648
+ `)+y.map(w=>{let T=`## ${w.file} (${w.kind}) ${w.status}
649
+ **${w.key}**: \`${w.value}\``;return w.usageCount>0&&w.usageFiles.length>0&&(T+=`
650
+ > Used in: ${w.usageFiles.map(v=>`\`${v}\``).join(", ")}${w.usageCount>5?` (+${w.usageCount-5} more)`:""}`),T}).join(`
651
+
652
+ `)}]}}let h=f.map(y=>({file:Wt.relative(e,y.file_path),key:y.key,value:y.value,kind:y.kind}));return{content:[{type:"text",text:`# Configuration Search: "${c}"
653
+
654
+ Found ${f.length} match(es):
655
+
656
+ `+h.map(y=>`## ${y.file} (${y.kind})
657
+ **${y.key}**: \`${y.value}\``).join(`
658
+
659
+ `)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let d=l.findByKind(s||null,r);if(o){let f=d.map(g=>{let S=Xr(p,g.key);return{file:Wt.relative(e,g.file_path),key:g.key,value:g.value,kind:g.kind,usageCount:S.count,status:S.count===0?"ORPHANED":"in-use"}});f.sort((g,S)=>g.usageCount===0&&S.usageCount>0?-1:S.usageCount===0&&g.usageCount>0?1:g.usageCount-S.usageCount);let h=f.filter(g=>g.usageCount===0).length,b=f.length,y=`# Config Discovery (${s||"all"}) with Usage Analysis
660
+
661
+ `;return y+=`**Summary**: ${b} config(s) found, ${h} orphaned
619
662
 
620
- Found ${d.length} match(es):
663
+ `,h>0&&(y+=`## \u26A0\uFE0F Orphaned (${h})
664
+ `,y+=f.filter(g=>g.usageCount===0).map(g=>`- \`${g.key}\` in ${g.file}`).join(`
665
+ `),y+=`
621
666
 
622
- `+u.map(h=>`## ${h.file} (${h.kind})
623
- **${h.key}**: \`${h.value}\``).join(`
667
+ `),y+=`## \u2713 In Use (${b-h})
668
+ `,y+=f.filter(g=>g.usageCount>0).map(g=>`- \`${g.key}\` (${g.usageCount} usages)`).join(`
669
+ `),d.length===r&&(y+=`
624
670
 
625
- `)}]}}let c=l.findByKind(i||null,r),a=c.map(d=>({...d,file:Yr.relative(e,d.file_path)})),p=JSON.stringify(a,null,2);return c.length===r&&(p=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
671
+ > Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:y}]}}let u=d.map(f=>({...f,file:Wt.relative(e,f.file_path)})),m=JSON.stringify(u,null,2);return d.length===r&&(m=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
626
672
 
627
- `+p),{content:[{type:"text",text:p}]}}F();import Qr from"path";async function An(s){let{repoPath:e,filePath:t}=xe(s);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=s.detailLevel||"signatures";await j(e);let{files:i,exports:r}=k.getInstance(e),o=i.findByPath(t),l=Qr.basename(t),c=/\.(ts|tsx|php|py|go)$/.test(l),a;c?a=await Ct(t):a={exports:r.findByFile(t),imports:[]},n==="structure"?(a.exports=a.exports.map(m=>({name:m.name,kind:m.kind,line:m.start_line,classification:m.classification})),delete a.imports):n==="signatures"&&(a.exports=a.exports.map(m=>({name:m.name,kind:m.kind,signature:m.signature,line:m.start_line,classification:m.classification,capabilities:JSON.parse(m.capabilities||"[]")})),delete a.imports);let p=Qr.relative(e,t),d=a.exports?.length||0,u="";return n==="structure"&&d>0?u=`
673
+ `+m),m+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:m}]}}U();import eo from"path";async function Mn(i){let{repoPath:e,filePath:t}=Re(i);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=i.detailLevel||"signatures";await z(e);let{files:s,exports:r}=C.getInstance(e),o=s.findByPath(t),c=eo.basename(t),a=/\.(ts|tsx|php|py|go)$/.test(c),l;a?l=await $t(t):l={exports:r.findByFile(t),imports:[]},n==="structure"?(l.exports=l.exports.map(m=>{let f={name:m.name,kind:m.kind,line:m.start_line,classification:m.classification};return m.members&&m.members.length>0?{...f,members:m.members.map(h=>({name:`${m.name}.${h.name}`,kind:h.kind,line:h.start_line}))}:f}),delete l.imports):n==="signatures"&&(l.exports=l.exports.map(m=>{let f={name:m.name,kind:m.kind,signature:m.signature,line:m.start_line,classification:m.classification,capabilities:JSON.parse(m.capabilities||"[]")};return m.members&&m.members.length>0?{...f,members:m.members.map(h=>({name:`${m.name}.${h.name}`,kind:h.kind,signature:h.signature,line:h.start_line}))}:f}),delete l.imports);let p=eo.relative(e,t),d=l.exports?.length||0,u="";return n==="structure"&&d>0?u=`
628
674
 
629
675
  \u{1F4A1} Showing ${d} symbol names. For full signatures: shadow_inspect_file({ filePath: "${p}", detailLevel: "signatures" })`:n==="signatures"&&d>0&&(u=`
630
676
 
631
- \u{1F4A1} Showing ${d} complete signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...a,fileDescription:o?.summary||"",classification:o?.classification||"Unknown"},null,2)+u}]}}F();import Kr from"path";import Tc from"fs";function vc(s,e,t){let n=s.split(`
632
- `),i=[],r=0;for(let d=0;d<Math.min(n.length,50);d++){let u=n[d].trim();if(u.startsWith("import ")||u.startsWith("from ")||u.startsWith("export ")&&u.includes(" from "))r=d+1;else if(u&&!u.startsWith("//")&&!u.startsWith("/*")&&!u.startsWith("*")&&u!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((d,u)=>d.startLine-u.startLine),l=0,c=0;for(let d of o)if(d.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${d.name} \u2501\u2501\u2501`);let u=n.slice(d.startLine-1,d.endLine);i.push(...u),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),c++}else{let u=d.signature||wc(n,d.startLine-1,d.kind);u&&(i.push(`${u}`),i.push(` /* implementation: ${d.lineCount} lines */`),i.push(""),l++)}let a=o[o.length-1];if(a)for(let d=a.endLine;d<n.length;d++){let u=n[d].trim();if(u==="}"||u==="};"){i.push(n[d]);break}else if(u&&!u.startsWith("//"))break}return{foldedSource:i.join(`
633
- `),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:c,siblingsFolded:l}}function wc(s,e,t){let n=s[e];if(t.includes("Function")||t.includes("Method")||t.includes("Arrow")){let i="";for(let r=e;r<Math.min(e+5,s.length);r++)if(i+=s[r],i.includes("{")||i.includes("=>")){let o=i.indexOf("{");o>0&&(i=i.substring(0,o).trim());break}return i.trim()}return n}async function gt(s){let{repoPath:e,filePath:t,resolver:n}=xe(s),i=String(s.symbolName),r=s.context||"definition";if(t&&!n.isWithinRoot(t))return{content:[{type:"text",text:`Error: Access denied. Path ${t} is outside the repository root.`}],isError:!0};await j(e);let o=k.getInstance(e),l=[];if(i.includes(".")){let[T,I]=i.split(".");l=o.exports.findMemberCandidates(T,I,t)}else l=o.exports.findDefinitionCandidates(i,t);if(l.length===0){let T=o.exports.findPotentialParents(i);if(T.length>0){let R=T.map(v=>`\`${v.name}\` (in ${n.getRelative(v.file_path)})`).join(", ");return{content:[{type:"text",text:`Symbol "${i}" not found as a top-level export.
634
- However, it likely exists inside: ${R}.
635
- Try: shadow_inspect_symbol({ symbolName: "${T[0].name}", context: "full" }) to see the class body.`}]}}let x=o.exports.findFuzzyCandidates(i).map(R=>R.name),$=$n(i,x,50,3);if($.length>0){let R=$.map(v=>` \u2022 \`${v.match}\` (${v.score}% match)`).join(`
636
- `);return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
677
+ \u{1F4A1} Showing ${d} complete signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...l,fileDescription:o?.summary||"",classification:o?.classification||"Unknown"},null,2)+u}]}}U();import to from"path";import kc from"fs";function Lc(i,e,t){let n=i.split(`
678
+ `),s=[],r=0;for(let d=0;d<Math.min(n.length,50);d++){let u=n[d].trim();if(u.startsWith("import ")||u.startsWith("from ")||u.startsWith("export ")&&u.includes(" from "))r=d+1;else if(u&&!u.startsWith("//")&&!u.startsWith("/*")&&!u.startsWith("*")&&u!==""&&r>0)break}r>0&&(s.push(...n.slice(0,r)),s.push(""));let o=[...t].sort((d,u)=>d.startLine-u.startLine),c=0,a=0;for(let d of o)if(d.isTarget){s.push(`// \u2501\u2501\u2501 REQUESTED: ${d.name} \u2501\u2501\u2501`);let u=n.slice(d.startLine-1,d.endLine);s.push(...u),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 u=d.signature||Nc(n,d.startLine-1,d.kind);u&&(s.push(`${u}`),s.push(` /* implementation: ${d.lineCount} lines */`),s.push(""),c++)}let l=o[o.length-1];if(l)for(let d=l.endLine;d<n.length;d++){let u=n[d].trim();if(u==="}"||u==="};"){s.push(n[d]);break}else if(u&&!u.startsWith("//"))break}return{foldedSource:s.join(`
679
+ `),totalOriginalLines:n.length,foldedToLines:s.length,siblingsShown:a,siblingsFolded:c}}function Nc(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 gt(i){let{repoPath:e,filePath:t,resolver:n}=Re(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 z(e);let o=C.getInstance(e),c=[];if(s.includes(".")){let[T,v]=s.split(".");c=o.exports.findMemberCandidates(T,v,t)}else c=o.exports.findDefinitionCandidates(s,t);if(c.length===0){let T=o.exports.findPotentialParents(s);if(T.length>0){let x=T.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.
680
+ However, it likely exists inside: ${x}.
681
+ Try: shadow_inspect_symbol({ symbolName: "${T[0].name}", context: "full" }) to see the class body.`}]}}let k=o.exports.findFuzzyCandidates(s).map(x=>x.name),F=Ht(s,k,50,3);if(F.length>0){let x=F.map(I=>` \u2022 \`${I.match}\` (${I.score}% match)`).join(`
682
+ `);return{content:[{type:"text",text:`Error: Symbol "${s}" not found in the index.
637
683
 
638
684
  Suggestions:
639
- ${R}
685
+ ${x}
640
686
 
641
687
  Next steps:
642
- \u2022 Search semantically: shadow_search_concept({ query: "${i}" })
643
- \u2022 Verify repository is indexed: shadow_sync_index({ repoPath: "${e}" })`}]}}return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
688
+ \u2022 Search semantically: shadow_search_concept({ query: "${s}" })
689
+ \u2022 Verify repository is indexed: shadow_sync_index({ repoPath: "${e}" })`}]}}return{content:[{type:"text",text:`Error: Symbol "${s}" not found in the index.
644
690
 
645
691
  Next steps:
646
- \u2022 Search for it: shadow_search_concept({ query: "${i}" })
647
- \u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${i}", filePath: "..." })
648
- `}]}}let c=l[0];if(c.kind==="ExportSpecifier"||c.kind==="ExportAllDeclaration"){let T=o.imports.findImportSource(c.file_path,i);if(T&&T.resolved_path)return gt({...s,filePath:T.resolved_path})}let a=Tc.readFileSync(c.file_path,"utf8"),p=a.split(`
649
- `),d=c.end_line-c.start_line+1,u=150,m,h=!1,b=null;if(r==="definition"&&d>u){let I=o.exports.findSiblings(c.file_path).map(x=>({name:x.name,kind:x.kind,signature:x.signature||"",startLine:x.start_line,endLine:x.end_line,lineCount:x.end_line-x.start_line+1,isTarget:x.name===c.name&&x.start_line===c.start_line,parentName:x.parent_name}));if(I.length>1){b=vc(a,{name:c.name,startLine:c.start_line,endLine:c.end_line},I);let x=n.getRelative(c.file_path);m=b.foldedSource+`
692
+ \u2022 Search for it: shadow_search_concept({ query: "${s}" })
693
+ \u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${s}", filePath: "..." })
694
+ `}]}}let a=c[0];if(a.kind==="ExportSpecifier"||a.kind==="ExportAllDeclaration"){let T=o.imports.findImportSource(a.file_path,s);if(T&&T.resolved_path)return gt({...i,filePath:T.resolved_path})}let l=kc.readFileSync(a.file_path,"utf8"),p=l.split(`
695
+ `),d=a.end_line-a.start_line+1,u=150,m,f=!1,h=null;if(r==="definition"&&d>u){let v=o.exports.findSiblings(a.file_path).map(k=>({name:k.name,kind:k.kind,signature:k.signature||"",startLine:k.start_line,endLine:k.end_line,lineCount:k.end_line-k.start_line+1,isTarget:k.name===a.name&&k.start_line===a.start_line,parentName:k.parent_name}));if(v.length>1){h=Lc(l,{name:a.name,startLine:a.start_line,endLine:a.end_line},v);let k=n.getRelative(a.file_path);m=h.foldedSource+`
650
696
 
651
697
  \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
652
698
  \u{1F4CA} Semantic Fold Applied (context: "definition")
653
699
 
654
- Original file: ${b.totalOriginalLines} lines
655
- Folded view: ${b.foldedToLines} lines
656
- Target Symbol: ${c.name}
700
+ Original file: ${h.totalOriginalLines} lines
701
+ Folded view: ${h.foldedToLines} lines
702
+ Target Symbol: ${a.name}
657
703
  \u{1F4A1} Need more context?
658
- \u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${c.name}", context: "full" })
659
- \u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${x}", detailLevel: "signatures" })
660
- \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(c.start_line-1,c.start_line-1+u).join(`
704
+ \u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${a.name}", context: "full" })
705
+ \u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${k}", detailLevel: "signatures" })
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`,f=!0}else m=p.slice(a.start_line-1,a.start_line-1+u).join(`
661
707
  `)+`
662
708
 
663
- ... (truncated ${d-u} lines)`,h=!0}else m=p.slice(c.start_line-1,c.end_line).join(`
664
- `);let E=c.parent_name?`${c.parent_name}.${c.name}`:c.name,g=o.exports.findHydratedById(c.id),y={name:E,kind:c.kind,file:n.getRelative(c.file_path),startLine:c.start_line,endLine:c.end_line,totalLines:d,...h&&{truncated:!0,previewLines:u},classification:c.classification,intelligence:g?{working_set_of:g.active_missions.map(T=>`Mission #${T.id}: ${T.name}`),total_intents:g.intent_log_count,latest_intent:g.recent_intents[0]?`${g.recent_intents[0].type}: ${g.recent_intents[0].content}`:null}:void 0,source:m};if(r==="definition")return{content:[{type:"text",text:JSON.stringify(y,null,2)}]};let S={definition:y,dependencies:o.imports.getImportsForFile(c.file_path).map(T=>({module:T.module_specifier,symbols:T.imported_symbols,relativePath:T.resolved_path?Kr.relative(e,T.resolved_path):null}))},w=[c.file_path],C=o.imports.findVerifiedDependents(w,i);return S.verifiedUsages=C.slice(0,10).map(T=>({file:Kr.relative(e,T.file_path),classification:T.classification,importedSymbols:T.imported_symbols})),{content:[{type:"text",text:JSON.stringify(S,null,2)}]}}async function Xr(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Semantic Concept Search");let n=ue();n.start(`Analyzing intent: "${f.bold(s)}"...`);try{let i=await Jr({repoPath:t,query:s});n.stop("Analysis complete.");let r=i.content[0].text;if(r.includes("Found")){let l=r.split("## ").slice(1).map(c=>{let[a,...p]=c.split(`
709
+ ... (truncated ${d-u} lines)`,f=!0}else m=p.slice(a.start_line-1,a.end_line).join(`
710
+ `);let b=a.parent_name?`${a.parent_name}.${a.name}`:a.name,y=o.exports.findHydratedById(a.id),g={name:b,kind:a.kind,file:n.getRelative(a.file_path),startLine:a.start_line,endLine:a.end_line,totalLines:d,...f&&{truncated:!0,previewLines:u},classification:a.classification,intelligence:y?{working_set_of:y.active_missions.map(T=>`Mission #${T.id}: ${T.name}`),total_intents:y.intent_log_count,latest_intent:y.recent_intents[0]?`${y.recent_intents[0].type}: ${y.recent_intents[0].content}`:null}:void 0,source:m};if(r==="definition")return{content:[{type:"text",text:JSON.stringify(g,null,2)}]};let S={definition:g,dependencies:o.imports.getImportsForFile(a.file_path).map(T=>({module:T.module_specifier,symbols:T.imported_symbols,relativePath:T.resolved_path?to.relative(e,T.resolved_path):null}))},R=[a.file_path],w=o.imports.findVerifiedDependents(R,s);return S.verifiedUsages=w.slice(0,10).map(T=>({file:to.relative(e,T.file_path),classification:T.classification,importedSymbols:T.imported_symbols})),{content:[{type:"text",text:JSON.stringify(S,null,2)}]}}async function no(i,e){let t=jt.resolve(e.dir);await B(async()=>{le("Semantic Concept Search");let n=de();n.start(`Analyzing intent: "${E.bold(i)}"...`);try{let s=await Kr({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(`
665
711
 
666
- `),[d,u]=a.split(" ( "),m=(d??"").replace(/^\d+\.\s*/,"").trim(),h=p.find(b=>b.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:m,matchPct:u??"",summaryLine:h}});if(l.forEach(({name:c,matchPct:a,summaryLine:p})=>{te(`${f.green(c)} ${f.dim("("+(a||""))}`,p,"blue"),console.log("")}),e.interactive&&l.length>1){let c=await on("Inspect a file",l.map(a=>({value:{name:a.name},label:a.name,hint:a.summaryLine.slice(0,50)})),{limit:15});if(c){let a=c.name.startsWith(t)?c.name:Ht.join(t,c.name),p=await An({repoPath:t,filePath:a});p.content?.[0]&&(console.log(""),te(f.bold("File summary"),p.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await G(t)}})}async function Zr(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Symbol Search");let n=ue();n.start(`Searching symbols: "${f.bold(s)}"...`);try{let i=await vi({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;try{let o=JSON.parse(r);if(Array.isArray(o)){if(console.log(""),rn(["Symbol","Kind","File","Line"],o.map(l=>[f.bold(f.green(l.name)),f.dim(l.kind??""),f.cyan(l.file??""),f.yellow(String(l.line??""))])),e.interactive&&o.length>1){let l=o.map(a=>({value:a,label:a.name,hint:`${a.file??""}:${a.line??""}`})),c=await on("Inspect symbol",l,{limit:15});if(c){let a=await gt({repoPath:t,symbolName:c.name});a.content?.[0]&&(console.log(""),te(f.bold(c.name),a.content[0].text,"cyan"))}}}else console.log(r)}catch{console.log(r)}}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await G(t)}})}async function eo(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Fuzzy Symbol Search");let n=ue();n.start(`Fuzzy matching: "${f.bold(s)}"...`);try{let i=await vi({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;if(r.includes("## ")){let l=r.split("## ").slice(1).map(c=>{let a=c.split(`
667
- `),p=a[0],d=a.find(g=>g.startsWith("**Match**:"))||"",u=a.find(g=>g.startsWith("**File**:"))||"",m=p.match(/`([^`]+)`/),h=m?m[1]:"",b=d.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),E=u.match(/`([^:]+):(\d+)`/);return{symbolName:h,file:E?E[1]:"",line:E?E[2]:"",matchType:b?b[1]:"",confidence:b?b[2]:""}});if(console.log(""),console.log(f.dim(`Found ${l.length} fuzzy match(es):`)),console.log(""),l.forEach((c,a)=>{console.log(`${f.dim(`${a+1}.`)} ${f.bold(f.green(c.symbolName))} ${f.dim(`(${c.matchType}, ${c.confidence}% match)`)}`),console.log(` ${f.cyan(c.file)}:${f.yellow(c.line)}`),console.log("")}),e.interactive&&l.length>1){let c=await on("Inspect symbol",l.map(a=>({value:a,label:a.symbolName,hint:`${a.file}:${a.line}`})),{limit:15});if(c){let a=await gt({repoPath:t,symbolName:c.symbolName});a.content?.[0]&&(console.log(""),te(f.bold(c.symbolName),a.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await G(t)}})}async function to(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Config Search");let n=ue();n.start(`Searching config: ${f.bold(s||"all")}...`);try{let i=await Vr({repoPath:t,key:s,kind:e.kind});n.stop("Search complete."),te("\u2699\uFE0F Results",i.content[0].text,"yellow")}finally{await G(t)}})}N();var wi=_.child({module:"mcp:tools:env:hooks"});async function Mn(s){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:i}=s;if(t==="install"){wi.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:i},"Installing git hooks");let r=gs({repoPath:e,enableAutoRefresh:n??!0,enableSymbolHealing:i??!0}),o=["# Git Hooks Installation","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(l=>`- \`${l}\``).join(`
668
- `):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(l=>`- \`${l}\` (already installed)`).join(`
669
- `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(l=>`- ${l}`).join(`
670
- `)),o.push("")),o.push("---"),o.push("**What happens now?**"),(n??!0)&&o.push("- After `git pull` or `git checkout`: Index auto-refreshes in background"),(i??!0)&&o.push("- After `git commit`: Symbol shift detection runs automatically"),{content:[{type:"text",text:o.join(`
671
- `)}]}}if(t==="remove"){wi.info({repoPath:e},"Uninstalling git hooks");let r=ys(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(l=>`- \`${l}\``).join(`
672
- `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(l=>`- ${l}`).join(`
712
+ `),[d,u]=l.split(" ( "),m=(d??"").replace(/^\d+\.\s*/,"").trim(),f=p.find(h=>h.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:m,matchPct:u??"",summaryLine:f}});if(c.forEach(({name:a,matchPct:l,summaryLine:p})=>{se(`${E.green(a)} ${E.dim("("+(l||""))}`,p,"blue"),console.log("")}),e.interactive&&c.length>1){let a=await cn("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:jt.join(t,a.name),p=await Mn({repoPath:t,filePath:l});p.content?.[0]&&(console.log(""),se(E.bold("File summary"),p.content[0].text,"cyan"))}}}else console.log(r)}catch(s){throw n.stop(`Search failed: ${s.message}`),s}finally{await q(t)}})}async function so(i,e){let t=jt.resolve(e.dir);await B(async()=>{le("Symbol Search");let n=de();n.start(`Searching symbols: "${E.bold(i)}"...`);try{let s=await Is({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(""),an(["Symbol","Kind","File","Line"],o.map(c=>[E.bold(E.green(c.name)),E.dim(c.kind??""),E.cyan(c.file??""),E.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 cn("Inspect symbol",c,{limit:15});if(a){let l=await gt({repoPath:t,symbolName:a.name});l.content?.[0]&&(console.log(""),se(E.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 q(t)}})}async function io(i,e){let t=jt.resolve(e.dir);await B(async()=>{le("Fuzzy Symbol Search");let n=de();n.start(`Fuzzy matching: "${E.bold(i)}"...`);try{let s=await Is({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(`
713
+ `),p=l[0],d=l.find(y=>y.startsWith("**Match**:"))||"",u=l.find(y=>y.startsWith("**File**:"))||"",m=p.match(/`([^`]+)`/),f=m?m[1]:"",h=d.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),b=u.match(/`([^:]+):(\d+)`/);return{symbolName:f,file:b?b[1]:"",line:b?b[2]:"",matchType:h?h[1]:"",confidence:h?h[2]:""}});if(console.log(""),console.log(E.dim(`Found ${c.length} fuzzy match(es):`)),console.log(""),c.forEach((a,l)=>{console.log(`${E.dim(`${l+1}.`)} ${E.bold(E.green(a.symbolName))} ${E.dim(`(${a.matchType}, ${a.confidence}% match)`)}`),console.log(` ${E.cyan(a.file)}:${E.yellow(a.line)}`),console.log("")}),e.interactive&&c.length>1){let a=await cn("Inspect symbol",c.map(l=>({value:l,label:l.symbolName,hint:`${l.file}:${l.line}`})),{limit:15});if(a){let l=await gt({repoPath:t,symbolName:a.symbolName});l.content?.[0]&&(console.log(""),se(E.bold(a.symbolName),l.content[0].text,"cyan"))}}}else console.log(r)}catch(s){throw n.stop(`Search failed: ${s.message}`),s}finally{await q(t)}})}async function ro(i,e){let t=jt.resolve(e.dir);await B(async()=>{le("Config Search");let n=de();n.start(`Searching config: ${E.bold(i||"all")}...`);try{let s=await Zr({repoPath:t,key:i,kind:e.kind});n.stop("Search complete."),se("\u2699\uFE0F Results",s.content[0].text,"yellow")}finally{await q(t)}})}P();var Cs=_.child({module:"mcp:tools:env:hooks"});async function Pn(i){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:s}=i;if(t==="install"){Cs.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:s},"Installing git hooks");let r=Si({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
+ `):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(c=>`- \`${c}\` (already installed)`).join(`
715
+ `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(c=>`- ${c}`).join(`
716
+ `)),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"){Cs.info({repoPath:e},"Uninstalling git hooks");let r=_i(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(c=>`- \`${c}\``).join(`
718
+ `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(c=>`- ${c}`).join(`
673
719
  `))),{content:[{type:"text",text:o.join(`
674
- `)}]}}if(t==="status"){wi.info({repoPath:e},"Checking git hooks status");let r=un(e);return{content:[{type:"text",text:["# Git Hooks Status","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(l=>`- \`${l}\``).join(`
675
- `):"- None","",`## Not Installed (${r.notInstalled.length})`,r.notInstalled.length>0?r.notInstalled.map(l=>`- \`${l}\``).join(`
720
+ `)}]}}if(t==="status"){Cs.info({repoPath:e},"Checking git hooks status");let r=mn(e);return{content:[{type:"text",text:["# Git Hooks Status","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(c=>`- \`${c}\``).join(`
721
+ `):"- None","",`## Not Installed (${r.notInstalled.length})`,r.notInstalled.length>0?r.notInstalled.map(c=>`- \`${c}\``).join(`
676
722
  `):"- None","","---",'**To install hooks**: Use `shadow_env_hooks({ action: "install" })`'].join(`
677
- `)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function no(s){let[e,t="."]=s;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 U(async()=>{let n=Wo("path").resolve(t);switch(e){case"install":{let i=await Mn({repoPath:n,action:"install",enableAutoRefresh:!0,enableSymbolHealing:!0});if(console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Git hooks installed successfully")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);console.log(` ${f.bold("Installed hooks: ")}`),r.hooks.forEach(o=>{console.log(` ${f.cyan("\u2022")} ${o}`)}),console.log("")}catch{console.log(i.content[0].text)}break}case"uninstall":{await Mn({repoPath:n,action:"remove"}),console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Git hooks uninstalled successfully")}`),console.log("");break}case"status":{let i=await Mn({repoPath:n,action:"status"});if(console.log(""),console.log(` ${f.bold("Git Hooks Status")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);r.installed&&r.installed.length>0?(console.log(` ${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(i.content[0].text)}console.log("");break}}})}F();N();import Ic from"path";import kc from"fs";var io=_.child({module:"mcp:tools:workspace:list"});async function so(s){let{repoPaths:e,status:t}=s;io.info({repoCount:e.length,status:t},"Getting workspace missions");let n=[];for(let i of e)if(kc.existsSync(i))try{let{missions:r}=k.getInstance(i),o=r.findAll(t);for(let l of o){let c=r.getLinks(l.id);n.push({...l,repo_path:i,repo_name:Ic.basename(i),cross_repo_links:c})}}catch(r){io.error({error:r,repoPath:i},"Failed to query repo missions")}return n.sort((i,r)=>{let o=a=>a==="in-progress"?0:a==="verifying"?1:2,l=o(i.status),c=o(r.status);return l!==c?l-c:(i.created_at||0)-(r.created_at||0)}),{content:[{type:"text",text:JSON.stringify({total_missions:n.length,missions:n},null,2)}]}}F();N();var Cc=_.child({module:"mcp:tools:workspace:link"});async function ro(s){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:i,relationship:r="related"}=s;Cc.info({parentRepoPath:e,childRepoPath:n},"Linking cross-repo missions");let{missions:o}=k.getInstance(e),{missions:l}=k.getInstance(n);try{let c=o.findById(t),a=l.findById(i);if(!c)throw new Error(`Parent mission ${t} not found`);if(!a)throw new Error(`Child mission ${i} not found`);return o.createLink(t,n,i,r,"parent"),l.createLink(i,e,t,r,"child"),{content:[{type:"text",text:JSON.stringify({status:"linked",relationship:r},null,2)}]}}catch(c){throw new Error(`Failed to link: ${c.message}`)}}N();import Hc from"path";N();Ve();import Lc from"better-sqlite3";import yt from"path";import oo from"fs";import $c from"os";import Nc from"crypto";var Ac=_.child({module:"fusion-connection"}),Pn=5,Mc=1,ao=["files","exports","imports","configs","schema_migrations"],Dn=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),Ac.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=yt.dirname(this.fusionDbPath);oo.existsSync(t)||oo.mkdirSync(t,{recursive:!0}),this.fusionDb=new Lc(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=$c.homedir(),n=yt.join(t,".mcp-liquid-shadow","fused"),i=e.replace(/[^a-zA-Z0-9-_]/g,"_");return yt.join(n,`${i}.db`)}initFusionSchema(){this.fusionDb.exec(`
723
+ `)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function oo(i){let[e,t="."]=i;if(!e||!["install","uninstall","status"].includes(e)){console.log(""),console.log(` ${E.bold("Usage: ")} liquid-shadow hooks <install|uninstall|status> [path]`),console.log(""),console.log(` ${E.bold("Commands: ")}`),console.log(` ${E.cyan("install")} Install git hooks for automatic index refresh and symbol healing`),console.log(` ${E.cyan("uninstall")} Remove installed git hooks`),console.log(` ${E.cyan("status")} Check git hooks installation status`),console.log(""),console.log(` ${E.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=Go("path").resolve(t);switch(e){case"install":{let s=await Pn({repoPath:n,action:"install",enableAutoRefresh:!0,enableSymbolHealing:!0});if(console.log(""),console.log(` ${E.green("\u2714")} ${E.bold("Git hooks installed successfully")}`),console.log(""),s.content&&s.content[0])try{let r=JSON.parse(s.content[0].text);console.log(` ${E.bold("Installed hooks: ")}`),r.hooks.forEach(o=>{console.log(` ${E.cyan("\u2022")} ${o}`)}),console.log("")}catch{console.log(s.content[0].text)}break}case"uninstall":{await Pn({repoPath:n,action:"remove"}),console.log(""),console.log(` ${E.green("\u2714")} ${E.bold("Git hooks uninstalled successfully")}`),console.log("");break}case"status":{let s=await Pn({repoPath:n,action:"status"});if(console.log(""),console.log(` ${E.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(` ${E.green("\u2714")} Installed hooks:`),r.installed.forEach(o=>{console.log(` ${E.cyan("\u2022")} ${o}`)})):console.log(` ${E.yellow("\u26A0")} No hooks installed`),r.missing&&r.missing.length>0&&(console.log(""),console.log(` ${E.dim("Missing hooks: ")}`),r.missing.forEach(o=>{console.log(` ${E.dim("\u2022")} ${o}`)}))}catch{console.log(s.content[0].text)}console.log("");break}}})}U();P();import Ac from"path";import Mc from"fs";var ao=_.child({module:"mcp:tools:workspace:list"});async function co(i){let{repoPaths:e,status:t,limit:n,summarize:s=!1}=i;ao.info({repoCount:e.length,status:t,summarize:s},"Getting workspace missions");let r=[];for(let c of e)if(Mc.existsSync(c))try{let{missions:a}=C.getInstance(c),l=a.findAll(t);for(let p of l){let d=a.getLinks(p.id);r.push({...p,repo_path:c,repo_name:Ac.basename(c),cross_repo_links:d})}}catch(a){ao.error({error:a,repoPath:c},"Failed to query repo missions")}if(r.sort((c,a)=>{let l=u=>u==="in-progress"?0:u==="verifying"?1:2,p=l(c.status),d=l(a.status);return p!==d?p-d:(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((d,u)=>(d[u.status]=(d[u.status]||0)+1,d),{}),p=r.reduce((d,u)=>(d[u.repo_name]=(d[u.repo_name]||0)+1,d),{});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)}]}}U();P();var Pc=_.child({module:"mcp:tools:workspace:link"});async function lo(i){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:s,relationship:r="related"}=i;Pc.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}`)}}P();import Gc from"path";P();Qe();import Dc from"better-sqlite3";import yt from"path";import po from"fs";import Oc from"os";import Fc from"crypto";var Hc=_.child({module:"fusion-connection"}),Dn=5,Wc=1,uo=["files","exports","imports","configs","schema_migrations"],On=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),Hc.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=yt.dirname(this.fusionDbPath);po.existsSync(t)||po.mkdirSync(t,{recursive:!0}),this.fusionDb=new Dc(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=Oc.homedir(),n=yt.join(t,".mcp-liquid-shadow","fused"),s=e.replace(/[^a-zA-Z0-9-_]/g,"_");return yt.join(n,`${s}.db`)}initFusionSchema(){this.fusionDb.exec(`
678
724
  CREATE TABLE IF NOT EXISTS fused_repos (
679
725
  alias TEXT PRIMARY KEY,
680
726
  repo_path TEXT NOT NULL UNIQUE,
@@ -708,64 +754,64 @@ Target Symbol: ${c.name}
708
754
 
709
755
  CREATE INDEX IF NOT EXISTS idx_virtual_edges_source ON virtual_edges(source_repo, source_file_path);
710
756
  CREATE INDEX IF NOT EXISTS idx_virtual_edges_target ON virtual_edges(target_repo, target_file_path);
711
- `),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(Mc.toString())}attachRepo(e){let t=yt.resolve(e);if(this.attachedRepos.has(t))return;if(!Ye(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=ke(t),i=n.name;this.validateSchemaCompatibility(n,t);let r=this.getSchemaVersion(n),o=this.generateAlias(t),l=3,c=100;for(let a=1;a<=l;a++)try{this.fusionDb.exec(`ATTACH DATABASE '${i}' AS ${o}`);let p={alias:o,repoPath:t,dbPath:i,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)
712
- VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(p){let d=p instanceof Error?p.message.toLowerCase():String(p).toLowerCase();if((d.includes("locked")||d.includes("busy"))&&a<l){this.sleep(c*a);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=yt.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=ke(t.repoPath),i=ao.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=Pn&&i.length===0,missingTables:i}});return{valid:e.every(t=>t.compatible),minVersion:Pn,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=yt.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=Nc.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<Pn)throw new Error(`Schema version mismatch for ${t}. Expected >= ${Pn}, got ${n}.`);let i=ao.filter(r=>!this.checkTableExists(e,r));if(i.length>0)throw new Error(`Missing tables in ${t}: ${i.join(", ")}`)}checkTableExists(e,t){try{return!!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)}catch{return!1}}sleep(e){let t=Date.now()+e;for(;Date.now()<t;);}get nameValue(){return this.name}get dbPath(){return this.fusionDbPath}};N();var Be=_.child({module:"edge-scanner"});function Ii(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Pc(s){if(!s)return null;try{let e=JSON.parse(s);return e.path||e.name||null}catch{return null}}function Dc(s,e){let t=Ii(s),n=Ii(e);if(t===n)return!0;let i=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function Oc(s){Be.info("Starting HTTP gap detection scan");let e=s.getAttachedRepos();if(e.length<2)return Be.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
757
+ `),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(Wc.toString())}attachRepo(e){let t=yt.resolve(e);if(this.attachedRepos.has(t))return;if(!Ve(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=ke(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)
758
+ VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,s,r);return}catch(p){let d=p instanceof Error?p.message.toLowerCase():String(p).toLowerCase();if((d.includes("locked")||d.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=yt.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=ke(t.repoPath),s=uo.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=Dn&&s.length===0,missingTables:s}});return{valid:e.every(t=>t.compatible),minVersion:Dn,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=yt.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=Fc.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<Dn)throw new Error(`Schema version mismatch for ${t}. Expected >= ${Dn}, got ${n}.`);let s=uo.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}};P();var ze=_.child({module:"edge-scanner"});function $s(i){let e=i.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function jc(i){if(!i)return null;try{let e=JSON.parse(i);return e.path||e.name||null}catch{return null}}function Uc(i,e){let t=$s(i),n=$s(e);if(t===n)return!0;let s=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${s}$`).test(t)}function Bc(i){ze.info("Starting HTTP gap detection scan");let e=i.getAttachedRepos();if(e.length<2)return ze.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
713
759
  SELECT id, name, file_path, capabilities
714
760
  FROM ${r.alias}.exports
715
761
  WHERE kind = 'HTTP Route'
716
- `,l=s.executeRawQuery(o);for(let c of l){let a=Pc(c.capabilities)||c.name;a&&a.startsWith("/")&&t.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,symbolId:c.id,routePath:a})}}catch(o){Be.warn({repo:r.alias,error:o},"Failed to query backend routes")}Be.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
762
+ `,c=i.executeRawQuery(o);for(let a of c){let l=jc(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){ze.warn({repo:r.alias,error:o},"Failed to query backend routes")}ze.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
717
763
  SELECT file_path, name
718
764
  FROM ${r.alias}.event_synapses
719
765
  WHERE type = 'api_route' AND direction = 'produce'
720
- `,l=s.executeRawQuery(o);for(let c of l){let a=Ii(c.name);a&&a.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,routePath:a})}}catch(o){Be.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}Be.debug({count:n.length},"Found frontend API calls");let i=0;for(let r of n)for(let o of t)if(r.repoPath!==o.repoPath&&Dc(r.routePath,o.routePath))try{s.addVirtualEdge({sourceRepo:r.repoPath,sourceFilePath:r.filePath,targetRepo:o.repoPath,targetFilePath:o.filePath,targetSymbolId:o.symbolId,relationship:"api_call",metadata:{frontendPath:r.routePath,backendPath:o.routePath,method:o.method},confidence:1}),i++}catch(l){Be.debug({source:r.filePath,target:o.filePath,error:l},"Skipped duplicate edge")}return Be.info({edgesCreated:i,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),i}function co(s){let e=Oc(s);return{httpGaps:e,totalEdges:e}}N();var Fc=_.child({module:"fusion-index-service"}),On=class{constructor(e){this.connection=e}executeFederatedQuery(e,...t){return this.connection.prepare(e).all(...t).map(r=>{let{_repo_alias:o,_repo_path:l,...c}=r;return{repo:o,repoPath:l,data:c}})}executeRawQuery(e,...t){return this.connection.prepare(e).all(...t)}buildAdvancedQuery(e){let t=this.connection.getAttachedRepos();if(t.length===0)throw new Error("No repositories attached");let{table:n,tableAlias:i,columns:r,joins:o,where:l,groupBy:c,having:a,orderBy:p,limit:d,offset:u}=e,m=i||n.charAt(0),h=r.join(", "),E=t.map(g=>{let y=`${g.alias}.${n} ${m}`,S="";o&&o.length>0&&(S=o.map(I=>{let x=I.alias||I.table.charAt(0);return`${I.type} JOIN ${g.alias}.${I.table} ${x} ON ${I.on}`}).join(`
721
- `));let w=l?`WHERE ${l}`:"",C=c&&c.length>0?`GROUP BY ${c.join(", ")}`:"",T=a?`HAVING ${a}`:"";return`SELECT '${g.alias}' as _repo_alias, '${g.repoPath}' as _repo_path, ${h} FROM ${y} ${S} ${w} ${C} ${T}`.trim()}).join(`
766
+ `,c=i.executeRawQuery(o);for(let a of c){let l=$s(a.name);l&&l.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:a.file_path,routePath:l})}}catch(o){ze.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}ze.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&&Uc(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){ze.debug({source:r.filePath,target:o.filePath,error:c},"Skipped duplicate edge")}return ze.info({edgesCreated:s,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),s}function mo(i){let e=Bc(i);return{httpGaps:e,totalEdges:e}}P();var zc=_.child({module:"fusion-index-service"}),Fn=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:d,offset:u}=e,m=s||n.charAt(0),f=r.join(", "),b=t.map(y=>{let g=`${y.alias}.${n} ${m}`,S="";o&&o.length>0&&(S=o.map(v=>{let k=v.alias||v.table.charAt(0);return`${v.type} JOIN ${y.alias}.${v.table} ${k} ON ${v.on}`}).join(`
767
+ `));let R=c?`WHERE ${c}`:"",w=a&&a.length>0?`GROUP BY ${a.join(", ")}`:"",T=l?`HAVING ${l}`:"";return`SELECT '${y.alias}' as _repo_alias, '${y.repoPath}' as _repo_path, ${f} FROM ${g} ${S} ${R} ${w} ${T}`.trim()}).join(`
722
768
  UNION ALL
723
- `);return p&&(E=`SELECT * FROM (${E}) AS federated_results ORDER BY ${p}`),d!==void 0&&(E+=` LIMIT ${d}`),u!==void 0&&(E+=` OFFSET ${u}`),E}buildFtsQuery(e,t,n,i,r=50){let o=this.connection.getAttachedRepos();if(o.length===0)throw new Error("No repositories attached");let l=n.replace(/"/g,'""'),c=i.map(p=>`c.${p}`).join(", ");return`${o.map(p=>`
724
- SELECT '${p.alias}' as _repo_alias, '${p.repoPath}' as _repo_path, ${c}, bm25(${p.alias}.${e}) as _fts_rank
769
+ `);return p&&(b=`SELECT * FROM (${b}) AS federated_results ORDER BY ${p}`),d!==void 0&&(b+=` LIMIT ${d}`),u!==void 0&&(b+=` OFFSET ${u}`),b}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
+ SELECT '${p.alias}' as _repo_alias, '${p.repoPath}' as _repo_path, ${a}, bm25(${p.alias}.${e}) as _fts_rank
725
771
  FROM ${p.alias}.${e} fts
726
772
  JOIN ${p.alias}.${t} c ON fts.rowid = c.id
727
- WHERE ${p.alias}.${e} MATCH '"${l}"'`).join(`
773
+ WHERE ${p.alias}.${e} MATCH '"${c}"'`).join(`
728
774
  UNION ALL
729
- `)} ORDER BY _fts_rank LIMIT ${r}`}buildCrossRepoImportsQuery(){let e=this.connection.getAttachedRepos();if(e.length<2)throw new Error("Cross-repo analysis requires at least 2 attached repositories");let t=[];for(let n of e)for(let i of e)n.alias!==i.alias&&t.push(`
775
+ `)} ORDER BY _fts_rank LIMIT ${r}`}buildCrossRepoImportsQuery(){let e=this.connection.getAttachedRepos();if(e.length<2)throw new Error("Cross-repo analysis requires at least 2 attached repositories");let t=[];for(let n of e)for(let s of e)n.alias!==s.alias&&t.push(`
730
776
  SELECT
731
777
  '${n.alias}' as source_repo, '${n.repoPath}' as source_repo_path,
732
778
  i.file_path as source_file, i.module_specifier, i.imported_symbols,
733
- '${i.alias}' as target_repo, '${i.repoPath}' as target_repo_path,
779
+ '${s.alias}' as target_repo, '${s.repoPath}' as target_repo_path,
734
780
  f.path as target_file
735
781
  FROM ${n.alias}.imports i
736
- JOIN ${i.alias}.files f ON i.resolved_path = f.path
782
+ JOIN ${s.alias}.files f ON i.resolved_path = f.path
737
783
  WHERE i.resolved_path IS NOT NULL`);return t.join(`
738
784
  UNION ALL
739
- `)}buildUnionQuery(e,t,n){let i=this.connection.getAttachedRepos();if(i.length===0)throw new Error("No repositories attached");let r=t.join(", "),o=n?` WHERE ${n}`:"";return i.map(l=>`SELECT '${l.alias}' as _repo_alias, '${l.repoPath}' as _repo_path, ${r} FROM ${l.alias}.${e}${o}`).join(`
785
+ `)}buildUnionQuery(e,t,n){let s=this.connection.getAttachedRepos();if(s.length===0)throw new Error("No repositories attached");let r=t.join(", "),o=n?` WHERE ${n}`:"";return s.map(c=>`SELECT '${c.alias}' as _repo_alias, '${c.repoPath}' as _repo_path, ${r} FROM ${c.alias}.${e}${o}`).join(`
740
786
  UNION ALL
741
- `)}searchExports(e,t=50){let n=this.buildUnionQuery("exports",["id","name","kind","file_path","signature"],"name LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}searchFiles(e,t=50){let n=this.buildUnionQuery("files",["path","classification","content_hash"],"path LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}getVirtualEdges(e,t){let n="SELECT * FROM virtual_edges WHERE 1=1",i=[];return e&&(n+=" AND source_repo = ?",i.push(e)),t&&(n+=" AND target_repo = ?",i.push(t)),this.connection.prepare(n).all(...i)}addVirtualEdge(e){return this.connection.prepare(`
787
+ `)}searchExports(e,t=50){let n=this.buildUnionQuery("exports",["id","name","kind","file_path","signature"],"name LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,s=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...s)}searchFiles(e,t=50){let n=this.buildUnionQuery("files",["path","classification","content_hash"],"path LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,s=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...s)}getVirtualEdges(e,t){let n="SELECT * FROM virtual_edges WHERE 1=1",s=[];return e&&(n+=" AND source_repo = ?",s.push(e)),t&&(n+=" AND target_repo = ?",s.push(t)),this.connection.prepare(n).all(...s)}addVirtualEdge(e){return this.connection.prepare(`
742
788
  INSERT INTO virtual_edges
743
789
  (source_repo, source_file_path, source_symbol_id, target_repo, target_file_path, target_symbol_id, relationship, metadata, confidence, updated_at)
744
790
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
745
- `).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 Fc.info({name:this.connection.nameValue},"Starting edge scan"),co(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var lo=_.child({module:"fused-index"}),Ci=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Dn(e),this.service=new On(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(),lo.info({name:this.configName},"Fused index closed")}getStatus(){let e=this.service.executeRawQuery("SELECT COUNT(*) as count FROM virtual_edges");return{name:this.connection.nameValue,path:this.connection.dbPath,attachedRepos:this.connection.getAttachedRepos().length,repos:this.connection.getAttachedRepos(),virtualEdgesCount:e[0]?.count||0}}searchExports(e,t=50){return this.service.searchExports(e,t)}searchFiles(e,t=50){return this.service.searchFiles(e,t)}getVirtualEdges(e,t){return this.service.getVirtualEdges(e,t)}addVirtualEdge(e){return this.service.addVirtualEdge(e)}scanEdges(){return this.service.scanEdges()}buildUnionQuery(e,t,n){return this.service.buildUnionQuery(e,t,n)}executeFederatedQuery(e,...t){return this.service.executeFederatedQuery(e,...t)}executeRawQuery(e,...t){return this.service.executeRawQuery(e,...t)}buildAdvancedQuery(e){return this.service.buildAdvancedQuery(e)}buildFtsQuery(e,t,n,i,r){return this.service.buildFtsQuery(e,t,n,i,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return lo.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},ki=new Map;function po(s){let e=ki.get(s.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),i=new Set(s.repoPaths.map(o=>Hc.resolve(o)));if(n.size===i.size&&[...n].every(o=>i.has(o)))return e;e.close(),ki.delete(s.name)}let t=new Ci(s);return ki.set(s.name,t),t}N();var Wc=_.child({module:"mcp:tools:workspace:fuse"});async function uo(s){let{repoPaths:e,name:t}=s;Wc.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=po({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 Fn from"path";async function mo(s){let[e,...t]=s;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 U(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=>Fn.resolve(r)),i=await so({repoPaths:n});if(console.log(""),console.log(` ${f.bold("Workspace Missions")}`),console.log(""),i.content&&i.content[0]){let r=JSON.parse(i.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${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,i,r,o,l]=t;await ro({parentRepoPath:Fn.resolve(n),parentMissionId:parseInt(i,10),childRepoPath:Fn.resolve(r),childMissionId:parseInt(o,10),relationship:l}),console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Missions linked successfully")}`),console.log(` ${f.dim("Parent: ")} ${n} (Mission ${i})`),console.log(` ${f.dim("Child: ")} ${r} (Mission ${o})`),l&&console.log(` ${f.dim("Relationship: ")} ${l}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${f.red("\u2716")} Please provide at least one repository path`);return}let n,i=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):i.push(Fn.resolve(t[o]));let r=await uo({repoPaths:i,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}}})}N();N();var Uc=_.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(i){return Uc.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:this.normalizeSteps(t)}}static normalizeSteps(e){return Array.isArray(e)?e.map((t,n)=>typeof t=="string"?{id:`step-${n}`,description:t,status:"pending"}:typeof t=="object"&&t!==null?{id:t.id||`step-${n}`,description:t.description||t.content||t.name||`Step ${n+1}`,status:t.status||"pending",dependencies:t.dependencies||t.deps,verification:t.verification,...t}:{id:`step-${n}`,description:String(t),status:"pending"}):e.steps&&Array.isArray(e.steps)?this.normalizeSteps(e.steps):typeof e=="object"?Object.entries(e).map(([t,n],i)=>typeof n=="string"?{id:t,description:n,status:"pending"}:typeof n=="object"&&n!==null?{id:t,description:n.description||n.content||n.name||t,status:n.status||"pending",dependencies:n.dependencies||n.deps,verification:n.verification,...n}:{id:t||`step-${i}`,description:String(n),status:"pending"}):[]}static stringify(e){return JSON.stringify(e,null,2)}static validate(e){let t=[];if(!e)return{valid:!0,errors:[]};try{let n=this.normalize(e),i=new Set;for(let r of n.steps)if(i.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),i.add(r.id),r.dependencies)for(let o of r.dependencies)i.has(o)||t.push(`Step "${r.id}" depends on non-existent step "${o}"`);return{valid:t.length===0,errors:t}}catch(n){return t.push(`Strategy validation failed: ${n instanceof Error?n.message:String(n)}`),{valid:!1,errors:t}}}};var jc=[{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"}],Bc=[{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"}],zc=[{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"}],Gc=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:jc},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:Bc},{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:zc}],ho=new Map(Gc.map(s=>[s.id,s]));function qc(s){return ho.get(s)}function Jc(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function fo(s,e,t={}){let n=qc(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(ho.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=Jc(n.defaultGoal,{...t,target:i}),l=Ne.normalize({steps:n.steps}),c=Ne.stringify(l);return{name:r,goal:o,strategy:c}}F();var Hn=_.child({module:"mcp:tools:ops:plan"});async function go(s){let{repoPath:e,name:t,goal:n,strategy:i,missionId:r,parentId:o,outcomeContract:l,templateId:c,templateVars:a}=s,{missions:p}=k.getInstance(e),d=se(e),u=fe(e);Hn.info({repoPath:e,name:t,missionId:r,templateId:c},"Planning mission");try{let m=t,h=n,b=i;if(c){let S=fo(c,t,a||{});m=m??S.name,h=h??S.goal,b=b??S.strategy}if(!m||!h)throw new Error("Mission requires name and goal (or templateId with optional templateVars).");let E=null;if(b){let S=Ne.normalize(b);E=Ne.stringify(S);let w=Ne.validate(E);w.valid||Hn.warn({errors:w.errors,strategy:b},"Strategy validation warnings detected")}let g,y;r?(p.update(r,{name:m,goal:h,strategy_graph:E,commit_sha:u,parent_id:o!==void 0?o:void 0,outcome_contract:l}),g=r,y=`Mission "${m}" updated.`):(g=p.create({name:m,goal:h,strategy_graph:E,status:"planned",git_branch:d,commit_sha:u,parent_id:o||null,verification_context:null,outcome_contract:l||null}),y=`Mission "${m}" planned.`);try{await new Re(e).syncMissionToGitNotes(Number(g))}catch(S){Hn.warn({syncError:S,missionId:g},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:g,status:"planned",message:y,strategy_saved:!!b,contract_saved:!!l,from_template:c??void 0,commit:u},null,2)}]}}catch(m){throw Hn.error({error:m,repoPath:e},"Failed to plan mission"),new Error(`Failed to plan mission: ${m instanceof Error?m.message:String(m)}`)}}N();F();F();N();var Yc=_.child({module:"collision-service"}),Wn=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=se(this.repoPath);if(!e)return[];let{missions:t,intentLogs:n}=k.getInstance(this.repoPath),i=t.findActive().filter(l=>l.git_branch&&l.git_branch!==e),r=[],o=new Set;for(let l of i){let c=l.git_branch;if(o.has(c))continue;o.add(c),Yc.info({branch:c,currentBranch:e},"Checking predictive collisions"),qs(this.repoPath,e,c)&&r.push({branch:c,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${c}'.`});let p=t.findActive(e),d=new Set;for(let h of p)t.getWorkingSet(h.id).forEach(b=>d.add(b.file_path));let m=t.getWorkingSet(l.id).filter(h=>d.has(h.file_path));m.length>0&&r.push({branch:c,type:"intent",description:`Logical conflict: Mission '${l.name}' on '${c}' is modifying files you are currently working on.`,conflictingFiles:m.map(h=>h.file_path)})}return r}};var Wt=_.child({module:"mcp:tools:ops:briefing"});async function yo(s){let{repoPath:e,missionId:t,branch:n,scope:i="mission"}=s,{missions:r,intentLogs:o}=k.getInstance(e),l=fe(e),c=se(e);Wt.info({repoPath:e,missionId:t,branch:n,scope:i},"Generating briefing");try{if(i==="project"){let m=r.findActive(n),h=r.findParentOnlyIds(m),b=new Set(h),E=m.filter(R=>!b.has(R.id)),g={};for(let R of m)R.parent_id!=null&&(g[R.parent_id]||(g[R.parent_id]=[]),g[R.parent_id].push(R));let y={},S=new Map(m.map(R=>[R.id,R])),w=Object.keys(g).map(Number),C=w.filter(R=>!S.has(R)),T=C.length>0?r.findByIds(C):[],I=new Map(S);for(let R of T)I.set(R.id,R);for(let R of w){let v=I.get(R);v&&(y[R]={id:v.id,name:v.name??"",goal:v.goal??"",status:v.status??"unknown"})}let x={scope:"project",counts:r.getStats(),analytics:r.getAnalytics(),active_missions:m,parent_only_ids:h,missions_by_parent:g,parents_summary:Object.keys(y).length?y: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:E,recent_completed:r.findRecentCompleted(),recent_activity:o.findRecentDecisionActivity(),meta:{current_branch:c,current_commit:l}};if(s.includeGroupedByParent){let R=h.map(v=>{let P=m.find(H=>H.id===v),L=g[v]??[];return{parent:P,children:L}});x.missions_grouped_by_parent=R}let $=E.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(x,null,2)}],suggestedNext:$}}let a;if(t?a=r.findById(t):a=r.findActive(n||c||void 0)[0],!a)return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let p="No external shadow changes detected.";try{new mt(e).analyzeGhostChanges(a.commit_sha||void 0),p="Shadow Trace completed: Checked for external modifications."}catch(m){Wt.warn({error:m},"Ghost analysis failed")}let d={repaired:0,failed:0};try{d=new _e(e).detectAndRepairShifts()}catch(m){Wt.warn({error:m},"Symbol shift repair failed")}let u={mission:{id:a.id,name:a.name,goal:a.goal,status:a.status,last_updated:new Date(a.updated_at*1e3).toISOString(),git_branch:a.git_branch,commit_sha:a.commit_sha,outcome_contract:a.outcome_contract},artifacts:r.getArtifacts(a.id),shadow_trace:{ghost_analysis:p,symbols_repaired:d.repaired,symbols_missing:d.failed},context:{current_commit:l,working_set:r.getWorkingSet(a.id).map(m=>m.file_path)},strategy_snapshot:a.strategy_graph?JSON.parse(a.strategy_graph):null,recent_activity:o.findByMission(a.id,15),ancestor_activity:[],predictive_collisions:[]};try{let m=new Wn(e);u.predictive_collisions=await m.analyzePotentialCollisions()}catch(m){Wt.warn({error:m},"Predictive collision analysis failed")}if(s.includeLineage){let b=new tt(e).getAncestorMissionIds().filter(E=>E!==a?.id);if(b.length>0)for(let E of b){let g=o.findByMission(E,5);u.ancestor_activity.push(...g)}}return{content:[{type:"text",text:JSON.stringify(u,null,2)}]}}catch(a){throw Wt.error({error:a,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${a instanceof Error?a.message:String(a)}`)}}N();F();F();N();N();var Vc=_.child({module:"reasoning-engine"}),Un=class{analyze(e){Vc.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[]};for(let n of e){let i=n.content.toLowerCase(),r=this.matchesContext(i,n.type),o=this.matchesDecision(i,n.type),l=this.matchesConsequence(i,n.type),c=this.matchesRecommendation(i,n.type);r?t.context.push(n.content):o?t.decisions.push(n.content):c?t.recommendations.push(n.content):l?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(i=>e.includes(i))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(i=>e.includes(i))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(i=>e.includes(i))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(i=>e.includes(i))}};var jn=_.child({module:"briefing-engine"}),ze=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=k.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Un,this.persistencePivot=new Re(e)}async distillMission(e,t=!0){jn.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.gatherConsolidatedLogs(e);if(n.length===0)return{missionId:e,adr:"No intent logs found for this mission.",metrics:{totalLogs:0,symbolCount:0}};let i=this.reasoningEngine.analyze(n),r=new Set(n.map(l=>l.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
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}
746
792
 
747
793
  `;if(o+=`## Summary of Intent
748
794
  `,o+=`Collected ${n.length} intent events across ${r.size} symbols.
749
795
 
750
- `,i.context.length>0&&(o+=`### Context
751
- `,i.context.forEach(l=>{o+=`- ${l}
796
+ `,s.context.length>0&&(o+=`### Context
797
+ `,s.context.forEach(c=>{o+=`- ${c}
752
798
  `}),o+=`
753
- `),i.decisions.length>0&&(o+=`### Key Decisions
754
- `,i.decisions.forEach(l=>{o+=`- ${l}
799
+ `),s.decisions.length>0&&(o+=`### Key Decisions
800
+ `,s.decisions.forEach(c=>{o+=`- ${c}
755
801
  `}),o+=`
756
- `),i.consequences.length>0&&(o+=`### Consequences & Evolutions
757
- `,i.consequences.forEach(l=>{o+=`- ${l}
802
+ `),s.consequences.length>0&&(o+=`### Consequences & Evolutions
803
+ `,s.consequences.forEach(c=>{o+=`- ${c}
758
804
  `}),o+=`
759
- `),i.recommendations.length>0&&(o+=`### Strategic Recommendations
760
- `,i.recommendations.forEach(l=>{o+=`- ${l}
805
+ `),s.recommendations.length>0&&(o+=`### Strategic Recommendations
806
+ `,s.recommendations.forEach(c=>{o+=`- ${c}
761
807
  `}),o+=`
762
- `),i.unclassified.length>0&&(o+=`### Additional Notes
763
- `,i.unclassified.forEach(l=>{o+=`- ${l}
808
+ `),s.unclassified.length>0&&(o+=`### Additional Notes
809
+ `,s.unclassified.forEach(c=>{o+=`- ${c}
764
810
  `}),o+=`
765
811
  `),o+=`
766
812
  ---
767
- *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),jn.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(l){jn.error({missionId:e,error:l},"Failed to sync ADR to Git Notes")}}else jn.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 i=this.missions.findByParentId(e);for(let r of i)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};N();import{Visitor as Qc}from"@swc/core/Visitor.js";import*as bo from"@swc/core";var Kc=_.child({module:"verification-engine"}),Li=class extends Qc{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)}},Bn=class{async verify(e,t){try{let n=await bo.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new Li(t);i.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=i.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=i.foundUsage,!r){let l=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${l} 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 Kc.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};import Eo from"path";import zn from"fs";var bt=_.child({module:"mcp:tools:ops:track"});async function So(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:l}=s,{missions:c,intentLogs:a}=k.getInstance(e),p=fe(e);bt.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:l?.length},"Updating mission status");try{if(l&&Array.isArray(l))for(let m of l)c.addArtifact(t,m.type,m.identifier,m.metadata);let d=[];if(o&&Array.isArray(o)&&d.push(...o),n&&i&&d.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(c.updateStatus(t,i,p||void 0),a.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),i==="completed")try{await new ze(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:i,message:"Mission status updated successfully.",artifacts_added:l?.length||0,commit:p},null,2)}]}}if(d.length===0&&(!l||l.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:h,status:b,contextPivot:E}=m,g=c.findById(t);if(!g)throw new Error(`Mission ID ${t} not found`);let y=JSON.parse(g.strategy_graph||"{}"),S=null;if(Array.isArray(y)?S=y.find(w=>w.id===h):y.nodes&&Array.isArray(y.nodes)?S=y.nodes.find(w=>w.id===h):y.steps?Array.isArray(y.steps)?S=y.steps.find(w=>w.id===h):S=y.steps[h]:y[h]&&(S=y[h]),!S)throw new Error(`Step ID "${h}" not found`);if(b==="completed"&&S.verification){let w=new Bn,C=Array.isArray(S.verification)?S.verification:[S.verification];for(let T of C){let I=T.filePath;if(I&&!Eo.isAbsolute(I)&&(I=Eo.join(e,I)),I){if(!zn.existsSync(I))throw new Error(`Verification failed: File not found at ${I}`);let x=await w.verify(zn.readFileSync(I,"utf8"),T);if(!x.passed)throw new Error(`Verification failed: ${x.errors.join("")}`)}else{let x=c.getWorkingSet(t),$=!1;for(let R of x){if(!zn.existsSync(R.file_path))continue;if((await w.verify(zn.readFileSync(R.file_path,"utf8"),T)).passed){$=!0;break}}if(!$)throw new Error(`Verification failed for rule "${T.target}" in working set.`)}}}if(S.status=b,c.update(t,{strategy_graph:JSON.stringify(y),commit_sha:p}),a.create({mission_id:t,type:"system",content:`Step "${h}" updated to "${b}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),E)try{let w=JSON.parse(E);if(c.clearWorkingSet(t),w.files&&Array.isArray(w.files))for(let C of w.files)c.addToWorkingSet(t,C)}catch(w){bt.warn({error:w},"Failed to apply context pivot")}u.push({stepId:h,status:b})}try{await new Re(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:l?.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)}`)}}N();var To=_.child({module:"mcp:tools:ops:graph"});async function vo(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;To.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(Ro(),xo));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw To.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}F();N();var Ut=_.child({module:"mcp:tools:ops:log"});async function wo(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o}=s;Ut.info({repoPath:e,type:n,symbolName:o},"Logging intent");let{missions:l,exports:c,intentLogs:a}=k.getInstance(e);try{let p=t??null;if(p){if(!l.findById(p))throw new Error(`Mission ${p} not found. Use shadow_ops_briefing to see available missions.`)}else{let b=l.findActive();b.length>0?(p=b[0].id,Ut.debug({missionId:p},"Auto-resolved to active mission")):(p=null,Ut.debug("No active mission found, logging as system/unlinked intent"))}let d=null,u=null,m=o||null;if(o){let E=(r?c.findByNameAndFile(o,r):c.findByName(o))[0];E?(d=E.id,u=E.signature,m=E.name):Ut.warn({symbolName:o,filePath:r},"Symbol not found for intent linking")}let h=a.create({mission_id:p,symbol_id:d,file_path:r||null,type:n,content:i,confidence:1,symbol_name:m,signature:u,commit_sha:null});return{content:[{type:"text",text:JSON.stringify({logId:h,missionId:p,symbolId:d,status:"logged",message:d?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(p){throw Ut.error({error:p,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${p instanceof Error?p.message:String(p)}`)}}F();N();var Io=_.child({module:"mcp:tools:ops:synthesize"});async function ko(s){let{repoPath:e,missionId:t}=s;Io.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=k.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(i){throw Io.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}import Xc from"path";var q={...f,box:te,table:rn,list:rs};async function Co(s){let[e,...t]=s;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 U(async()=>{let n=t[0]?Xc.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${q.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let l=await go({repoPath:n,name:r,goal:o}),c=JSON.parse(l.content[0].text);console.log(` ${q.green("\u2714")} Mission planned (ID: ${c.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${q.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await So({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${q.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...l]=t;if(!r||!o||l.length===0){console.error(` ${q.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await wo({repoPath:n,missionId:parseInt(r),type:o,content:l.join(" ")}),console.log(` ${q.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${q.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await ko({repoPath:n,missionId:parseInt(r)});console.log(""),q.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await vo({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i,r=t.indexOf("--branch");r!==-1&&t[r+1]&&(i=t[r+1]);let o=await yo({repoPath:n,branch:i});if(o.content&&o.content[0]){let l=o.content[0].text;try{let c=JSON.parse(l);if(c.mission){console.log(""),console.log(q.bold(q.cyan(` Mission Dashboard: ${c.mission.name} `))),q.box("Tactical Goal",c.mission.goal,"cyan");let a=c.mission.status==="completed"?"green":c.mission.status==="failed"?"red":"yellow",p=[["Status",q.bold(q[a](c.mission.status.toUpperCase()))],["ID",`#${c.mission.id}`],["Branch",c.mission.git_branch||"main"]];q.table(["Field","Value"],p),c.recent_activity&&c.recent_activity.length>0&&(console.log(` ${q.bold("Recent Activity:")}`),q.list(c.recent_activity.slice(0,5).map(d=>`${q.dim(`[${d.type.toUpperCase()}]`)} ${d.content}`)))}else console.log(l)}catch{console.log(l)}}break}}})}import Ni from"path";async function Lo(s){let[e,...t]=s;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 U(async()=>{let n=t[0]?Ni.resolve(t[0]):process.cwd();if(e==="symbol"){let i=t[1];if(!i){console.error(` ${f.red("\u2716")} Please provide a symbol name`);return}let r=await gt({repoPath:n,symbolName:i});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let i=t[1];if(!i){console.error(` ${f.red("\u2716")} Please provide a file path`);return}let r=Ni.isAbsolute(i)?i:Ni.join(n,i),o=await An({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var $o=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],Zc=["--help","-h","--version","-v","--dir","-d"],el={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 tl(){let s=Object.entries(el).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
768
- `),e=$o.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
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=Do.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
769
815
  _liquid_shadow() {
770
816
  local cur="\${COMP_WORDS[COMP_CWORD]}"
771
817
  local words=("\${COMP_WORDS[@]}")
@@ -775,10 +821,10 @@ _liquid_shadow() {
775
821
  if [[ "\${words[$i]}" != -* ]]; then cmd="\${words[$i]}"; break; fi
776
822
  ((i++))
777
823
  done
778
- local opts="${Zc.join(" ")}"
824
+ local opts="${ol.join(" ")}"
779
825
  if [ -n "$cmd" ]; then
780
826
  case "$cmd" in
781
- ${s}
827
+ ${i}
782
828
  esac
783
829
  else
784
830
  COMPREPLY=($(compgen -W "${e}" -- "$cur"))
@@ -787,11 +833,11 @@ ${s}
787
833
  COMPREPLY=($(compgen -W "$opts" -- "$cur"))
788
834
  }
789
835
  complete -F _liquid_shadow liquid-shadow
790
- `}function nl(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
836
+ `}function ll(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
791
837
  # Run after compinit (e.g. in .zshrc after compinit)
792
838
 
793
839
  _liquid_shadow() {
794
- local -a cmds; cmds=(${$o.map(e=>`'${e}'`).join(" ")})
840
+ local -a cmds; cmds=(${Do.map(e=>`'${e}'`).join(" ")})
795
841
  if [ $CURRENT -eq 2 ]; then
796
842
  _describe 'command' cmds
797
843
  return
@@ -808,7 +854,7 @@ _liquid_shadow() {
808
854
  _describe 'flag' fl
809
855
  }
810
856
  compdef _liquid_shadow liquid-shadow
811
- `}async function No(s){s==="bash"?console.log(tl()):s==="zsh"?console.log(nl()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}import il from"fs";import sl from"path";var rl=2e3;async function Ao(s){let e=sl.resolve(s);await U(async()=>{le("Watch mode");let t=we(e),n=null,i=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(f.dim(" Changes detected, reindexing...")),await j(e,5,!1,!0),console.log(f.green(" Reindex complete."))}catch(r){console.error(f.red(" Reindex failed:"),r instanceof Error?r.message:r)}},rl)};try{il.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&i()}),console.log(f.cyan(` Watching ${e}`)),console.log(f.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),Rt("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 G(e)}})}F();N();var ol=_.child({module:"narrative-service"}),Gn=class{missions;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t}=k.getInstance(e);this.missions=t,this.briefingEngine=new ze(e)}async generateChronicle(e={}){ol.info(e,"Generating Repo Chronicle...");let n=this.missions.findAll().filter(a=>a.parent_id===null&&a.status!=="planned");e.since&&(n=n.filter(a=>a.updated_at>=e.since)),e.until&&(n=n.filter(a=>a.updated_at<=e.until)),n.sort((a,p)=>p.updated_at-a.updated_at);let i=e.offset||0,r=e.limit||10;n=n.slice(i,i+r);let o=[],l=[],c=[];for(let a of n){let p=this.missions.findByParentId(a.id),d=p.length>0,u=await this.briefingEngine.distillMission(a.id,!1);if(d){let m=[];for(let b of p)m.push(await this.mapMissionToEpisode(b));m.unshift(await this.mapMissionToEpisode(a));let h={kind:"initiative",root_mission_id:a.id,title:a.name,strategy_graph:a.strategy_graph?JSON.parse(a.strategy_graph):{},episodes:m,synthesized_narrative:u.adr};o.push(h),c.push(h)}else{let m=await this.mapMissionToEpisode(a,u.adr);l.push(m),c.push(m)}}return{repo_path:this.repoPath,generated_at:Date.now(),initiatives:o,unattached_episodes:l,timeline:c}}async mapMissionToEpisode(e,t){let n=t;return n||(n=(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}}renderChronicleMarkdown(e){let t=`# Repository Chronicle
857
+ `}async function Oo(i){i==="bash"?console.log(cl()):i==="zsh"?console.log(ll()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}import pl from"fs";import ul from"path";var dl=2e3;async function Fo(i){let e=ul.resolve(i);await B(async()=>{le("Watch mode");let t=Ce(e),n=null,s=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(E.dim(" Changes detected, reindexing...")),await z(e,5,!1,!0),console.log(E.green(" Reindex complete."))}catch(r){console.error(E.red(" Reindex failed:"),r instanceof Error?r.message:r)}},dl)};try{pl.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&s()}),console.log(E.cyan(` Watching ${e}`)),console.log(E.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),Tt("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 q(e)}})}U();P();var ml=_.child({module:"narrative-service"}),Jn=class{missions;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t}=C.getInstance(e);this.missions=t,this.briefingEngine=new Ge(e)}async generateChronicle(e={}){ml.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),d=p.length>0,u=await this.briefingEngine.distillMission(l.id,!1);if(d){let m=[];for(let h of p)m.push(await this.mapMissionToEpisode(h));m.unshift(await this.mapMissionToEpisode(l));let f={kind:"initiative",root_mission_id:l.id,title:l.name,strategy_graph:l.strategy_graph?JSON.parse(l.strategy_graph):{},episodes:m,synthesized_narrative:u.adr};o.push(f),a.push(f)}else{let m=await this.mapMissionToEpisode(l,u.adr);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){let n=t;return n||(n=(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}}renderChronicleMarkdown(e){let t=`# Repository Chronicle
812
858
 
813
859
  `;if(t+=`*Generated at ${new Date(e.generated_at).toISOString()}*
814
860
 
@@ -819,4 +865,4 @@ compdef _liquid_shadow liquid-shadow
819
865
  `,t+=`${n.adr_summary}
820
866
 
821
867
  `),t+=`---
822
- `;return t}};N();import al from"path";async function Mo(s,e){let t=al.resolve(s||process.cwd()),n=e.format==="json"?"json":"markdown",i=_.child({module:"cli:chronicle",repoPath:t});i.info("Generating repository chronicle...");try{let r=new Gn(t),o=await r.generateChronicle({limit:e.limit,offset:e.offset,since:e.since,until:e.until});console.log(n==="json"?JSON.stringify(o,null,2):r.renderChronicleMarkdown(o))}catch(r){i.error({error:r},"Failed to generate chronicle"),console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}}function ae(s){let e=process.cwd();return Oi(e,s.flags)}process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),G().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),G().then(()=>process.exit(1))});var Z=cl().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 s=>{let e=ae(s),t={...s.flags,dir:s.flags.dir??e.dir,level:s.flags.level??e.level,deep:s.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await nr(s.parameters.dir||e.dir,t)});Z.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=ae(s);await fs(s.parameters.dir||e.dir)});Z.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=ae(s);await xs(s.parameters.dir||e.dir)});Z.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=ae(s);await sr(s.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 s=>{let e=ae(s);await Zs(s.parameters.dir||e.dir,{...s.flags,dir:s.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 s=>{let e=ae(s);await zr(s.parameters.mode,s.parameters.dir||e.dir,{...s.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 s=>{let e=ae(s);await cr(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});Z.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"],flags:{since:{type:String,description:"Analyze since specific commit hash"}}}).on("sync",async s=>{let e=ae(s);await Ur(s.parameters.dir||e.dir,{sinceCommit:s.flags.since||void 0})});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 s=>{let e=ae(s);await to(s.parameters.key,{...s.flags,dir:s.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 s=>{let e=ae(s);await Xr(s.parameters.query,{...s.flags,dir:s.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 s=>{let e=ae(s);await Zr(s.parameters.query,{...s.flags,dir:s.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 s=>{let e=ae(s);await eo(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});Z.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async s=>{await no([s.parameters.action,s.parameters.path])});Z.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async s=>{await mo([s.parameters.action,...s.parameters.args])});Z.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async s=>{await Co([s.parameters.action,...s.parameters.args])});Z.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async s=>{await Lo([s.parameters.mode,...s.parameters.args])});Z.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=ae(s);await Ao(s.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 s=>{let e=ae(s);await Mo(s.parameters.dir||e.dir,{...s.flags,format:s.flags.format,limit:s.flags.limit?parseInt(String(s.flags.limit),10):void 0,offset:s.flags.offset?parseInt(String(s.flags.offset),10):void 0,since:s.flags.since?Math.floor(new Date(String(s.flags.since)).getTime()/1e3):void 0,until:s.flags.until?Math.floor(new Date(String(s.flags.until)).getTime()/1e3):void 0})});Z.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async s=>{await No(s.parameters.shell||"")});Z.parse();
868
+ `;return t}};P();import hl from"path";async function Ho(i,e){let t=hl.resolve(i||process.cwd()),n=e.format==="json"?"json":"markdown",s=_.child({module:"cli:chronicle",repoPath:t});s.info("Generating repository chronicle...");try{let r=new Jn(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)}}function ce(i){let e=process.cwd();return js(e,i.flags)}process.on("unhandledRejection",i=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",i),q().then(()=>process.exit(1))});process.on("uncaughtException",i=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",i),q().then(()=>process.exit(1))});var ee=fl().name("liquid-shadow").version("1.0.2").description("Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem").scriptName("liquid-shadow");ee.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=ce(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 or(i.parameters.dir||e.dir,t)});ee.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async i=>{let e=ce(i);await Ei(i.parameters.dir||e.dir)});ee.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async i=>{let e=ce(i);await wi(i.parameters.dir||e.dir)});ee.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async i=>{let e=ce(i);await cr(i.parameters.dir||e.dir)});ee.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=ce(i);await sr(i.parameters.dir||e.dir,{...i.flags,dir:i.flags.dir??e.dir})});ee.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=ce(i);await Yr(i.parameters.mode,i.parameters.dir||e.dir,{...i.flags})});ee.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=ce(i);await dr(i.parameters.file,{...i.flags,dir:i.flags.dir??e.dir,symbolName:i.parameters.symbolName})});ee.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"]}).on("sync",async i=>{let e=ce(i);await Gr(i.parameters.dir||e.dir,{})});ee.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=ce(i);await ro(i.parameters.key,{...i.flags,dir:i.flags.dir??e.dir})});ee.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=ce(i);await no(i.parameters.query,{...i.flags,dir:i.flags.dir??e.dir})});ee.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=ce(i);await so(i.parameters.query,{...i.flags,dir:i.flags.dir??e.dir})});ee.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=ce(i);await io(i.parameters.query,{...i.flags,dir:i.flags.dir??e.dir})});ee.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async i=>{await oo([i.parameters.action,i.parameters.path])});ee.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async i=>{await yo([i.parameters.action,...i.parameters.args])});ee.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async i=>{await Mo([i.parameters.action,...i.parameters.args])});ee.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async i=>{await Po([i.parameters.mode,...i.parameters.args])});ee.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async i=>{let e=ce(i);await Fo(i.parameters.dir||e.dir)});ee.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=ce(i);await Ho(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})});ee.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async i=>{await Oo(i.parameters.shell||"")});ee.parse();