@precisionutilityguild/liquid-shadow 1.0.7 → 1.0.10

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.
Files changed (40) hide show
  1. package/README.md +3 -3
  2. package/dist/data/migrations/000_baseline.sql +27 -0
  3. package/dist/data/migrations/013_file_claims.sql +18 -0
  4. package/dist/data/migrations/014_tribunal_state.sql +24 -0
  5. package/dist/data/migrations/015_repo_level_handoffs_nullable.sql +52 -0
  6. package/dist/data/migrations/016_repair_tribunal_artifact_fk.sql +58 -0
  7. package/dist/entry/cli/index.js +597 -495
  8. package/dist/entry/ember/index.js +109 -32
  9. package/dist/entry/mcp/server.js +443 -347
  10. package/dist/entry/tribunal/index.js +650 -0
  11. package/dist/index.js +441 -345
  12. package/dist/logic/parser/index.js +16 -14
  13. package/dist/skills/shadow_audit/SKILL.md +22 -30
  14. package/dist/skills/shadow_chronicle/SKILL.md +16 -29
  15. package/dist/skills/shadow_continue/SKILL.md +37 -53
  16. package/dist/skills/shadow_coordinate/SKILL.md +46 -0
  17. package/dist/skills/shadow_crystallize/SKILL.md +13 -27
  18. package/dist/skills/shadow_mission/SKILL.md +27 -41
  19. package/dist/skills/shadow_onboard/SKILL.md +26 -35
  20. package/dist/skills/shadow_research/SKILL.md +15 -23
  21. package/dist/skills/shadow_sync/SKILL.md +18 -9
  22. package/dist/skills/shadow_synthesize/SKILL.md +14 -36
  23. package/dist/skills/shadow_trace_impact/SKILL.md +30 -50
  24. package/dist/skills/shadow_understand/SKILL.md +37 -52
  25. package/dist/skills/shadow_workspace/SKILL.md +17 -17
  26. package/dist/web-manifest.json +16 -6
  27. package/package.json +1 -1
  28. package/skills/shadow_audit/SKILL.md +22 -30
  29. package/skills/shadow_chronicle/SKILL.md +16 -29
  30. package/skills/shadow_continue/SKILL.md +37 -53
  31. package/skills/shadow_coordinate/SKILL.md +46 -0
  32. package/skills/shadow_crystallize/SKILL.md +13 -27
  33. package/skills/shadow_mission/SKILL.md +27 -41
  34. package/skills/shadow_onboard/SKILL.md +26 -35
  35. package/skills/shadow_research/SKILL.md +15 -23
  36. package/skills/shadow_sync/SKILL.md +18 -9
  37. package/skills/shadow_synthesize/SKILL.md +14 -36
  38. package/skills/shadow_trace_impact/SKILL.md +30 -50
  39. package/skills/shadow_understand/SKILL.md +37 -52
  40. package/skills/shadow_workspace/SKILL.md +17 -17
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDescriptor;var Wc=Object.getOwnPropertyNames;var Hc=Object.getPrototypeOf,zc=Object.prototype.hasOwnProperty;var Uc=(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 Z=(s,e)=>()=>(s&&(e=s(s=0)),e);var jc=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),qi=(s,e)=>{for(var t in e)Gi(s,t,{get:e[t],enumerable:!0})},Bc=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Wc(e))!zc.call(s,i)&&i!==t&&Gi(s,i,{get:()=>e[i],enumerable:!(n=Fc(e,i))||n.enumerable});return s};var Gc=(s,e,t)=>(t=s!=null?Oc(Hc(s)):{},Bc(e||!s||!s.__esModule?Gi(t,"default",{value:s,enumerable:!0}):t,s));import qc from"pino";var Vc,Jc,S,q=Z(()=>{"use strict";Vc={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},Jc=qc({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:Vc[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),S=Jc});import Et from"fs";import xn from"path";import{fileURLToPath as Qc}from"url";function el(){let s=Zc;if(Et.readdirSync(s).some(n=>n.match(/^\d{3}_.*\.sql$/)))return s;let t=xn.resolve(s,"../../data/migrations");return Et.existsSync(t)&&Et.readdirSync(t).some(n=>n.match(/^\d{3}_.*\.sql$/))?t:s}function tl(s){s.exec(`
2
+ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDescriptor;var hl=Object.getOwnPropertyNames;var gl=Object.getPrototypeOf,yl=Object.prototype.hasOwnProperty;var bl=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ee=(s,e)=>()=>(s&&(e=s(s=0)),e);var _l=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),us=(s,e)=>{for(var t in e)ps(s,t,{get:e[t],enumerable:!0})},El=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hl(e))!yl.call(s,i)&&i!==t&&ps(s,i,{get:()=>e[i],enumerable:!(n=fl(e,i))||n.enumerable});return s};var Sl=(s,e,t)=>(t=s!=null?ml(gl(s)):{},El(e||!s||!s.__esModule?ps(t,"default",{value:s,enumerable:!0}):t,s));import xl from"pino";var wl,vl,x,G=ee(()=>{"use strict";wl={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},vl=xl({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:wl[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),x=vl});import Pt from"fs";import Fn from"path";import{fileURLToPath as kl}from"url";function Ll(){let s=Il;if(Pt.readdirSync(s).some(n=>n.match(/^\d{3}_.*\.sql$/)))return s;let t=Fn.resolve(s,"../../data/migrations");return Pt.existsSync(t)&&Pt.readdirSync(t).some(n=>n.match(/^\d{3}_.*\.sql$/))?t:s}function Ml(s){s.exec(`
3
3
  CREATE TABLE IF NOT EXISTS schema_migrations (
4
4
  version INTEGER PRIMARY KEY,
5
5
  name TEXT NOT NULL,
6
6
  applied_at REAL DEFAULT (unixepoch())
7
7
  );
8
- `)}function nl(s){tl(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function il(s){return Et.readdirSync(s).filter(t=>t.match(/^\d{3}_.*\.sql$/)&&!t.startsWith("000_")).sort().map(t=>{let n=t.match(/^(\d{3})_(.+)\.sql$/),i=parseInt(n[1],10),r=n[2],a=Et.readFileSync(xn.join(s,t),"utf-8").split(/^-- DOWN$/m);return{version:i,name:r,up:a[0].trim(),down:a[1]?.trim()}})}function sl(s,e){st.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)})(),st.info({version:e.version},"Migration applied successfully")}function rl(s,e,t){let n=xn.join(e,"000_baseline.sql");if(!Et.existsSync(n)){st.warn("000_baseline.sql not found \u2014 falling back to incremental migrations");return}st.info("Fresh database detected \u2014 applying consolidated baseline schema");let i=Et.readFileSync(n,"utf-8");s.transaction(()=>{s.exec(i);let r=s.prepare("INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (?, ?)");for(let o of t)r.run(o.version,o.name)})(),st.info({stamped:t.length},"Baseline applied \u2014 incremental migrations stamped")}function tr(s){let e=nl(s),t=el(),n=il(t);if(e.size===0){rl(s,t,n);return}let i=n.filter(r=>!e.has(r.version));if(i.length===0){st.debug("No pending migrations");return}st.info({count:i.length},"Running pending migrations");for(let r of i)sl(s,r);st.info("All migrations complete")}var st,Xc,Zc,nr=Z(()=>{"use strict";q();st=S.child({module:"migrations"}),Xc=Qc(import.meta.url),Zc=xn.dirname(Xc)});import ol from"better-sqlite3";import vn from"path";import Ji from"fs";import ir from"crypto";import al from"os";function Rn(s){let e=al.homedir(),t=vn.join(e,".mcp-liquid-shadow"),n=vn.join(t,"dbs");Ji.existsSync(n)||Ji.mkdirSync(n,{recursive:!0});let i=ir.createHash("sha256").update(s).digest("hex").substring(0,12),o=`${vn.basename(s).replace(/[^a-zA-Z0-9-_]/g,"_")}_${i}.db`;return vn.join(n,o)}function cl(s,e){let t=e||Rn(s);Qe.debug({repoPath:s,dbPath:t},"Initializing database");let n=new ol(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),tr(n),Tn.set(s,t),rt.set(t,n),Qe.debug({repoPath:s,dbPath:t},"Database initialized successfully"),n}function Nt(s){return ir.createHash("sha256").update(s,"utf8").digest("hex")}function sr(s,e){return e?Nt(s)!==e:!0}function Te(s){let e=Tn.get(s)||Rn(s),t=rt.get(e);if(t){if(t.open)return t;rt.delete(e)}let n=cl(s);return rt.set(e,n),n}function Xe(s){let e=Rn(s);if(!Ji.existsSync(e))return!1;try{let t=Te(s);return t.prepare(`
8
+ `)}function $l(s){Ml(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function Al(s){return Pt.readdirSync(s).filter(t=>t.match(/^\d{3}_.*\.sql$/)&&!t.startsWith("000_")).sort().map(t=>{let n=t.match(/^(\d{3})_(.+)\.sql$/),i=parseInt(n[1],10),r=n[2],a=Pt.readFileSync(Fn.join(s,t),"utf-8").split(/^-- DOWN$/m);return{version:i,name:r,up:a[0].trim(),down:a[1]?.trim()}})}function Nl(s,e){bt.info({version:e.version,name:e.name},"Applying migration"),s.transaction(()=>{s.exec(e.up),s.prepare("INSERT INTO schema_migrations (version, name) VALUES (?, ?)").run(e.version,e.name)})(),bt.info({version:e.version},"Migration applied successfully")}function Pl(s,e,t){let n=Fn.join(e,"000_baseline.sql");if(!Pt.existsSync(n)){bt.warn("000_baseline.sql not found \u2014 falling back to incremental migrations");return}bt.info("Fresh database detected \u2014 applying consolidated baseline schema");let i=Pt.readFileSync(n,"utf-8");s.transaction(()=>{s.exec(i);let r=s.prepare("INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (?, ?)");for(let o of t)r.run(o.version,o.name)})(),bt.info({stamped:t.length},"Baseline applied \u2014 incremental migrations stamped")}function Cr(s){let e=$l(s),t=Ll(),n=Al(t);if(e.size===0){Pl(s,t,n);return}let i=n.filter(r=>!e.has(r.version));if(i.length===0){bt.debug("No pending migrations");return}bt.info({count:i.length},"Running pending migrations");for(let r of i)Nl(s,r);bt.info("All migrations complete")}var bt,Cl,Il,Ir=ee(()=>{"use strict";G();bt=x.child({module:"migrations"}),Cl=kl(import.meta.url),Il=Fn.dirname(Cl)});import Dl from"better-sqlite3";import Wn from"path";import ms from"fs";import Lr from"crypto";import Ol from"os";function zn(s){let e=Ol.homedir(),t=Wn.join(e,".mcp-liquid-shadow"),n=Wn.join(t,"dbs");ms.existsSync(n)||ms.mkdirSync(n,{recursive:!0});let i=Lr.createHash("sha256").update(s).digest("hex").substring(0,12),o=`${Wn.basename(s).replace(/[^a-zA-Z0-9-_]/g,"_")}_${i}.db`;return Wn.join(n,o)}function Fl(s,e){let t=e||zn(s);pt.debug({repoPath:s,dbPath:t},"Initializing database");let n=new Dl(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),Cr(n),Hn.set(s,t),_t.set(t,n),pt.debug({repoPath:s,dbPath:t},"Database initialized successfully"),n}function Kt(s){return Lr.createHash("sha256").update(s,"utf8").digest("hex")}function Mr(s,e){return e?Kt(s)!==e:!0}function Oe(s){let e=Hn.get(s)||zn(s),t=_t.get(e);if(t){if(t.open)return t;_t.delete(e)}let n=Fl(s);return _t.set(e,n),n}function ut(s){let e=zn(s);if(!ms.existsSync(e))return!1;try{let t=Oe(s);return t.prepare(`
9
9
  SELECT value FROM index_metadata
10
10
  WHERE key = 'index_completed'
11
- `).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return Qe.debug({repoPath:s,error:t},"Error checking index status"),!1}}function Yi(s,e){let t=Te(s),n=t.prepare("INSERT OR REPLACE INTO index_metadata (key, value, updated_at) VALUES (?, ?, unixepoch())");t.transaction(()=>{n.run("index_completed","true"),n.run("last_indexed_at",Date.now().toString()),e&&n.run("last_indexed_commit",e)})(),Qe.debug({repoPath:s,commitSha:e},"Repository marked as indexed")}function nn(s){try{return Te(s).prepare(`
11
+ `).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return pt.debug({repoPath:s,error:t},"Error checking index status"),!1}}function fs(s,e){let t=Oe(s),n=t.prepare("INSERT OR REPLACE INTO index_metadata (key, value, updated_at) VALUES (?, ?, unixepoch())");t.transaction(()=>{n.run("index_completed","true"),n.run("last_indexed_at",Date.now().toString()),e&&n.run("last_indexed_commit",e)})(),pt.debug({repoPath:s,commitSha:e},"Repository marked as indexed")}function yn(s){try{return Oe(s).prepare(`
12
12
  SELECT value FROM index_metadata
13
13
  WHERE key = 'last_indexed_commit'
14
- `).get()?.value||null}catch(e){return Qe.debug({repoPath:s,error:e},"Error getting last indexed commit"),null}}function kn(s){let e=Tn.get(s)||Rn(s),t=rt.get(e);t&&(t.open&&(Qe.debug({repoPath:s,dbPath:e},"Closing database connection"),t.close()),rt.delete(e)),Tn.delete(s)}function rr(){for(let[s,e]of rt.entries())try{e.open&&(Qe.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){Qe.error({dbPath:s,err:t},"Error closing database execution")}rt.clear()}var Qe,rt,Tn,or,Ze=Z(()=>{"use strict";q();nr();Qe=S.child({module:"db"});rt=new Map,Tn=new Map;process.on("exit",()=>rr());or=s=>{Qe.debug({signal:s},"Received termination signal, closing databases"),rr(),process.exit(0)};process.on("SIGINT",()=>or("SIGINT"));process.on("SIGTERM",()=>or("SIGTERM"))});var ae,Ue=Z(()=>{"use strict";ae=class{db;constructor(e){this.db=e}get database(){return this.db}all(e,...t){return this.db.prepare(e).all(...t)}get(e,...t){return this.db.prepare(e).get(...t)}run(e,...t){return this.db.prepare(e).run(...t).changes}insert(e,...t){return this.db.prepare(e).run(...t).lastInsertRowid}transaction(e){return this.db.transaction(e)()}}});function pl(s,e){if(!s)return!1;let t=s.trim();return!t||ll.has(t.toLowerCase())||e.has(t)?!1:/^[A-Za-z_$][A-Za-z0-9_$.]*$/.test(t)}function ul(s){return s.split(/[,|&]/).map(e=>e.trim()).filter(Boolean)}function dl(s){let e=s.replace(/^[({\[]+/,"").replace(/[)}\]]+$/,"").replace(/^readonly\s+/,"").trim();return e&&e.match(/^([A-Za-z_$][A-Za-z0-9_$.]*)/)?.[1]||null}function ml(s){let e=[],t=0,n="",i=!1;for(let r of s){if(r==="<"&&(t++,t===1)){i=!0,n="";continue}if(r===">"&&(t>0&&t--,t===0&&i)){i=!1,n.trim()&&e.push(n),n="";continue}i&&(n+=r)}return e}function hl(s){let e=new Set;for(let t of s){let n=t.split(",").map(i=>i.trim());for(let i of n){let r=i.match(/^([A-Za-z_$][A-Za-z0-9_$]*)/);r?.[1]&&e.add(r[1])}}return e}function Ki(s,e){let t=[];for(let n of ul(s)){let i=dl(n);i&&pl(i,e)&&t.push(i)}return t}function ar(s){if(!s)return[];let e=s.replace(/\s+/g," ").trim();if(!e)return[];let t=ml(e),n=hl(t),i=[],r=new Set,o=(l,p,u)=>{let d=`${l}:${p}`;r.has(d)||(r.add(d),i.push({relationship:l,targetName:p,...u?{metadata:u}:{}}))},a=e.match(/\bextends\s+(.+?)(?=\bimplements\b|\{|=|$)/);if(a?.[1]){let l=Ki(a[1],n);for(let p of l)o("extends",p,a[1].trim())}let c=e.match(/\bimplements\s+(.+?)(?=\{|=|$)/);if(c?.[1]){let l=Ki(c[1],n);for(let p of l)o("implements",p,c[1].trim())}for(let l of t){let p=/([A-Za-z_$][A-Za-z0-9_$]*)\s+extends\s+([^,>]+)/g,u=null;for(;(u=p.exec(l))!==null;){let d=u[2]?.trim();if(!d)continue;let h=Ki(d,n);for(let m of h)o("constrained_by",m,d)}}return i}var ll,cr=Z(()=>{"use strict";ll=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","symbol","object","bigint","readonly","keyof","infer","extends","implements","class","interface","type","function","new"])});import fl from"path";var Cn,lr=Z(()=>{"use strict";Ue();cr();Cn=class extends ae{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=fl.resolve(e,t),i=n.endsWith("/")?n:n+"/";return this.all(`
14
+ `).get()?.value||null}catch(e){return pt.debug({repoPath:s,error:e},"Error getting last indexed commit"),null}}function Bn(s){let e=Hn.get(s)||zn(s),t=_t.get(e);t&&(t.open&&(pt.debug({repoPath:s,dbPath:e},"Closing database connection"),t.close()),_t.delete(e)),Hn.delete(s)}function $r(){for(let[s,e]of _t.entries())try{e.open&&(pt.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){pt.error({dbPath:s,err:t},"Error closing database execution")}_t.clear()}var pt,_t,Hn,Ar,dt=ee(()=>{"use strict";G();Ir();pt=x.child({module:"db"});_t=new Map,Hn=new Map;process.on("exit",()=>$r());Ar=s=>{pt.debug({signal:s},"Received termination signal, closing databases"),$r(),process.exit(0)};process.on("SIGINT",()=>Ar("SIGINT"));process.on("SIGTERM",()=>Ar("SIGTERM"))});var pe,qe=ee(()=>{"use strict";pe=class{db;constructor(e){this.db=e}get database(){return this.db}all(e,...t){return this.db.prepare(e).all(...t)}get(e,...t){return this.db.prepare(e).get(...t)}run(e,...t){return this.db.prepare(e).run(...t).changes}insert(e,...t){return this.db.prepare(e).run(...t).lastInsertRowid}transaction(e){return this.db.transaction(e)()}}});function Hl(s,e){if(!s)return!1;let t=s.trim();return!t||Wl.has(t.toLowerCase())||e.has(t)?!1:/^[A-Za-z_$][A-Za-z0-9_$.]*$/.test(t)}function zl(s){return s.split(/[,|&]/).map(e=>e.trim()).filter(Boolean)}function Bl(s){let e=s.replace(/^[({\[]+/,"").replace(/[)}\]]+$/,"").replace(/^readonly\s+/,"").trim();return e&&e.match(/^([A-Za-z_$][A-Za-z0-9_$.]*)/)?.[1]||null}function Ul(s){let e=[],t=0,n="",i=!1;for(let r of s){if(r==="<"&&(t++,t===1)){i=!0,n="";continue}if(r===">"&&(t>0&&t--,t===0&&i)){i=!1,n.trim()&&e.push(n),n="";continue}i&&(n+=r)}return e}function jl(s){let e=new Set;for(let t of s){let n=t.split(",").map(i=>i.trim());for(let i of n){let r=i.match(/^([A-Za-z_$][A-Za-z0-9_$]*)/);r?.[1]&&e.add(r[1])}}return e}function hs(s,e){let t=[];for(let n of zl(s)){let i=Bl(n);i&&Hl(i,e)&&t.push(i)}return t}function Nr(s){if(!s)return[];let e=s.replace(/\s+/g," ").trim();if(!e)return[];let t=Ul(e),n=jl(t),i=[],r=new Set,o=(c,p,u)=>{let d=`${c}:${p}`;r.has(d)||(r.add(d),i.push({relationship:c,targetName:p,...u?{metadata:u}:{}}))},a=e.match(/\bextends\s+(.+?)(?=\bimplements\b|\{|=|$)/);if(a?.[1]){let c=hs(a[1],n);for(let p of c)o("extends",p,a[1].trim())}let l=e.match(/\bimplements\s+(.+?)(?=\{|=|$)/);if(l?.[1]){let c=hs(l[1],n);for(let p of c)o("implements",p,l[1].trim())}for(let c of t){let p=/([A-Za-z_$][A-Za-z0-9_$]*)\s+extends\s+([^,>]+)/g,u=null;for(;(u=p.exec(c))!==null;){let d=u[2]?.trim();if(!d)continue;let h=hs(d,n);for(let m of h)o("constrained_by",m,d)}}return i}var Wl,Pr=ee(()=>{"use strict";Wl=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","symbol","object","bigint","readonly","keyof","infer","extends","implements","class","interface","type","function","new"])});import Gl from"path";var Un,Dr=ee(()=>{"use strict";qe();Pr();Un=class extends pe{findByPath(e){return this.get("SELECT * FROM files WHERE path = ?",e)}findAll(e){let t="SELECT * FROM files ORDER BY path ASC";return e&&(t+=` LIMIT ${e}`),this.all(t)}getAllPaths(){return this.all("SELECT path FROM files").map(t=>t.path)}findInSubPath(e,t){let n=Gl.resolve(e,t),i=n.endsWith("/")?n:n+"/";return this.all(`
15
15
  SELECT * FROM files
16
16
  WHERE (path LIKE ? OR path = ?)
17
17
  ORDER BY path ASC
@@ -57,14 +57,14 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=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 l of o){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.file_path].score+=p;let u=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.file_path].reasons.push(`${u}: ${l.mission_name}`)}let a=Math.floor(Date.now()/1e3)-86400,c=this.all(`
60
+ `,r=[];t&&r.push(t);let o=this.all(i,...r);for(let c of o){n[c.file_path]||(n[c.file_path]={score:1,reasons:[]});let p=c.status==="in-progress"||c.status==="verifying"?1:.5;n[c.file_path].score+=p;let u=c.status==="in-progress"||c.status==="verifying"?"Working Set":"Lineage Bleed";n[c.file_path].reasons.push(`${u}: ${c.mission_name}`)}let a=Math.floor(Date.now()/1e3)-86400,l=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
- `,a);for(let l of c){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.mission_id?e.includes(l.mission_id):!1,u=p?.1:.2;n[l.file_path].score<5&&(n[l.file_path].score+=u);let d=p?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.file_path].reasons.includes(d)&&n[l.file_path].reasons.length<5&&n[l.file_path].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
67
+ `,a);for(let c of l){n[c.file_path]||(n[c.file_path]={score:1,reasons:[]});let p=c.mission_id?e.includes(c.mission_id):!1,u=p?.1:.2;n[c.file_path].score<5&&(n[c.file_path].score+=u);let d=p?`Lineage Intent: ${c.type}`:`Recent Intent: ${c.type}`;!n[c.file_path].reasons.includes(d)&&n[c.file_path].reasons.length<5&&n[c.file_path].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
68
68
  SELECT
69
69
  SUBSTR(path, LENGTH(?) + 2,
70
70
  INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
@@ -87,7 +87,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
87
87
  SUBSTR(path, LENGTH(?) + 2) as relPath
88
88
  FROM files
89
89
  WHERE path LIKE ? || '/%/package.json'
90
- `,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(i=>{for(let r of i)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,i){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),a=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),l=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),p=this.db.prepare("DELETE FROM type_graph_edges WHERE file_path = ?"),u=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),h=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),f=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),_=this.db.prepare("INSERT INTO type_graph_edges (file_path, source_symbol_id, source_symbol_name, target_symbol_name, relationship, line_number, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)"),g=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(i=>{for(let r of i)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,i){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),a=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),l=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),c=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),p=this.db.prepare("DELETE FROM type_graph_edges WHERE file_path = ?"),u=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),h=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),f=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),b=this.db.prepare("INSERT INTO type_graph_edges (file_path, source_symbol_id, source_symbol_name, target_symbol_name, relationship, line_number, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)"),g=this.db.prepare(`
91
91
  INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
92
92
  VALUES (?, ?, ?, ?, ?, ?, ?)
93
93
  ON CONFLICT(path) DO UPDATE SET
@@ -97,7 +97,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
97
97
  summary=excluded.summary,
98
98
  embedding=excluded.embedding,
99
99
  content_hash=excluded.content_hash
100
- `),b=this.db.transaction(x=>{for(let R of x){let{meta:k,exports:D,imports:U,configs:P,events:E,content:T,classification:I,summary:M,embedding:N,contentHash:$}=R;r.run(k.path),o.run(k.path),a.run(k.path),c.run(k.path),l.run(k.path),p.run(k.path);let W=$??(T&&n?n(T):null);if(g.run(k.path,k.mtime,Date.now(),I||"Unknown",M||"",N?JSON.stringify(N):null,W),D){let L=(A,H,F)=>{for(let v of H){let C=v.embedding?JSON.stringify(v.embedding):null,B=u.run(A,v.name,v.kind,v.signature,v.doc||"",v.line,v.endLine||v.line,v.classification||"Other",v.capabilities||"[]",F,C),j=Number(B.lastInsertRowid);if(Number.isFinite(j)){let J=ar(v.signature);for(let z of J)z.targetName!==v.name&&_.run(A,j,v.name,z.targetName,z.relationship,v.line,z.metadata||null)}v.members&&v.members.length>0&&L(A,v.members,B.lastInsertRowid)}};L(k.path,D,null)}if(U)for(let L of U){let A=L.resolved_path!==void 0?L.resolved_path:i?.(L.module,k.path,t)??"";d.run(k.path,L.module,L.name,A)}if(P)for(let L of P)h.run(k.path,L.key,L.value,L.kind);if(T!==void 0&&m.run(k.path,T),E)for(let L of E)f.run(k.path,L.type,L.name,L.direction,L.line,L.snippet)}}),w=500;for(let x=0;x<e.length;x+=w)b(e.slice(x,x+w))}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}buildContentFtsQuery(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>=2).slice(0,12);if(t.length===0)return"";if(t.length===1)return`${t[0]}*`;let n=`"${t.join(" ")}"`,i=t.map(r=>`${r}*`).join(" OR ");return`${n} OR ${i}`}}});var In,pr=Z(()=>{"use strict";Ue();In=class s extends ae{static HTTP_METHOD_EXPORTS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]);findByNameAndFile(e,t){return this.all("SELECT * FROM exports WHERE file_path = ? AND name = ?",t,e)}findByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ?",e)}findAtLine(e,t){return this.get(`
100
+ `),y=this.db.transaction(k=>{for(let R of k){let{meta:w,exports:N,imports:U,configs:H,events:C,content:M,classification:D,summary:P,embedding:B,contentHash:L}=R;r.run(w.path),o.run(w.path),a.run(w.path),l.run(w.path),c.run(w.path),p.run(w.path);let A=L??(M&&n?n(M):null);if(g.run(w.path,w.mtime,Date.now(),D||"Unknown",P||"",B?JSON.stringify(B):null,A),N){let $=(W,J,O)=>{for(let S of J){let v=S.embedding?JSON.stringify(S.embedding):null,T=u.run(W,S.name,S.kind,S.signature,S.doc||"",S.line,S.endLine||S.line,S.classification||"Other",S.capabilities||"[]",O,v),I=Number(T.lastInsertRowid);if(Number.isFinite(I)){let z=Nr(S.signature);for(let j of z)j.targetName!==S.name&&b.run(W,I,S.name,j.targetName,j.relationship,S.line,j.metadata||null)}S.members&&S.members.length>0&&$(W,S.members,T.lastInsertRowid)}};$(w.path,N,null)}if(U)for(let $ of U){let W=$.resolved_path!==void 0?$.resolved_path:i?.($.module,w.path,t)??"";d.run(w.path,$.module,$.name,W)}if(H)for(let $ of H)h.run(w.path,$.key,$.value,$.kind);if(M!==void 0&&m.run(w.path,M),C)for(let $ of C)f.run(w.path,$.type,$.name,$.direction,$.line,$.snippet)}}),E=500;for(let k=0;k<e.length;k+=E)y(e.slice(k,k+E))}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}buildContentFtsQuery(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>=2).slice(0,12);if(t.length===0)return"";if(t.length===1)return`${t[0]}*`;let n=`"${t.join(" ")}"`,i=t.map(r=>`${r}*`).join(" OR ");return`${n} OR ${i}`}}});var jn,Or=ee(()=>{"use strict";qe();jn=class s extends pe{static HTTP_METHOD_EXPORTS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]);findByNameAndFile(e,t){return this.all("SELECT * FROM exports WHERE file_path = ? AND name = ?",t,e)}findByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ?",e)}findTopLevelByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ? AND parent_id IS NULL",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
@@ -194,7 +194,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
194
194
  SELECT * FROM exports
195
195
  WHERE lower(name) LIKE ?
196
196
  LIMIT ?
197
- `,`%${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:i=!1,includeFixtures:r=!1,excludePatterns:o=[],confidenceThreshold:a="all"}=e,c=[];n||(c.push("e.file_path NOT LIKE '%/test/%'"),c.push("e.file_path NOT LIKE '%/tests/%'"),c.push("e.file_path NOT LIKE '%/__tests__/%'"),c.push("e.file_path NOT LIKE '%.spec.%'"),c.push("e.file_path NOT LIKE '%.test.%'")),i||(c.push("e.file_path NOT LIKE '%/migrations/%'"),c.push("e.file_path NOT LIKE '%/migration/%'"),c.push("e.file_path NOT LIKE '%Migration.%'")),r||(c.push("e.file_path NOT LIKE '%/__fixtures__/%'"),c.push("e.file_path NOT LIKE '%/__mocks__/%'"),c.push("e.file_path NOT LIKE '%/fixtures/%'"),c.push("e.file_path NOT LIKE '%/mocks/%'"),c.push("e.file_path NOT LIKE '%.fixture.%'"),c.push("e.file_path NOT LIKE '%.mock.%'"));for(let m of o){let f=m.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");c.push(`e.file_path NOT LIKE '${f}'`)}let l=c.length>0?`AND ${c.join(" AND ")}`:"",d=this.all(`
197
+ `,`%${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:i=!1,includeFixtures:r=!1,excludePatterns:o=[],confidenceThreshold:a="all"}=e,l=[];n||(l.push("e.file_path NOT LIKE '%/test/%'"),l.push("e.file_path NOT LIKE '%/tests/%'"),l.push("e.file_path NOT LIKE '%/__tests__/%'"),l.push("e.file_path NOT LIKE '%.spec.%'"),l.push("e.file_path NOT LIKE '%.test.%'")),i||(l.push("e.file_path NOT LIKE '%/migrations/%'"),l.push("e.file_path NOT LIKE '%/migration/%'"),l.push("e.file_path NOT LIKE '%Migration.%'")),r||(l.push("e.file_path NOT LIKE '%/__fixtures__/%'"),l.push("e.file_path NOT LIKE '%/__mocks__/%'"),l.push("e.file_path NOT LIKE '%/fixtures/%'"),l.push("e.file_path NOT LIKE '%/mocks/%'"),l.push("e.file_path NOT LIKE '%.fixture.%'"),l.push("e.file_path NOT LIKE '%.mock.%'")),l.push("e.file_path NOT LIKE '%/dist/%'"),l.push("e.file_path NOT LIKE '%/build/%'"),l.push("e.file_path NOT LIKE '%/.next/%'"),l.push("e.file_path NOT LIKE '%/.nuxt/%'"),l.push("e.file_path NOT LIKE '%/.cache/%'"),l.push("e.file_path NOT LIKE '%/coverage/%'"),l.push("e.file_path NOT LIKE '%/node_modules/%'"),l.push("e.file_path NOT LIKE '%/storage/runtime/%'"),l.push("e.file_path NOT LIKE '%/compiled_templates/%'"),l.push("e.file_path NOT LIKE '%/compiled_classes/%'"),l.push("e.file_path NOT LIKE '%.generated.%'"),l.push("e.file_path NOT LIKE '%.gen.%'");for(let m of o){let f=m.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");l.push(`e.file_path NOT LIKE '${f}'`)}let c=l.length>0?`AND ${l.join(" AND ")}`:"",d=this.all(`
198
198
  SELECT e.name, e.kind, e.file_path, e.start_line
199
199
  FROM exports e
200
200
  WHERE e.kind IN (
@@ -203,7 +203,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
203
203
  'ArrowFunctionExpression', 'FunctionExpression'
204
204
  )
205
205
  AND e.parent_id IS NULL
206
- ${l}
206
+ ${c}
207
207
  AND NOT EXISTS (
208
208
  SELECT 1
209
209
  FROM imports i
@@ -215,7 +215,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
215
215
  AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
216
216
  ORDER BY e.file_path, e.start_line
217
217
  LIMIT ?
218
- `,t*2).filter(m=>!this.isFrameworkEntrypointExport(m)).map(m=>{let{confidence:f,reason:_}=this.scoreDeadExportConfidence(m);return{...m,confidence:f,reason:_}}),h=d;return a==="high"?h=d.filter(m=>m.confidence==="high"):a==="medium"&&(h=d.filter(m=>m.confidence==="high"||m.confidence==="medium")),h.slice(0,t)}scoreDeadExportConfidence(e){let t=e.file_path.toLowerCase(),n=e.name;return t.includes("/index.")||t.endsWith("index.ts")||t.endsWith("index.js")?{confidence:"low",reason:"Barrel/index file - likely re-export"}:e.kind==="TsInterfaceDeclaration"||e.kind==="TsTypeAliasDeclaration"?{confidence:"medium",reason:"Type definition - may be used externally"}:t.includes("/entry/")||t.includes("/bin/")||t.includes("main.")||t.includes("server.")||t.includes("cli.")?{confidence:"medium",reason:"Entry point - may be invoked externally"}:(t.includes("/components/")||t.endsWith(".tsx")||t.endsWith(".jsx"))&&/^[A-Z][A-Za-z0-9_]*$/.test(n)?{confidence:"medium",reason:"Component export - may be used by runtime composition"}:(t.includes("/contexts/")||t.includes("/context/"))&&(/Provider$/.test(n)||n.startsWith("use"))?{confidence:"medium",reason:"Context/provider export - may be wired dynamically"}:n.startsWith("create")||n.endsWith("Factory")||n.endsWith("Builder")?{confidence:"medium",reason:"Factory/builder pattern - may be used dynamically"}:n.startsWith("use")&&n.length>3?{confidence:"medium",reason:"Hook pattern - may be used in components"}:{confidence:"high",reason:"No detected usage"}}isFrameworkEntrypointExport(e){let n=e.file_path.toLowerCase().replace(/\\/g,"/"),i=e.name;return!!(/(^|\/)(src\/)?app\/.*\/route\.(t|j)sx?$/.test(n)&&s.HTTP_METHOD_EXPORTS.has(i)||/(^|\/)(src\/)?app\/.*\/(page|layout|loading|error|not-found|default|template)\.(t|j)sx?$/.test(n)||/(^|\/)(src\/)?middleware\.(t|j)sx?$/.test(n)||n.includes("/routes/")&&["loader","action","meta","headers"].includes(i))}getGravityMap(e=[],t){let n={},i=`
218
+ `,t*2).filter(m=>!this.isFrameworkEntrypointExport(m)).map(m=>{let{confidence:f,reason:b}=this.scoreDeadExportConfidence(m);return{...m,confidence:f,reason:b}}),h=d;return a==="high"?h=d.filter(m=>m.confidence==="high"):a==="medium"&&(h=d.filter(m=>m.confidence==="high"||m.confidence==="medium")),h.slice(0,t)}scoreDeadExportConfidence(e){let t=e.file_path.toLowerCase(),n=e.name;return t.includes("/index.")||t.endsWith("index.ts")||t.endsWith("index.js")?{confidence:"low",reason:"Barrel/index file - likely re-export"}:e.kind==="TsInterfaceDeclaration"||e.kind==="TsTypeAliasDeclaration"?{confidence:"medium",reason:"Type definition - may be used externally"}:t.includes("/entry/")||t.includes("/bin/")||t.includes("main.")||t.includes("server.")||t.includes("cli.")?{confidence:"medium",reason:"Entry point - may be invoked externally"}:(t.includes("/components/")||t.endsWith(".tsx")||t.endsWith(".jsx"))&&/^[A-Z][A-Za-z0-9_]*$/.test(n)?{confidence:"medium",reason:"Component export - may be used by runtime composition"}:(t.includes("/contexts/")||t.includes("/context/"))&&(/Provider$/.test(n)||n.startsWith("use"))?{confidence:"medium",reason:"Context/provider export - may be wired dynamically"}:n.startsWith("create")||n.endsWith("Factory")||n.endsWith("Builder")?{confidence:"medium",reason:"Factory/builder pattern - may be used dynamically"}:n.startsWith("use")&&n.length>3?{confidence:"medium",reason:"Hook pattern - may be used in components"}:{confidence:"high",reason:"No detected usage"}}isFrameworkEntrypointExport(e){let n=e.file_path.toLowerCase().replace(/\\/g,"/"),i=e.name;return!!(/(^|\/)(src\/)?app\/.*\/route\.(t|j)sx?$/.test(n)&&s.HTTP_METHOD_EXPORTS.has(i)||/(^|\/)(src\/)?app\/.*\/(page|layout|loading|error|not-found|default|template)\.(t|j)sx?$/.test(n)||/(^|\/)(src\/)?middleware\.(t|j)sx?$/.test(n)||n.includes("/app/exceptions/handler.php")||n.includes("/app/http/middleware/")||n.includes("/app/providers/")||n.includes("/app/console/commands/")||n.includes("/database/seeds/")||n.includes("/config/")&&n.endsWith(".php")||n.includes("/routes/")&&["loader","action","meta","headers"].includes(i))}getGravityMap(e=[],t){let n={},i=`
219
219
  SELECT ws.symbol_id, m.name as mission_name, m.status
220
220
  FROM working_set ws
221
221
  JOIN missions m ON ws.mission_id = m.id
@@ -224,14 +224,14 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
224
224
  OR m.id IN (${e.length>0?e.join(","):"-1"})
225
225
  )
226
226
  AND ws.symbol_id IS NOT NULL
227
- `,r=[];t&&r.push(t);let o=this.all(i,...r);for(let l of o){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let p=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.symbol_id].score+=p;let u=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.symbol_id].reasons.push(`${u}: ${l.mission_name}`)}let a=Math.floor(Date.now()/1e3)-86400,c=this.all(`
227
+ `,r=[];t&&r.push(t);let o=this.all(i,...r);for(let c of o){n[c.symbol_id]||(n[c.symbol_id]={score:1,reasons:[]});let p=c.status==="in-progress"||c.status==="verifying"?1:.5;n[c.symbol_id].score+=p;let u=c.status==="in-progress"||c.status==="verifying"?"Working Set":"Lineage Bleed";n[c.symbol_id].reasons.push(`${u}: ${c.mission_name}`)}let a=Math.floor(Date.now()/1e3)-86400,l=this.all(`
228
228
  SELECT symbol_id, type, mission_id
229
229
  FROM intent_logs
230
230
  WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
231
231
  AND symbol_id IS NOT NULL
232
232
  ORDER BY created_at DESC
233
233
  LIMIT 200
234
- `,a);for(let l of c){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let p=l.mission_id?e.includes(l.mission_id):!1,u=p?.1:.2;n[l.symbol_id].score<5&&(n[l.symbol_id].score+=u);let d=p?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.symbol_id].reasons.includes(d)&&n[l.symbol_id].reasons.length<5&&n[l.symbol_id].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
234
+ `,a);for(let c of l){n[c.symbol_id]||(n[c.symbol_id]={score:1,reasons:[]});let p=c.mission_id?e.includes(c.mission_id):!1,u=p?.1:.2;n[c.symbol_id].score<5&&(n[c.symbol_id].score+=u);let d=p?`Lineage Intent: ${c.type}`:`Recent Intent: ${c.type}`;!n[c.symbol_id].reasons.includes(d)&&n[c.symbol_id].reasons.length<5&&n[c.symbol_id].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
235
235
  SELECT kind, COUNT(*) as c
236
236
  FROM exports
237
237
  WHERE kind IS NOT NULL AND kind != ''
@@ -244,7 +244,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
244
244
  OR name LIKE ?
245
245
  OR name LIKE ?
246
246
  LIMIT 10
247
- `,e,`%.${e}`,`%::${e}`)}findTypeGraphEdges(e,t={}){let{filePath:n,direction:i="both",relationship:r,limit:o=50}=t,a=Math.max(1,Math.min(o,500)),c=[];if(i==="both"||i==="outbound"){let l=`
247
+ `,e,`%.${e}`,`%::${e}`)}findTypeGraphEdges(e,t={}){let{filePath:n,direction:i="both",relationship:r,limit:o=50}=t,a=Math.max(1,Math.min(o,500)),l=[];if(i==="both"||i==="outbound"){let c=`
248
248
  SELECT
249
249
  id,
250
250
  file_path,
@@ -257,7 +257,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
257
257
  'outbound' AS direction
258
258
  FROM type_graph_edges
259
259
  WHERE source_symbol_name = ?
260
- `,p=[e];n&&(l+=" AND file_path = ?",p.push(n)),r&&(l+=" AND relationship = ?",p.push(r)),l+=" ORDER BY file_path ASC, line_number ASC, target_symbol_name ASC LIMIT ?",p.push(a),c.push(...this.all(l,...p))}if(i==="both"||i==="inbound"){let l=`
260
+ `,p=[e];n&&(c+=" AND file_path = ?",p.push(n)),r&&(c+=" AND relationship = ?",p.push(r)),c+=" ORDER BY file_path ASC, line_number ASC, target_symbol_name ASC LIMIT ?",p.push(a),l.push(...this.all(c,...p))}if(i==="both"||i==="inbound"){let c=`
261
261
  SELECT
262
262
  id,
263
263
  file_path,
@@ -270,7 +270,7 @@ var Oc=Object.create;var Gi=Object.defineProperty;var Fc=Object.getOwnPropertyDe
270
270
  'inbound' AS direction
271
271
  FROM type_graph_edges
272
272
  WHERE target_symbol_name = ?
273
- `,p=[e];r&&(l+=" AND relationship = ?",p.push(r)),l+=" ORDER BY file_path ASC, line_number ASC, source_symbol_name ASC LIMIT ?",p.push(a),c.push(...this.all(l,...p))}return c.slice(0,a)}findTypeGraphEdgesBySymbolId(e,t={}){let n=this.findById(e);return n?this.findTypeGraphEdges(n.name,{...t,filePath:n.file_path}):[]}}});var ur,dr=Z(()=>{"use strict";ur=`
273
+ `,p=[e];r&&(c+=" AND relationship = ?",p.push(r)),c+=" ORDER BY file_path ASC, line_number ASC, source_symbol_name ASC LIMIT ?",p.push(a),l.push(...this.all(c,...p))}return l.slice(0,a)}findTypeGraphEdgesBySymbolId(e,t={}){let n=this.findById(e);return n?this.findTypeGraphEdges(n.name,{...t,filePath:n.file_path}):[]}}});var Fr,Wr=ee(()=>{"use strict";Fr=`
274
274
  WITH RECURSIVE dependency_chain AS (
275
275
  -- Base case: Direct dependents of the target symbol
276
276
  -- Meaning: Files that import the file where the symbol is defined
@@ -321,7 +321,7 @@ SELECT DISTINCT
321
321
  dc.imported_symbols
322
322
  FROM dependency_chain dc
323
323
  ORDER BY dc.depth, dc.consumer_path;
324
- `});var Ln,mr=Z(()=>{"use strict";Ue();dr();Ln=class extends ae{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(`
324
+ `});var Gn,Hr=ee(()=>{"use strict";qe();Wr();Gn=class extends pe{findByFile(e){return this.all("SELECT * FROM imports WHERE file_path = ?",e)}findByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM imports WHERE file_path IN (${t}) ORDER BY file_path`,...e)}getAllResolved(){return this.all(`
325
325
  SELECT * FROM imports
326
326
  WHERE resolved_path IS NOT NULL AND resolved_path != ''
327
327
  `)}findDependents(e){return this.all("SELECT * FROM imports WHERE resolved_path = ?",e)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM imports WHERE file_path = ?",e)?.count||0}countDependents(e){return this.get("SELECT COUNT(*) as count FROM imports WHERE resolved_path = ?",e)?.count||0}getImportsForFile(e){return this.all("SELECT module_specifier, imported_symbols, resolved_path FROM imports WHERE file_path = ?",e)}findImportSource(e,t){return this.get(`
@@ -347,7 +347,7 @@ ORDER BY dc.depth, dc.consumer_path;
347
347
  SELECT COUNT(*) as count FROM imports
348
348
  WHERE resolved_path IN (${n})
349
349
  AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
350
- `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(ur,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});import{fileURLToPath as gl}from"node:url";import{dirname as Qi,join as fr,resolve as yl}from"node:path";import{existsSync as bl}from"node:fs";function El(){let s=hr;for(;s!==Qi(s);){if(bl(fr(s,"package.json")))return s;s=Qi(s)}return yl(hr,"..","..")}function _e(...s){return fr(El(),...s)}var _l,hr,St=Z(()=>{"use strict";_l=gl(import.meta.url),hr=Qi(_l)});import{Worker as Sl}from"node:worker_threads";import{cpus as wl}from"node:os";import{fileURLToPath as xl}from"node:url";import{dirname as vl,join as gr}from"node:path";import{existsSync as yr}from"node:fs";function Tl(){if(_r.endsWith(".ts")){let e=gr(br,"worker.ts");if(yr(e))return e}let s=gr(br,"worker.js");return yr(s)?s:_e("dist/logic/domain/embeddings/worker.js")}function Ot(s){return Dt||(Dt=new sn(s)),Dt}async function $n(){Dt&&(await Dt.shutdown(),Dt=null)}var _r,br,sn,Dt,Er=Z(()=>{"use strict";q();St();_r=xl(import.meta.url),br=vl(_r);sn=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;cacheDir;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(2,wl().length-1)),this.cacheDir=e.cacheDir??"./.cache",this.initTimeout=e.initTimeout??6e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{S.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((n,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,S.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,S.info({numWorkers:this.workers.length},"Embedding worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=Tl();S.debug({workerPath:e},"Resolved worker path");let t=[];for(let n=0;n<this.numWorkers;n++)n>0&&await new Promise(i=>setTimeout(i,25)),t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new Sl(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),a={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){S.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(a),S.debug({workerIndex:t},"Worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(a,c.id,c.embeddings||[]):c.type==="error"&&c.id&&this.handleTaskError(a,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),S.error({err:c,workerIndex:t},"Worker error"),a.currentTaskId&&this.handleTaskError(a,a.currentTaskId,c),!this.initialized){i(c);return}let l=this.workers.indexOf(a);l!==-1&&this.workers.splice(l,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{S.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&S.warn({workerIndex:t,code:c},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=128,n){if(this.initialized||await this.initialize(),e.length===0)return[];let i=[];for(let l=0;l<e.length;l+=t)i.push(e.slice(l,l+t));let r=new Array(i.length),o=0,a=i.map((l,p)=>new Promise((u,d)=>{let m={id:`task_${++this.taskIdCounter}`,texts:l,resolve:f=>{if(r[p]=f,o++,n){let _=Math.min(o*t,e.length);n(_,e.length)}u()},reject:f=>{if(r[p]=new Array(l.length).fill(null),o++,S.warn({err:f,chunkIndex:p},"Chunk embedding failed"),n){let _=Math.min(o*t,e.length);n(_,e.length)}u()}};this.taskQueue.push(m),this.processQueue()}));await Promise.all(a);let c=[];for(let l of r)c.push(...l);return S.info({total:e.length,successful:c.filter(l=>l!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),c}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}S.info({numWorkers:this.workers.length},"Shutting down embedding worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,S.info("Embedding worker pool shutdown complete")}},Dt=null});var ot={};qi(ot,{EmbeddingPriorityQueue:()=>Zi,EmbeddingWorkerPool:()=>sn,cosineSimilarity:()=>Mn,generateEmbedding:()=>ts,generateEmbeddingsBatch:()=>ns,getDefaultPool:()=>Ot,setUseWorkerThreads:()=>Pn,shutdownDefaultPool:()=>$n});async function Rl(){return rn||(rn=await import("@xenova/transformers"),rn.env.cacheDir="./.cache",rn.env.allowLocalModels=!0),rn}function Pn(s){es=s,S.info({useWorkerThreads:s},"Worker thread mode updated")}function Sr(s=!1){let e=(on||"").toLowerCase(),t={};return on&&(t.dtype=on),s?(t.quantized=!1,t):(e==="fp32"||e==="fp16"||e==="float32"||e==="float16"?t.quantized=!1:e.startsWith("q")&&(t.quantized=!0),t)}async function kl(){S.info({model:An,dtype:on},"Loading embedding model...");let{pipeline:s}=await Rl(),e=Sr(!1);try{return await s("feature-extraction",An,e)}catch(t){let n=t?.message||"";if(!(n.includes("/onnx/model_quantized.onnx")||n.includes("model_quantized.onnx")))throw t;return S.warn({model:An,dtype:on},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",An,Sr(!0))}}async function xr(){return Xi||(Xi=kl()),Xi}async function ts(s){try{let t=await(await xr())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return S.error({err:e},"Failed to generate embedding"),null}}async function ns(s,e=wr,t){return s.length===0?[]:es?Ot().generateEmbeddings(s,e,t):vr(s,e,t)}async function vr(s,e,t){let n=new Array(s.length).fill(null),i=await xr();for(let r=0;r<s.length;r+=e){let o=Math.min(r+e,s.length),a=s.slice(r,o);try{let c=await i(a,{pooling:"mean",normalize:!0}),[l,p]=c.dims;for(let u=0;u<l;u++){let d=u*p,h=d+p;n[r+u]=Array.from(c.data.slice(d,h))}}catch(c){S.error({err:c,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let l=0;l<a.length;l++)try{let p=a[l];if(!p||p.trim().length===0)continue;let u=await i(p,{pooling:"mean",normalize:!0});n[r+l]=Array.from(u.data)}catch{n[r+l]=null}}t&&t(o,s.length)}return S.debug({total:s.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function Mn(s,e){let t=0,n=0,i=0;for(let r=0;r<s.length;r++)t+=s[r]*e[r],n+=s[r]*s[r],i+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(i))}var An,on,rn,wr,es,Xi,Zi,Ae=Z(()=>{"use strict";q();Er();An=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",on=process.env.EMBEDDING_DTYPE??"fp32",rn=null;wr=128,es=!1;Xi=null;Zi=class{queue=[];processing=!1;results=new Map;enqueue(e){this.queue.push(e),this.queue.sort((t,n)=>n.priority-t.priority)}enqueueMany(e){this.queue.push(...e),this.queue.sort((t,n)=>n.priority-t.priority)}get size(){return this.queue.length}get isProcessing(){return this.processing}getResult(e){return this.results.get(e)}async processQueue(e=wr,t){if(this.processing)return S.warn("Queue processing already in progress"),this.results;this.processing=!0;let n=this.queue.length;try{es?await this.processQueueParallel(e,n,t):await this.processQueueSequential(e,n,t)}finally{this.processing=!1}return this.results}async processQueueSequential(e,t,n){for(;this.queue.length>0;){let i=this.queue.splice(0,e),r=i.map(a=>a.text),o=await vr(r,r.length);if(i.forEach((a,c)=>{this.results.set(a.id,o[c])}),n){let a=t-this.queue.length;n(a,t)}}}async processQueueParallel(e,t,n){let i=this.queue.splice(0),r=i.map(c=>c.text),a=await Ot().generateEmbeddings(r,e,(c,l)=>{n&&n(c,l)});i.forEach((c,l)=>{this.results.set(c.id,a[l])})}clear(){this.queue=[],this.results.clear()}}});var Nn,Tr=Z(()=>{"use strict";Ue();Nn=class extends ae{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
350
+ `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(Fr,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});import{fileURLToPath as ql}from"node:url";import{dirname as gs,join as Br,resolve as Vl}from"node:path";import{existsSync as Jl}from"node:fs";function Kl(){let s=zr;for(;s!==gs(s);){if(Jl(Br(s,"package.json")))return s;s=gs(s)}return Vl(zr,"..","..")}function Le(...s){return Br(Kl(),...s)}var Yl,zr,Dt=ee(()=>{"use strict";Yl=ql(import.meta.url),zr=gs(Yl)});import{Worker as Ql}from"node:worker_threads";import{cpus as Zl}from"node:os";import{fileURLToPath as Xl}from"node:url";import{dirname as ep,join as Ur}from"node:path";import{existsSync as jr}from"node:fs";function tp(){if(qr.endsWith(".ts")){let e=Ur(Gr,"worker.ts");if(jr(e))return e}let s=Ur(Gr,"worker.js");return jr(s)?s:Le("dist/logic/domain/embeddings/worker.js")}function Zt(s){return Qt||(Qt=new bn(s)),Qt}async function qn(){Qt&&(await Qt.shutdown(),Qt=null)}var qr,Gr,bn,Qt,Vr=ee(()=>{"use strict";G();Dt();qr=Xl(import.meta.url),Gr=ep(qr);bn=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;cacheDir;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(2,Zl().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{x.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,x.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,x.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=tp();x.debug({workerPath:e},"Resolved worker path");let t=[];for(let n=0;n<this.numWorkers;n++)n>0&&await new Promise(i=>setTimeout(i,25)),t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new Ql(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),a={worker:o,busy:!1,currentTaskId:null};o.on("message",l=>{if(l.type==="ready"){if(clearTimeout(r),this.shutdownRequested){x.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(a),x.debug({workerIndex:t},"Worker ready"),n()}else l.type==="result"&&l.id?this.handleTaskComplete(a,l.id,l.embeddings||[]):l.type==="error"&&l.id&&this.handleTaskError(a,l.id,new Error(l.error||"Unknown error"))}),o.on("error",l=>{if(clearTimeout(r),x.error({err:l,workerIndex:t},"Worker error"),a.currentTaskId&&this.handleTaskError(a,a.currentTaskId,l),!this.initialized){i(l);return}let c=this.workers.indexOf(a);c!==-1&&this.workers.splice(c,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{x.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",l=>{l!==0&&!this.shutdownRequested&&x.warn({workerIndex:t,code:l},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=128,n){if(this.initialized||await this.initialize(),e.length===0)return[];let i=[];for(let c=0;c<e.length;c+=t)i.push(e.slice(c,c+t));let r=new Array(i.length),o=0,a=i.map((c,p)=>new Promise((u,d)=>{let m={id:`task_${++this.taskIdCounter}`,texts:c,resolve:f=>{if(r[p]=f,o++,n){let b=Math.min(o*t,e.length);n(b,e.length)}u()},reject:f=>{if(r[p]=new Array(c.length).fill(null),o++,x.warn({err:f,chunkIndex:p},"Chunk embedding failed"),n){let b=Math.min(o*t,e.length);n(b,e.length)}u()}};this.taskQueue.push(m),this.processQueue()}));await Promise.all(a);let l=[];for(let c of r)l.push(...c);return x.info({total:e.length,successful:l.filter(c=>c!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),l}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}x.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,x.info("Embedding worker pool shutdown complete")}},Qt=null});var Et={};us(Et,{EmbeddingPriorityQueue:()=>bs,EmbeddingWorkerPool:()=>bn,cosineSimilarity:()=>Yn,generateEmbedding:()=>Es,generateEmbeddingsBatch:()=>Ss,getDefaultPool:()=>Zt,setUseWorkerThreads:()=>Jn,shutdownDefaultPool:()=>qn});async function np(){return _n||(_n=await import("@xenova/transformers"),_n.env.cacheDir="./.cache",_n.env.allowLocalModels=!0),_n}function Jn(s){_s=s,x.info({useWorkerThreads:s},"Worker thread mode updated")}function Jr(s=!1){let e=(En||"").toLowerCase(),t={};return En&&(t.dtype=En),s?(t.quantized=!1,t):(e==="fp32"||e==="fp16"||e==="float32"||e==="float16"?t.quantized=!1:e.startsWith("q")&&(t.quantized=!0),t)}async function ip(){x.info({model:Vn,dtype:En},"Loading embedding model...");let{pipeline:s}=await np(),e=Jr(!1);try{return await s("feature-extraction",Vn,e)}catch(t){let n=t?.message||"";if(!(n.includes("/onnx/model_quantized.onnx")||n.includes("model_quantized.onnx")))throw t;return x.warn({model:Vn,dtype:En},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",Vn,Jr(!0))}}async function Kr(){return ys||(ys=ip()),ys}async function Es(s){try{let t=await(await Kr())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return x.error({err:e},"Failed to generate embedding"),null}}async function Ss(s,e=Yr,t){return s.length===0?[]:_s?Zt().generateEmbeddings(s,e,t):Qr(s,e,t)}async function Qr(s,e,t){let n=new Array(s.length).fill(null),i=await Kr();for(let r=0;r<s.length;r+=e){let o=Math.min(r+e,s.length),a=s.slice(r,o);try{let l=await i(a,{pooling:"mean",normalize:!0}),[c,p]=l.dims;for(let u=0;u<c;u++){let d=u*p,h=d+p;n[r+u]=Array.from(l.data.slice(d,h))}}catch(l){x.error({err:l,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let c=0;c<a.length;c++)try{let p=a[c];if(!p||p.trim().length===0)continue;let u=await i(p,{pooling:"mean",normalize:!0});n[r+c]=Array.from(u.data)}catch{n[r+c]=null}}t&&t(o,s.length)}return x.debug({total:s.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function Yn(s,e){let t=0,n=0,i=0;for(let r=0;r<s.length;r++)t+=s[r]*e[r],n+=s[r]*s[r],i+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(i))}var Vn,En,_n,Yr,_s,ys,bs,Ve=ee(()=>{"use strict";G();Vr();Vn=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",En=process.env.EMBEDDING_DTYPE??"fp32",_n=null;Yr=128,_s=!1;ys=null;bs=class{queue=[];processing=!1;results=new Map;enqueue(e){this.queue.push(e),this.queue.sort((t,n)=>n.priority-t.priority)}enqueueMany(e){this.queue.push(...e),this.queue.sort((t,n)=>n.priority-t.priority)}get size(){return this.queue.length}get isProcessing(){return this.processing}getResult(e){return this.results.get(e)}async processQueue(e=Yr,t){if(this.processing)return x.warn("Queue processing already in progress"),this.results;this.processing=!0;let n=this.queue.length;try{_s?await this.processQueueParallel(e,n,t):await this.processQueueSequential(e,n,t)}finally{this.processing=!1}return this.results}async processQueueSequential(e,t,n){for(;this.queue.length>0;){let i=this.queue.splice(0,e),r=i.map(a=>a.text),o=await Qr(r,r.length);if(i.forEach((a,l)=>{this.results.set(a.id,o[l])}),n){let a=t-this.queue.length;n(a,t)}}}async processQueueParallel(e,t,n){let i=this.queue.splice(0),r=i.map(l=>l.text),a=await Zt().generateEmbeddings(r,e,(l,c)=>{n&&n(l,c)});i.forEach((l,c)=>{this.results.set(l.id,a[c])})}clear(){this.queue=[],this.results.clear()}}});var Kn,Zr=ee(()=>{"use strict";qe();Kn=class extends pe{findById(e){return this.get("SELECT * FROM missions WHERE id = ?",e)}findByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM missions WHERE id IN (${t})`,...e)}findActive(e){let t="SELECT * FROM missions WHERE status IN ('in-progress', 'planned', 'verifying')",n=[];return e&&(t+=" AND git_branch = ?",n.push(e)),t+=` ORDER BY
351
351
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
352
352
  created_at ASC`,this.all(t,...n)}findAll(e){let t="SELECT * FROM missions",n=[];return e&&(t+=" WHERE status = ?",n.push(e)),t+=` ORDER BY
353
353
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
@@ -413,7 +413,7 @@ ORDER BY dc.depth, dc.consumer_path;
413
413
  SELECT AVG(updated_at - created_at) AS avg_duration
414
414
  FROM missions
415
415
  WHERE status = 'completed' AND updated_at > created_at
416
- `),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,a=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),l=a?.n??0,p=c?.n??0,u=`${l} completed in last 7 days, ${p} in last 30 days.`;if(i!=null){let d=Math.round(i/60);u+=` Avg mission duration: ${d} min.`}return{completionRate:t,averageDurationSeconds:i,completedLast7Days:l,completedLast30Days:p,velocityNote:u}}suspendByBranch(e){return this.run(`UPDATE missions
416
+ `),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,a=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),l=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),c=a?.n??0,p=l?.n??0,u=`${c} completed in last 7 days, ${p} in last 30 days.`;if(i!=null){let d=Math.round(i/60);u+=` Avg mission duration: ${d} min.`}return{completionRate:t,averageDurationSeconds:i,completedLast7Days:c,completedLast30Days:p,velocityNote:u}}suspendByBranch(e){return this.run(`UPDATE missions
417
417
  SET status = 'suspended', updated_at = unixepoch()
418
418
  WHERE git_branch = ? AND status IN ('in-progress', 'verifying')`,e)}resumeByBranch(e){return this.run(`UPDATE missions
419
419
  SET status = 'in-progress', updated_at = unixepoch()
@@ -438,7 +438,7 @@ ORDER BY dc.depth, dc.consumer_path;
438
438
  SELECT linked_repo_path, linked_mission_id, relationship, direction
439
439
  FROM cross_repo_links
440
440
  WHERE mission_id = ?
441
- `,e)}catch{return[]}}findLastMission(){return this.get("SELECT * FROM missions ORDER BY updated_at DESC, id DESC LIMIT 1")}findActiveByPriority(){return this.get("SELECT * FROM missions WHERE status IN ('in-progress', 'active', 'verifying') ORDER BY CASE WHEN status = 'in-progress' THEN 0 ELSE 1 END, created_at ASC LIMIT 1")}addHandoff(e,t){let n=JSON.stringify(t),i=e??0,r=this.insert("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",i,"handoff",t.kind,n),o=[`[handoff:${t.kind}]`,...t.findings.map(a=>a.statement),...t.risks.map(a=>a.description),...t.gaps].filter(Boolean).join(" ");return Promise.resolve().then(()=>(Ae(),ot)).then(({generateEmbedding:a})=>a(o)).then(a=>{a&&this.run("UPDATE mission_artifacts SET embedding = ? WHERE id = ?",JSON.stringify(a),r)}).catch(()=>{}),r}getHandoffs(e,t,n=20){let i=["type = 'handoff'"],r=[];e!==void 0&&(i.push("mission_id = ?"),r.push(e??0)),t&&(i.push("identifier = ?"),r.push(t));let o=`SELECT * FROM mission_artifacts WHERE ${i.join(" AND ")} ORDER BY created_at DESC LIMIT ?`;return r.push(n),this.all(o,...r)}async findSemanticHandoffs(e,t=5){let{cosineSimilarity:n}=await Promise.resolve().then(()=>(Ae(),ot)),i=this.all("SELECT * FROM mission_artifacts WHERE type = 'handoff' AND embedding IS NOT NULL"),r=[];for(let o of i)try{let a=JSON.parse(o.embedding),c=n(e,a);c>.3&&r.push({...o,similarity:c})}catch{}return r.sort((o,a)=>a.similarity-o.similarity).slice(0,t)}}});var Dn,Rr=Z(()=>{"use strict";Ue();q();Dn=class s extends ae{findByMission(e,t=50){return this.all(`
441
+ `,e)}catch{return[]}}findLastMission(){return this.get("SELECT * FROM missions ORDER BY updated_at DESC, id DESC LIMIT 1")}findActiveByPriority(){return this.get("SELECT * FROM missions WHERE status IN ('in-progress', 'active', 'verifying') ORDER BY CASE WHEN status = 'in-progress' THEN 0 ELSE 1 END, created_at ASC LIMIT 1")}addHandoff(e,t){let n=JSON.stringify(t),i=this.insert("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,"handoff",t.kind,n),r=[`[handoff:${t.kind}]`,...t.findings.map(o=>o.statement),...t.risks.map(o=>o.description),...t.gaps].filter(Boolean).join(" ");return Promise.resolve().then(()=>(Ve(),Et)).then(({generateEmbedding:o})=>o(r)).then(o=>{o&&this.run("UPDATE mission_artifacts SET embedding = ? WHERE id = ?",JSON.stringify(o),i)}).catch(()=>{}),i}getHandoffs(e,t,n=20){let i=["type = 'handoff'"],r=[];e!==void 0&&(e===null?i.push("mission_id IS NULL"):(i.push("mission_id = ?"),r.push(e))),t&&(i.push("identifier = ?"),r.push(t));let o=`SELECT * FROM mission_artifacts WHERE ${i.join(" AND ")} ORDER BY created_at DESC LIMIT ?`;return r.push(n),this.all(o,...r)}async findSemanticHandoffs(e,t){let{cosineSimilarity:n}=await Promise.resolve().then(()=>(Ve(),Et)),i=["type = 'handoff'","embedding IS NOT NULL"],r=[];t?.missionId!==void 0&&(t.missionId===null?i.push("mission_id IS NULL"):(i.push("mission_id = ?"),r.push(t.missionId))),t?.kind&&(i.push("identifier = ?"),r.push(t.kind));let o=this.all(`SELECT * FROM mission_artifacts WHERE ${i.join(" AND ")}`,...r),a=[];for(let l of o)try{let c=JSON.parse(l.embedding),p=n(e,c);p>.3&&a.push({...l,similarity:p})}catch{}return a.sort((l,c)=>c.similarity-l.similarity).slice(0,t?.limit??5)}}});var Qn,Xr=ee(()=>{"use strict";qe();G();Qn=class s extends pe{findByMission(e,t=50){return this.all(`
442
442
  SELECT
443
443
  id, mission_id, symbol_id, file_path, type, content, confidence,
444
444
  symbol_name, signature, commit_sha, is_crystallized, crystal_id,
@@ -459,7 +459,7 @@ ORDER BY dc.depth, dc.consumer_path;
459
459
  `,e)}create(e){let t=this.insert(`
460
460
  INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
461
461
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
462
- `,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha);return s.EMBEDDABLE_TYPES.has(e.type)&&this.generateAndStoreEmbedding(Number(t),e).catch(n=>{S.debug({err:n,intentLogId:t},"Failed to generate intent log embedding")}),t}static EMBEDDABLE_TYPES=new Set(["decision","discovery","fix","blocker","note","heritage","crystal"]);static buildEmbeddingText(e){let t=[`[${e.type}]`];return e.symbol_name&&t.push(`symbol: ${e.symbol_name}`),e.file_path&&t.push(`file: ${e.file_path.split("/").pop()}`),t.push(e.content),t.join(" ")}async generateAndStoreEmbedding(e,t){let{generateEmbedding:n}=await Promise.resolve().then(()=>(Ae(),ot)),i=s.buildEmbeddingText(t),r=await n(i);r&&this.run("UPDATE intent_logs SET embedding = ? WHERE id = ?",JSON.stringify(r),e)}findWithEmbeddings(){return this.all("SELECT * FROM intent_logs WHERE embedding IS NOT NULL AND type NOT IN ('system', 'lapsed')")}async findSemanticMatches(e,t,n){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(Ae(),ot)),r=this.findWithEmbeddings();if(r.length>5e3)return S.warn({count:r.length},"Intent log count exceeds brute-force vector scan limit (5000). Skipping semantic recall."),[];let o=[];for(let a of r)if(!(n&&a.symbol_id===n))try{let c=JSON.parse(a.embedding),l=i(e,c);l>.25&&o.push({id:a.id,mission_id:a.mission_id,type:a.type,content:a.content,symbol_name:a.symbol_name,file_path:a.file_path,similarity:l,created_at:a.created_at})}catch{}return o.sort((a,c)=>c.similarity-a.similarity).slice(0,t)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${i} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
462
+ `,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha);return s.EMBEDDABLE_TYPES.has(e.type)&&this.generateAndStoreEmbedding(Number(t),e).catch(n=>{x.debug({err:n,intentLogId:t},"Failed to generate intent log embedding")}),t}static EMBEDDABLE_TYPES=new Set(["decision","discovery","fix","blocker","note","heritage","crystal"]);static buildEmbeddingText(e){let t=[`[${e.type}]`];return e.symbol_name&&t.push(`symbol: ${e.symbol_name}`),e.file_path&&t.push(`file: ${e.file_path.split("/").pop()}`),t.push(e.content),t.join(" ")}async generateAndStoreEmbedding(e,t){let{generateEmbedding:n}=await Promise.resolve().then(()=>(Ve(),Et)),i=s.buildEmbeddingText(t),r=await n(i);r&&this.run("UPDATE intent_logs SET embedding = ? WHERE id = ?",JSON.stringify(r),e)}findWithEmbeddings(){return this.all("SELECT * FROM intent_logs WHERE embedding IS NOT NULL AND type NOT IN ('system', 'lapsed')")}async findSemanticMatches(e,t,n){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(Ve(),Et)),r=this.findWithEmbeddings();if(r.length>5e3)return x.warn({count:r.length},"Intent log count exceeds brute-force vector scan limit (5000). Skipping semantic recall."),[];let o=[];for(let a of r)if(!(n&&a.symbol_id===n))try{let l=JSON.parse(a.embedding),c=i(e,l);c>.25&&o.push({id:a.id,mission_id:a.mission_id,type:a.type,content:a.content,symbol_name:a.symbol_name,file_path:a.file_path,similarity:c,created_at:a.created_at})}catch{}return o.sort((a,l)=>l.similarity-a.similarity).slice(0,t)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${i} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
463
463
  SELECT id, file_path, symbol_name, signature
464
464
  FROM intent_logs
465
465
  WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
@@ -491,24 +491,48 @@ ORDER BY dc.depth, dc.consumer_path;
491
491
  FROM intent_logs
492
492
  WHERE mission_id = ? AND is_crystallized = 0
493
493
  AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
494
+ ORDER BY created_at ASC`,e)}findCrystallizableByMission(e){return this.all(`SELECT
495
+ id, mission_id, symbol_id, file_path, type, content, confidence,
496
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
497
+ created_at
498
+ FROM intent_logs
499
+ WHERE mission_id = ?
500
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
494
501
  ORDER BY created_at ASC`,e)}findCrystalByMission(e){return this.get(`SELECT
495
502
  id, mission_id, symbol_id, file_path, type, content, confidence,
496
503
  symbol_name, signature, commit_sha, is_crystallized, crystal_id,
497
504
  created_at
498
505
  FROM intent_logs
499
506
  WHERE mission_id = ? AND type = 'crystal'
500
- ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t){return this.transaction(()=>{let n=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
501
- VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
507
+ ORDER BY created_at DESC LIMIT 1`,e)}findCrystalBySymbol(e){return this.get(`SELECT
508
+ id, mission_id, symbol_id, file_path, type, content, confidence,
509
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
510
+ created_at
511
+ FROM intent_logs
512
+ WHERE symbol_id = ? AND mission_id IS NULL AND type = 'crystal'
513
+ ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t,n){return this.transaction(()=>{let i=n;return typeof i=="number"?this.run(`UPDATE intent_logs
514
+ SET content = ?, confidence = 1.0
515
+ WHERE id = ? AND mission_id = ? AND type = 'crystal'`,t,i,e):i=Number(this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
516
+ VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
502
517
  SET is_crystallized = 1, crystal_id = ?
503
518
  WHERE mission_id = ? AND is_crystallized = 0 AND id != ?
504
- AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),n})}findRawBySymbol(e){return this.all(`SELECT * FROM intent_logs
519
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,i,e,i),this.generateAndStoreEmbedding(i,{type:"crystal",content:t}).catch(r=>{x.debug({err:r,intentLogId:i},"Failed to refresh crystal embedding")}),i})}findRawBySymbol(e){return this.all(`SELECT * FROM intent_logs
505
520
  WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0
506
521
  AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
507
- ORDER BY created_at ASC`,e)}crystallizeBySymbol(e,t){return this.transaction(()=>{let n=this.insert(`INSERT INTO intent_logs (mission_id, symbol_id, type, content, confidence, is_crystallized, file_path, symbol_name, signature, commit_sha)
508
- VALUES (NULL, ?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
522
+ ORDER BY created_at ASC`,e)}findCrystallizableBySymbol(e){return this.all(`SELECT
523
+ id, mission_id, symbol_id, file_path, type, content, confidence,
524
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
525
+ created_at
526
+ FROM intent_logs
527
+ WHERE symbol_id = ? AND mission_id IS NULL
528
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
529
+ ORDER BY created_at ASC`,e)}crystallizeBySymbol(e,t,n){return this.transaction(()=>{let i=n;return typeof i=="number"?this.run(`UPDATE intent_logs
530
+ SET content = ?, confidence = 1.0
531
+ WHERE id = ? AND symbol_id = ? AND mission_id IS NULL AND type = 'crystal'`,t,i,e):i=Number(this.insert(`INSERT INTO intent_logs (mission_id, symbol_id, type, content, confidence, is_crystallized, file_path, symbol_name, signature, commit_sha)
532
+ VALUES (NULL, ?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
509
533
  SET is_crystallized = 1, crystal_id = ?
510
534
  WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0 AND id != ?
511
- AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),n})}countByMissions(e){if(e.length===0)return{};let t=e.map(()=>"?").join(","),n=this.all(`SELECT mission_id, COUNT(*) as cnt
535
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,i,e,i),this.generateAndStoreEmbedding(i,{type:"crystal",content:t}).catch(r=>{x.debug({err:r,intentLogId:i},"Failed to refresh crystal embedding")}),i})}countByMissions(e){if(e.length===0)return{};let t=e.map(()=>"?").join(","),n=this.all(`SELECT mission_id, COUNT(*) as cnt
512
536
  FROM intent_logs
513
537
  WHERE mission_id IN (${t})
514
538
  AND type NOT IN ('system', 'adr', 'lapsed')
@@ -522,32 +546,85 @@ ORDER BY dc.depth, dc.consumer_path;
522
546
  FROM intent_logs
523
547
  WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
524
548
  AND created_at > ?
525
- ORDER BY created_at DESC LIMIT ?`,e,n.created_at,t-1);return[n,...i]}return this.findByMission(e,t)}async findSemanticTheme(e,t,n=200){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(Ae(),ot)),r=this.findWithEmbeddings(),o=[];for(let a of r)if(s.EMBEDDABLE_TYPES.has(a.type)&&!(t&&a.mission_id!==null&&!t.includes(a.mission_id)))try{let c=JSON.parse(a.embedding),l=i(e,c);l>.35&&o.push({...a,_similarity:l})}catch{}return o.sort((a,c)=>c._similarity-a._similarity).slice(0,n).map(({_similarity:a,...c})=>c)}crystallizeTheme(e,t,n){return this.transaction(()=>{let i=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
526
- VALUES (NULL, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,n);if(t.length>0){let r=t.map(()=>"?").join(",");this.run(`UPDATE intent_logs SET is_crystallized = 1, crystal_id = ? WHERE id IN (${r})`,i,...t)}return i})}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:n}=await Promise.resolve().then(()=>(Ae(),ot)),i=[...s.EMBEDDABLE_TYPES].map(p=>`'${p}'`).join(","),r=this.all(`SELECT * FROM intent_logs WHERE embedding IS NULL AND type IN (${i})`);if(r.length===0)return 0;let o=r.map(p=>s.buildEmbeddingText(p)),a=await n(o,e,t),c=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),l=0;return this.transaction(()=>{for(let p=0;p<r.length;p++)a[p]&&(c.run(JSON.stringify(a[p]),r[p].id),l++)}),S.info({total:r.length,embedded:l},"Intent log embedding backfill complete"),l}}});var On,kr=Z(()=>{"use strict";Ue();On=class extends ae{findByKey(e,t=20){return this.all(`
549
+ ORDER BY created_at DESC LIMIT ?`,e,n.created_at,t-1);return[n,...i]}return this.findByMission(e,t)}async findSemanticTheme(e,t,n=200){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(Ve(),Et)),r=this.findWithEmbeddings(),o=[];for(let a of r)if(s.EMBEDDABLE_TYPES.has(a.type)&&a.type!=="crystal"&&a.mission_id!=null&&!(t&&!t.includes(a.mission_id)))try{let l=JSON.parse(a.embedding),c=i(e,l);c>.35&&o.push({...a,_similarity:c})}catch{}return o.sort((a,l)=>l._similarity-a._similarity).slice(0,n).map(({_similarity:a,...l})=>l)}crystallizeTheme(e,t,n){return this.transaction(()=>{let i=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
550
+ VALUES (NULL, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,n);if(t.length>0){let r=t.map(()=>"?").join(",");this.run(`UPDATE intent_logs SET is_crystallized = 1, crystal_id = ? WHERE id IN (${r})`,i,...t)}return i})}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:n}=await Promise.resolve().then(()=>(Ve(),Et)),i=[...s.EMBEDDABLE_TYPES].map(p=>`'${p}'`).join(","),r=this.all(`SELECT * FROM intent_logs WHERE embedding IS NULL AND type IN (${i})`);if(r.length===0)return 0;let o=r.map(p=>s.buildEmbeddingText(p)),a=await n(o,e,t),l=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),c=0;return this.transaction(()=>{for(let p=0;p<r.length;p++)a[p]&&(l.run(JSON.stringify(a[p]),r[p].id),c++)}),x.info({total:r.length,embedded:c},"Intent log embedding backfill complete"),c}}});var Zn,eo=ee(()=>{"use strict";qe();Zn=class extends pe{findByKey(e,t=20){return this.all(`
527
551
  SELECT file_path, key, value, kind
528
552
  FROM configs
529
553
  WHERE key LIKE ? OR value LIKE ?
530
554
  LIMIT ?
531
- `,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",i=[];return e&&(n+=" WHERE kind = ?",i.push(e)),n+=" LIMIT ?",i.push(t),this.all(n,...i)}findEnvValue(e){return this.get("SELECT value FROM configs WHERE key LIKE ? OR key = ? LIMIT 1",`%:env:${e}`,e)?.value}countByKind(e){return this.get("SELECT COUNT(*) as count FROM configs WHERE kind = ?",e)?.count||0}getAll(){return this.all("SELECT key, value, kind, file_path FROM configs")}}});var Fn,Cr=Z(()=>{"use strict";Ue();Fn=class extends ae{search(e,t=10){return this.all(`
555
+ `,`%${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 Xn,to=ee(()=>{"use strict";qe();Xn=class extends pe{search(e,t=10){return this.all(`
532
556
  SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
533
557
  FROM content_fts
534
558
  WHERE content_fts MATCH ?
535
559
  LIMIT ?
536
- `,e,t)}}});var Ir,Wn,Lr=Z(()=>{"use strict";Ue();Ir=500,Wn=class extends ae{record(e,t,n=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,n),this.pruneIfNeeded()}findRecent(e=20){return this.all("SELECT id, query, mode, branch, created_at FROM search_history ORDER BY created_at DESC LIMIT ?",e)}findRecentByQueryPrefix(e,t=10){return e.trim()?this.all(`SELECT id, query, mode, branch, created_at FROM search_history
537
- WHERE query LIKE ? ORDER BY created_at DESC LIMIT ?`,`${e}%`,t):this.findRecent(t)}pruneIfNeeded(){(this.get("SELECT COUNT(*) as count FROM search_history")?.count??0)<=Ir||this.run(`DELETE FROM search_history WHERE id NOT IN (
560
+ `,e,t)}}});var no,ei,io=ee(()=>{"use strict";qe();no=500,ei=class extends pe{record(e,t,n=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,n),this.pruneIfNeeded()}findRecent(e=20){return this.all("SELECT id, query, mode, branch, created_at FROM search_history ORDER BY created_at DESC LIMIT ?",e)}findRecentByQueryPrefix(e,t=10){return e.trim()?this.all(`SELECT id, query, mode, branch, created_at FROM search_history
561
+ 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)<=no||this.run(`DELETE FROM search_history WHERE id NOT IN (
538
562
  SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
539
- )`,Ir)}}});var Hn,$r=Z(()=>{"use strict";Ue();Hn=class extends ae{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(`
563
+ )`,no)}}});var ti,so=ee(()=>{"use strict";qe();ti=class extends pe{getSection(e){return this.get("SELECT section, data, updated_at FROM hologram_snapshot WHERE section = ?",e)}getAllSections(){return this.all("SELECT section, data, updated_at FROM hologram_snapshot ORDER BY section")}upsertSection(e,t){this.run(`
540
564
  INSERT INTO hologram_snapshot (section, data, updated_at)
541
565
  VALUES (?, ?, unixepoch())
542
566
  ON CONFLICT(section) DO UPDATE SET
543
567
  data = excluded.data,
544
568
  updated_at = excluded.updated_at
545
- `,e,t)}deleteSection(e){this.run("DELETE FROM hologram_snapshot WHERE section = ?",e)}deleteAll(){this.run("DELETE FROM hologram_snapshot")}hasSection(e){return(this.get("SELECT COUNT(*) as count FROM hologram_snapshot WHERE section = ?",e)?.count??0)>0}}});var O,V=Z(()=>{"use strict";Ze();lr();pr();mr();Tr();Rr();kr();Cr();Lr();$r();O=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=Te(e),o=t.files?.database,a=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!a)return t;this.repositoryCache.delete(e)}let n=Te(e),i={files:new Cn(n),exports:new In(n),imports:new Ln(n),missions:new Nn(n),intentLogs:new Dn(n),configs:new On(n),content:new Fn(n),searchHistory:new Wn(n),hologram:new Hn(n)};return this.repositoryCache.set(e,i),i}static closeInstance(e){this.repositoryCache.delete(e),kn(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var Mr=jc((gh,is)=>{var Un=process||{},Ar=Un.argv||[],zn=Un.env||{},Cl=!(zn.NO_COLOR||Ar.includes("--no-color"))&&(!!zn.FORCE_COLOR||Ar.includes("--color")||Un.platform==="win32"||(Un.stdout||{}).isTTY&&zn.TERM!=="dumb"||!!zn.CI),Il=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+Ll(i,e,t,r)+e:s+i+e},Ll=(s,e,t,n)=>{let i="",r=0;do i+=s.substring(r,n)+t,r=n+e.length,n=s.indexOf(e,r);while(~n);return i+s.substring(r)},Pr=(s=Cl)=>{let e=s?Il:()=>String;return{isColorSupported:s,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};is.exports=Pr();is.exports.createColors=Pr});var ai,ci,Co,li,Io,Lo,$o,Ao,Po,Mo,No,Do,Oo,Fo,mn,pi,Wo,Ho,ys=Z(()=>{"use strict";ai=[/\/pages\/(?!_)[^/]+\.(tsx?|jsx?)$/i,/\/pages\/.*\/index\.(tsx?|jsx?)$/i,/\/app\/.*\/page\.(tsx?|jsx?)$/i,/\/app\/.*\/layout\.(tsx?|jsx?)$/i,/\/app\/api\/.*\/route\.(ts|js)$/i,/\/pages\/api\/.*\.(ts|js)$/i],ci=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],Co=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],li=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],Io=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],Lo=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],$o=[/\/commands?\/[^/]+\.(ts|js|py|php)$/i,/\/cli\/[^/]+\.(ts|js|py|php)$/i,/\/bin\/[^/]+\.(ts|js|py|php)$/i,/cli\.(ts|js|py|php)$/i,/main\.(ts|js|py|php)$/i],Ao=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],Po=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],Mo=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],No=[/\/stores?\//i,/\/slices?\//i,/\/reducers?\//i,/\/atoms?\//i,/\/selectors?\//i,/\.(store|slice|reducer|atom|selector)\.(ts|js)$/i,/.*Slice\.(ts|js)$/i,/.*Store\.(ts|js)$/i],Do=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],Oo=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],Fo=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],mn=[/\.(model|entity|schema|repository|repo|dao|migration|query|mutation|resolver|connection|db)\.(ts|js)$/i,/queries\.(ts|js)$/i,/mutations\.(ts|js)$/i,/resolvers\.(ts|js)$/i,/connection\.(ts|js)$/i,/\/models?\//i,/\/entities?\//i,/\/repositories?\//i,/\/repos?\//i,/\/data\//i,/\/database\//i,/\/prisma\//i,/\/drizzle\//i,/\/api\/.*client\.(ts|js|tsx)$/i,/(^|\/)[A-Z0-9_-]*API\.(tsx?|js|jsx)$/],pi=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],Wo=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],Ho=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var ui,Uo,di,jo,bs=Z(()=>{"use strict";ui=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],Uo=[/views\.py$/i,/forms\.py$/i,/serializers\.py$/i,/admin\.py$/i,/apps\.py$/i,/tasks\.py$/i,/middlewares?\.py$/i,/signals?\.py$/i,/context_processors\.py$/i],di=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],jo=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var mi,Go,hi,qo,_s=Z(()=>{"use strict";mi=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],Go=[/\/services?\/.*\.php$/i,/\/providers?\/.*\.php$/i,/\/middleware\/.*\.php$/i,/\/jobs?\/.*\.php$/i,/\/listeners?\/.*\.php$/i,/\/events?\/.*\.php$/i,/\/observers?\/.*\.php$/i,/\/console\/commands\/.*\.php$/i,/\/actions?\/.*\.php$/i,/\/traits?\/.*\.php$/i,/\/concerns?\/.*\.php$/i,/\/contracts?\/.*\.php$/i],hi=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],qo=["laravel","symfony","slim","cakephp","codeigniter"]});import Jo from"path";function Ct(s,e,t){let n=[],i="Unknown",r=0;t||(t=Rp(s,e));let{inDegree:o,outDegree:a}=t,c=(d,h,m,f)=>{for(let _ of d)if(_.test(s))return n.push(`${f}: ${_.source}`),i=h,r+=m,!0;return!1},l=!1;if(l||(l=c(ai,"Entry",45,"Next.js entry")),l||(l=c(Io,"Entry",40,"MCP handler")),l||(l=c($o,"Entry",40,"CLI command")),l||(l=c(mn,"Data",45,"Data layer/Repository")),l||(l=c(No,"Data",35,"State management")),l||(l=c(Co,"Logic",40,"React component")),l||(l=c(li,"Logic",35,"Logic pattern")),l||(l=c(Ao,"Logic",35,"Parser/AST")),l||(l=c(Po,"Logic",35,"Core module")),l||(l=c(Mo,"Logic",30,"UI layer")),l||(l=c(Fo,"Types",35,"Type definition")),l||(l=c(ui,"Entry",40,"Python Entry")),l||(l=c(di,"Data",40,"Python Data")),l||(l=c(Uo,"Logic",35,"Python Logic")),l||(l=c(mi,"Entry",40,"PHP Entry")),l||(l=c(hi,"Data",40,"PHP Data")),l||(l=c(Go,"Logic",35,"PHP Logic")),l||(l=c(Do,"Logic",35,"Hook/Context")),!l){for(let d of Lo)if(d.test(s)){n.push(`MCP utility: ${d.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,l=!0;break}}l||c(Oo,"Data",35,"Schema definition")&&(l=!0),l||(c(mn,"Data",30,"Path matches data pattern")||c(pi,"Utility",25,"Path matches utility pattern")||c(ci,"Entry",30,"Path matches entry pattern"))&&(l=!0);for(let d of Es)if(d.test(s)){n.push(`Test file: ${d.source}`),i="Test",r=50,l=!0;break}l||c(Ss,"Infrastructure",40,"Infrastructure")&&(l=!0);for(let d of Tp)d.test(s)&&(n.push(`Monorepo component: ${d.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let u=e.imports.getImportsForFile(s).map(d=>d.module_specifier.toLowerCase());for(let d of Ho)if(u.some(h=>h.includes(d))){n.push(`Imports JS data library: ${d}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let d of jo)if(u.some(h=>h.includes(d))){n.push(`Imports Python framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of qo)if(u.some(h=>h.includes(d))){n.push(`Imports PHP framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of Wo)if(u.some(h=>h.includes(d))){n.push(`Imports JS framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}if(o===0&&a>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),i==="Unknown"?(i="Entry",r+=30):i==="Entry"&&(r+=15)),o>5&&a<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),i==="Unknown"?(i="Utility",r+=25):i==="Utility"&&(r+=10)),i==="Unknown"&&o>0&&a>0){let d=o/(o+a);d>.3&&d<.7&&(n.push(`Balanced traffic: in=${o}, out=${a} (likely Logic layer)`),i="Logic",r+=25)}return i==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:i,confidence:r,signals:n}}function Rp(s,e){let t=e.imports.countDependents(s),n=e.imports.countByFile(s);return{inDegree:t,outDegree:n}}function mt(s,e){let t=s.files.getAllPaths().map(m=>({path:m})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let m of t){let f=Ct(m.path,s);n.set(m.path,f),i[f.layer].push({path:m.path,classification:f})}let r={Entry:dt(i.Entry,e),Logic:dt(i.Logic,e),Data:dt(i.Data,e),Utility:dt(i.Utility,e),Infrastructure:dt(i.Infrastructure,e),Test:dt(i.Test,e),Types:dt(i.Types,e),Unknown:dt(i.Unknown,e)},o={};t.forEach(m=>{let f=Jo.extname(m.path).toLowerCase();f&&(o[f]=(o[f]||0)+1)});let a={".ts":"TypeScript",".tsx":"Typescript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".php":"PHP",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".vue":"Vue"},c={};Object.entries(o).forEach(([m,f])=>{let _=a[m];_&&(c[_]=(c[_]||0)+f)});let l=Object.entries(c).sort((m,f)=>f[1]-m[1]),p=l.length>0?l[0][0]:"Unknown",{pattern:u,patternConfidence:d,insights:h}=kp(r,t.length,s);return{pattern:u,patternConfidence:d,layers:r,insights:h,primaryStack:p}}function dt(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:Jo.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function kp(s,e,t){let n=[],i="Unknown",r=0,o=s.Entry.count/e*100,a=s.Logic.count/e*100,c=s.Data.count/e*100,l=s.Utility.count/e*100,p=s.Unknown.count/e*100;o>5&&a>10&&c>5&&p<40?(i="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${a.toFixed(1)}%), Data (${c.toFixed(1)}%)`)):l>20?(i="Modular",r=50+l/2,n.push(`High shared module usage: ${l.toFixed(1)}% utility files`)):p>60&&(i="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let u=t.configs.countByKind("Service");return u>3&&(i="Microservices",r=55+u*5,n.push(`Detected ${u} service definitions (likely microservices)`)),s.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),s.Data.count===0&&n.push("\u26A0\uFE0F No data layer detected - repository may not use traditional ORM patterns"),l>30&&n.push(`High utility concentration (${l.toFixed(1)}%) - good reusability`),{pattern:i,patternConfidence:Math.min(100,r),insights:n}}var Es,Ss,Tp,It=Z(()=>{"use strict";ys();bs();_s();Es=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],Ss=[/Dockerfile/i,/docker-compose/i,/\.ya?ml$/i,/nginx\.conf/i,/\/infra\//i,/\/deploy\//i,/\/k8s\//i,/\/kubernetes\//i,/\/terraform\//i,/\/ansible\//i,/package\.json/i,/tsconfig.*\.json/i,/\.env/i],Tp=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});function wu(s){try{return JSON.stringify(s)}catch{return String(s)}}function At(s){if(s instanceof Error)return s.message;if(typeof s=="string")return s;if(s&&typeof s=="object"&&"message"in s){let e=s.message;if(typeof e=="string"&&e.trim())return e}return wu(s)}function ye(s){if(s instanceof Error){let e;return"cause"in s&&s.cause!==void 0&&(e=At(s.cause)),{errorName:s.name||"Error",errorMessage:s.message,errorStack:s.stack,...e?{errorCause:e}:{}}}return s&&typeof s=="object"?{errorName:s.constructor?.name||"Object",errorMessage:At(s)}:{errorName:typeof s,errorMessage:At(s)}}var gn=Z(()=>{"use strict"});var wa={};qi(wa,{HologramService:()=>Se});var Oe,Se,Gt=Z(()=>{"use strict";V();It();q();gn();Oe=S.child({module:"hologram"}),Se=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=O.getInstance(e)}updateTopography(e){Oe.debug({repoPath:this.repoPath},"Updating topography snapshot");let t=Object.values(e.layers).reduce((r,o)=>r+o.count,0),n={};for(let[r,o]of Object.entries(e.layers)){let a=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(a*10)/10,topFiles:o.topFiles.slice(0,3).map(c=>({path:c.path,confidence:c.confidence}))}}let i={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(i)),Oe.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=mt(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){Oe.debug({repoPath:this.repoPath,count:e.length},"Updating gravity zones");let t={hotspots:e.slice(0,50),updatedAt:Date.now()};this.repos.hologram.upsertSection("gravity",JSON.stringify(t)),Oe.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){Oe.debug({repoPath:this.repoPath,count:e.length},"Updating ghost bridges");let t={bridges:e.slice(0,20),updatedAt:Date.now()};this.repos.hologram.upsertSection("ghosts",JSON.stringify(t)),Oe.info({repoPath:this.repoPath},"Ghost bridges updated")}getSnapshot(){let e=this.repos.hologram.getAllSections(),t={metadata:{repoPath:this.repoPath,lastUpdated:Date.now(),version:"1.0.0"}};for(let n of e)try{let i=JSON.parse(n.data);switch(n.section){case"topography":t.topography=i;break;case"gravity":t.gravity=i;break;case"ghosts":t.ghosts=i;break}}catch(i){Oe.debug({repoPath:this.repoPath,section:n.section,...ye(i)},"Skipping malformed hologram section")}return t}getSection(e){let t=this.repos.hologram.getSection(e);if(!t)return null;try{return JSON.parse(t.data)}catch(n){return Oe.debug({repoPath:this.repoPath,section:e,...ye(n)},"Skipping malformed hologram section"),null}}computeGravityZones(){Oe.debug({repoPath:this.repoPath},"Computing gravity zones from import graph");let e=this.repos.files.getAllPaths(),t=new Map;for(let i of e){let r=Ct(i,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(i);if(o.length===0)continue;let a=this.repos.imports.countDependents(i),c=this.repos.imports.countByFile(i),l=a*2+c;if(l>0){let p=o.find(d=>d.kind!=="TsTypeAliasDeclaration"&&d.kind!=="TsInterfaceDeclaration")||o[0],u=`${i}::${p.name}`;t.set(u,{symbol:p.name,filePath:i,inDegree:a,outDegree:c,gravity:l})}}let n=Array.from(t.values()).sort((i,r)=>r.gravity-i.gravity).slice(0,50);return Oe.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),Oe.info({repoPath:this.repoPath},"Hologram cleared")}}});var pc={};qi(pc,{GraphExporterService:()=>Vs});var lc,Vs,uc=Z(()=>{"use strict";V();q();lc=S.child({module:"graph-exporter"}),Vs=class{constructor(e){this.repoPath=e;this.repos=O.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;lc.info({focusMissionId:i,depth:r,format:n,includeCompleted:t},"Generating mission graph");let a=this.buildMissionTree(i,t,r,o);return n==="json"?JSON.stringify(a,null,2):this.generateMermaidDiagram(a)}buildMissionTree(e,t,n,i){let r;if(e){let c=this.repos.missions.findById(e);r=c?[c]:[]}else r=this.repos.missions.findAll().filter(l=>!l.parent_id),t||(r=r.filter(l=>l.status!=="completed"));let o=0,a=[];for(let c of r){if(o>=i)break;let l=this.buildNode(c,t,n,1,{count:o,max:i});l&&(a.push(l),o+=this.countNodes(l))}return a}buildNode(e,t,n,i,r){if(i>n||r.count>=r.max)return null;let o;if(e.strategy_graph)try{let p=JSON.parse(e.strategy_graph);o=this.parseStrategySteps(p)}catch(p){lc.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let a={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},c=this.repos.missions.findByParentId(e.id),l=t?c:c.filter(p=>p.status!=="completed");for(let p of l){if(r.count>=r.max)break;let u=this.buildNode(p,t,n,i+1,r);u&&(a.children.push(u),r.count++)}return a}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,i)=>({id:n.id||`step-${i}`,description:n.description||n.content||n.name||`Step ${i+1}`,status:n.status,dependencies:n.dependencies||n.deps})):e.steps&&Array.isArray(e.steps)?this.parseStrategySteps(e.steps):typeof e=="object"?Object.entries(e).map(([n,i])=>({id:n,description:i.description||i.content||n,status:i.status,dependencies:i.dependencies||i.deps})):t}countNodes(e){let t=1;for(let n of e.children)t+=this.countNodes(n);return t}generateMermaidDiagram(e){let t=["graph TD"];for(let n of e)this.addMermaidNode(n,t);return t.join(`
546
- `)}addMermaidNode(e,t,n){let i=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),a=`${r} ${e.name}`;if(t.push(` ${i}["${this.escapeMermaid(a)}"]:::${o}`),n&&t.push(` ${n} --> ${i}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let c of e.steps){let l=`S${e.id}_${c.id}`,p=c.status||"pending",u=this.getStatusIcon(p),d=this.getStatusClass(p),h=`${u} ${c.description}`;if(t.push(` ${l}["${this.escapeMermaid(h)}"]:::${d}`),t.push(` ${i} -.-> ${l}`),c.dependencies&&c.dependencies.length>0)for(let m of c.dependencies){let f=`S${e.id}_${m}`;t.push(` ${f} --> ${l}`)}}for(let c of e.children)this.addMermaidNode(c,t,i);n||(t.push(""),t.push(" classDef completed fill:#90EE90,stroke:#2E8B57,stroke-width:2px"),t.push(" classDef inProgress fill:#87CEEB,stroke:#4682B4,stroke-width:2px"),t.push(" classDef planned fill:#FFE4B5,stroke:#DAA520,stroke-width:2px"),t.push(" classDef suspended fill:#D3D3D3,stroke:#808080,stroke-width:2px"),t.push(" classDef failed fill:#FFB6C1,stroke:#DC143C,stroke-width:2px"),t.push(" classDef pending fill:#FFF8DC,stroke:#B8860B,stroke-width:1px"))}getStatusIcon(e){return{completed:"\u2713","in-progress":"\u26A1",planned:"\u{1F4CB}",suspended:"\u23F8",failed:"\u2717",pending:"\u25CB",verifying:"\u{1F50D}"}[e]||"\u25CB"}getStatusClass(e){return{completed:"completed","in-progress":"inProgress",planned:"planned",suspended:"suspended",failed:"failed",pending:"pending",verifying:"inProgress"}[e]||"pending"}escapeMermaid(e){return e.replace(/"/g,"#quot;").replace(/\n/g," ").replace(/\[/g,"#91;").replace(/]/g,"#93;").slice(0,100)}}});import"dotenv/config";import{Cli as Yd}from"clerc";q();import Xs from"fs";import Yc from"path";import Zs from"js-yaml";var er={ignore:[],include:[],maxDepth:10},Kc=[{name:".liquid-shadow.yaml",parse:s=>Zs.load(s)??{}},{name:".liquid-shadow.yml",parse:s=>Zs.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 Ke(s){for(let{name:e,parse:t}of Kc){let n=Yc.join(s,e);if(Xs.existsSync(n))try{let i=Xs.readFileSync(n,"utf8"),r=t(i);return S.debug({repoPath:s,configFile:e},"Loaded repository configuration"),{...er,...r}}catch(i){S.error({repoPath:s,file:e,err:i},"Failed to parse configuration file")}}return er}function Vi(s,e){let n=Ke(s).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}V();import Al from"path";var ue=Gc(Mr(),1);import*as je from"@clack/prompts";var K={red:ue.default.red,green:ue.default.green,yellow:ue.default.yellow,blue:ue.default.blue,magenta:ue.default.magenta,cyan:ue.default.cyan,white:ue.default.white,gray:ue.default.gray,bold:ue.default.bold,dim:ue.default.dim,italic:ue.default.italic,underline:ue.default.underline,inverse:ue.default.inverse},at=s=>s.replace(/\x1b\[[0-9;]*m/g,""),pe=s=>je.intro(ue.default.bgCyan(ue.default.black(ue.default.bold(` ${s} `)))),Pe=s=>je.outro(ue.default.cyan(s)),se=(s,e,t="blue")=>{let n=e.split(`
547
- `),i=at(s),r=Math.max(i.length+4,...n.map(c=>at(c).length))+2,o="\u2500".repeat(r),a=K[t];console.log(a(`\u250C${o}\u2510`)),console.log(a("\u2502 ")+K.bold(s).padEnd(r+(s.length-i.length)-1)+a("\u2502")),console.log(a(`\u251C${o}\u2524`)),n.forEach(c=>{let l=at(c),p=" ".repeat(r-l.length-1);console.log(a("\u2502 ")+c+p+a("\u2502"))}),console.log(a(`\u2514${o}\u2518`))},jn=(s,e)=>{let t=s.map((i,r)=>Math.max(at(i).length,...e.map(o=>at(o[r]||"").length))+2),n=K.cyan("\u2502");console.log(n),console.log(n+" "+s.map((i,r)=>K.bold(K.cyan(i)).padEnd(t[r]+(i.length-at(i).length))).join(K.gray(" "))+" "),e.forEach(i=>{console.log(n+" "+i.map((r,o)=>(r||"").padEnd(t[o]+(r.length-at(r).length))).join(K.gray(" "))+" ")}),console.log(n)},Nr=(s,e="\u2022")=>{s.forEach(t=>{console.log(`${K.cyan("\u2502")} ${K.cyan(e)} ${t}`)})},Bn=(s,e=40)=>{let t=Math.max(...s.map(i=>i.value)),n=Math.max(...s.map(i=>at(i.label).length));console.log(K.cyan("\u2502")),s.forEach(i=>{let r=Math.round(i.value/t*e),o="\u2588".repeat(r)+K.dim("\u2591".repeat(e-r)),a=i.color?K[i.color]:K.cyan,c=i.label.padEnd(n);console.log(`${K.cyan("\u2502")} ${K.bold(c)} ${a(o)} ${K.white(i.value.toString())}`)}),console.log(K.cyan("\u2502"))},ss=(s,e="")=>{s.forEach((t,n)=>{let i=n===s.length-1,r=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?K[t.color]:t.children?K.blue:K.white,a=t.info?` ${K.gray(`(${t.info})`)}`:"";if(console.log(`${K.cyan("\u2502")} ${e}${K.gray(r)}${o(t.name)}${a}`),t.children&&t.children.length>0){let c=e+(i?" ":"\u2502 ");ss(t.children,c)}})},Re=()=>je.spinner();async function Gn(s,e,t){if(e.length===0)return;let n=await je.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(!je.isCancel(n))return n}var $l=s=>{console.error("");let e=s instanceof Error?s.message:String(s);console.error(` ${K.red("\u2716")} ${K.bold("Error: ")} ${e}`),s instanceof Error&&"cause"in s&&console.error(` ${K.dim("Cause: "+String(s.cause))}`),console.error(""),process.exit(1)},Y=async s=>{try{await s()}catch(e){$l(e)}},y=K;Ae();Ze();q();async function Q(s){S.debug("Performing graceful shutdown...");try{await $n()}catch(e){S.error({err:e},"Error shutting down worker pool")}try{s&&kn(s)}catch(e){S.error({err:e},"Error closing database")}S.debug("Shutdown complete")}async function Dr(s){let e=Al.resolve(s);try{await Y(async()=>{pe("\u{1F311} Liquid Shadow: Scouting Report");let t=O.getInstance(e),n=Ke(e),i=n.ignore&&n.ignore.length>0,r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);se("Intelligence Summary",`${y.bold("\u{1F4E1} Topology")}: ${y.cyan(r.toString())} files mapped
548
- ${y.bold("\u{1F9E9} Symbols")}: ${y.cyan(o.toString())} exports detected
549
- ${y.bold("\u{1F552} Last Sync")}: ${a?y.yellow(new Date(a).toLocaleString()):y.red("Never")}
550
- ${y.bold("\u2699\uFE0F Config")}: ${i?y.green("Custom Intelligence"):y.gray("Standard Sieve")}`,"blue"),c.length>0&&(console.log(""),console.log(` ${y.bold("Symbol Distribution (Top 5)")}`),Bn(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),30)),console.log(""),console.log(` ${y.dim("Pro-tip: Try")} ${y.bold(y.cyan("liquid-shadow dashboard"))} ${y.dim("for the full tactical view.")}`),console.log(""),Pe("Scouting complete.")})}finally{await Q(e)}}V();Ze();import jr from"path";var rs=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}},ct=new rs;function Or(){ct.recordIndexStart()}function os(){ct.recordIndexCacheHit()}function Fr(s){ct.recordIndexEnd(s)}function an(s,e){ct.recordIndexPhase(s,e)}function Wr(){ct.clearIndexPhases()}function qn(){return ct.recordQueryStart()}function Ft(){ct.recordSearchHistoryFailure()}function Vn(){return ct.getSnapshot()}q();St();import ee from"fs";import Pl from"os";import Be from"path";var wt=S.child({module:"git-hooks"}),Ml="Generated by liquid-shadow",Nl=1e6,Hr=["post-merge","post-checkout","post-commit"];function Dl(){let s=process.env.LIQUID_SHADOW_CLI_ENTRY;if(s){let t=Be.resolve(s);if(ee.existsSync(t))return t}let e=_e("dist/entry/cli/index.js");return ee.existsSync(e)?e:null}function as(s){return s.includes("liquid-shadow")||s.includes("mcp-liquid-shadow")||s.includes(Ml)}function Ol(){let s=Be.join(Pl.homedir(),".mcp-liquid-shadow","logs"),e=Be.join(s,"post-checkout.log");try{if(!ee.existsSync(e)||ee.statSync(e).size<=Nl)return null;ee.mkdirSync(s,{recursive:!0});let n=`${e}.1`;return ee.existsSync(n)&&ee.unlinkSync(n),ee.renameSync(e,n),null}catch(t){return`Failed to rotate post-checkout.log: ${t}`}}function Fl(s,e){return{"post-merge":`#!/bin/sh
569
+ `,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 ni,ro=ee(()=>{"use strict";qe();ni=class extends pe{claimFile(e,t){try{this.run(`
570
+ INSERT INTO file_claims (file_path, mission_id, claimed_at, updated_at)
571
+ VALUES (?, ?, unixepoch(), unixepoch())
572
+ `,e,t);let n=this.getClaim(e);if(!n)throw new Error(`Failed to hydrate claim after insert for file ${e}`);return{status:"claimed",claim:n}}catch{let n=this.getClaim(e);if(!n)throw new Error(`Failed to read existing claim for file ${e}`);return n.mission_id===t?(this.run("UPDATE file_claims SET updated_at = unixepoch() WHERE file_path = ?",e),{status:"already_claimed",claim:this.getClaim(e)??n}):{status:"conflict",claim:n}}}releaseFile(e,t){let n=this.getClaim(e);return n?t!==void 0&&n.mission_id!==t?{released:!1,reason:"not_owner",claim:n}:(this.run("DELETE FROM file_claims WHERE file_path = ?",e),{released:!0}):{released:!1,reason:"not_found"}}releaseAllForMission(e){return this.run("DELETE FROM file_claims WHERE mission_id = ?",e)}getClaim(e){return this.get(`
573
+ SELECT
574
+ fc.file_path,
575
+ fc.mission_id,
576
+ fc.claimed_at,
577
+ fc.updated_at,
578
+ m.name AS mission_name,
579
+ m.status AS mission_status,
580
+ m.git_branch AS mission_branch
581
+ FROM file_claims fc
582
+ LEFT JOIN missions m ON m.id = fc.mission_id
583
+ WHERE fc.file_path = ?
584
+ `,e)}getClaimsForMission(e){return this.all(`
585
+ SELECT
586
+ fc.file_path,
587
+ fc.mission_id,
588
+ fc.claimed_at,
589
+ fc.updated_at,
590
+ m.name AS mission_name,
591
+ m.status AS mission_status,
592
+ m.git_branch AS mission_branch
593
+ FROM file_claims fc
594
+ LEFT JOIN missions m ON m.id = fc.mission_id
595
+ WHERE fc.mission_id = ?
596
+ ORDER BY fc.file_path ASC
597
+ `,e)}listClaims(){return this.all(`
598
+ SELECT
599
+ fc.file_path,
600
+ fc.mission_id,
601
+ fc.claimed_at,
602
+ fc.updated_at,
603
+ m.name AS mission_name,
604
+ m.status AS mission_status,
605
+ m.git_branch AS mission_branch
606
+ FROM file_claims fc
607
+ LEFT JOIN missions m ON m.id = fc.mission_id
608
+ ORDER BY fc.updated_at DESC, fc.file_path ASC
609
+ `)}getClaimsByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`
610
+ SELECT
611
+ fc.file_path,
612
+ fc.mission_id,
613
+ fc.claimed_at,
614
+ fc.updated_at,
615
+ m.name AS mission_name,
616
+ m.status AS mission_status,
617
+ m.git_branch AS mission_branch
618
+ FROM file_claims fc
619
+ LEFT JOIN missions m ON m.id = fc.mission_id
620
+ WHERE fc.file_path IN (${t})
621
+ ORDER BY fc.file_path ASC
622
+ `,...e)}}});var F,Y=ee(()=>{"use strict";dt();Dr();Or();Hr();Zr();Xr();eo();to();io();so();ro();F=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=Oe(e),o=t.files?.database,l=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram||!t.claims;if(o===r&&r.open&&!l)return t;this.repositoryCache.delete(e)}let n=Oe(e),i={files:new Un(n),exports:new jn(n),imports:new Gn(n),missions:new Kn(n),intentLogs:new Qn(n),configs:new Zn(n),content:new Xn(n),searchHistory:new ei(n),hologram:new ti(n),claims:new ni(n)};return this.repositoryCache.set(e,i),i}static closeInstance(e){this.repositoryCache.delete(e),Bn(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var co=_l((th,xs)=>{var si=process||{},oo=si.argv||[],ii=si.env||{},sp=!(ii.NO_COLOR||oo.includes("--no-color"))&&(!!ii.FORCE_COLOR||oo.includes("--color")||si.platform==="win32"||(si.stdout||{}).isTTY&&ii.TERM!=="dumb"||!!ii.CI),rp=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+op(i,e,t,r)+e:s+i+e},op=(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)},ao=(s=sp)=>{let e=s?rp:()=>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")}};xs.exports=ao();xs.exports.createColors=ao});var xi,wi,na,vi,ia,sa,ra,oa,aa,ca,la,pa,ua,da,Tn,Ri,ma,fa,Ds=ee(()=>{"use strict";xi=[/\/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],wi=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],na=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],vi=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],ia=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],sa=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],ra=[/\/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],oa=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],aa=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],ca=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],la=[/\/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],pa=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],ua=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],da=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],Tn=[/\.(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)$/],Ri=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],ma=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],fa=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var Ti,ga,ki,ya,Os=ee(()=>{"use strict";Ti=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],ga=[/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],ki=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],ya=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var Ci,_a,Ii,Ea,Fs=ee(()=>{"use strict";Ci=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],_a=[/\/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],Ii=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],Ea=["laravel","symfony","slim","cakephp","codeigniter"]});import xa from"path";function Ut(s,e,t){let n=[],i="Unknown",r=0;t||(t=nu(s,e));let{inDegree:o,outDegree:a}=t,l=(d,h,m,f)=>{for(let b of d)if(b.test(s))return n.push(`${f}: ${b.source}`),i=h,r+=m,!0;return!1},c=!1;if(c||(c=l(xi,"Entry",45,"Next.js entry")),c||(c=l(ia,"Entry",40,"MCP handler")),c||(c=l(ra,"Entry",40,"CLI command")),c||(c=l(Tn,"Data",45,"Data layer/Repository")),c||(c=l(la,"Data",35,"State management")),c||(c=l(na,"Logic",40,"React component")),c||(c=l(vi,"Logic",35,"Logic pattern")),c||(c=l(oa,"Logic",35,"Parser/AST")),c||(c=l(aa,"Logic",35,"Core module")),c||(c=l(ca,"Logic",30,"UI layer")),c||(c=l(da,"Types",35,"Type definition")),c||(c=l(Ti,"Entry",40,"Python Entry")),c||(c=l(ki,"Data",40,"Python Data")),c||(c=l(ga,"Logic",35,"Python Logic")),c||(c=l(Ci,"Entry",40,"PHP Entry")),c||(c=l(Ii,"Data",40,"PHP Data")),c||(c=l(_a,"Logic",35,"PHP Logic")),c||(c=l(pa,"Logic",35,"Hook/Context")),!c){for(let d of sa)if(d.test(s)){n.push(`MCP utility: ${d.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,c=!0;break}}c||l(ua,"Data",35,"Schema definition")&&(c=!0),c||(l(Tn,"Data",30,"Path matches data pattern")||l(Ri,"Utility",25,"Path matches utility pattern")||l(wi,"Entry",30,"Path matches entry pattern"))&&(c=!0);for(let d of Ws)if(d.test(s)){n.push(`Test file: ${d.source}`),i="Test",r=50,c=!0;break}c||l(Hs,"Infrastructure",40,"Infrastructure")&&(c=!0);for(let d of tu)d.test(s)&&(n.push(`Monorepo component: ${d.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let u=e.imports.getImportsForFile(s).map(d=>d.module_specifier.toLowerCase());for(let d of fa)if(u.some(h=>h.includes(d))){n.push(`Imports JS data library: ${d}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let d of ya)if(u.some(h=>h.includes(d))){n.push(`Imports Python framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of Ea)if(u.some(h=>h.includes(d))){n.push(`Imports PHP framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of ma)if(u.some(h=>h.includes(d))){n.push(`Imports JS framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}if(o===0&&a>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),i==="Unknown"?(i="Entry",r+=30):i==="Entry"&&(r+=15)),o>5&&a<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),i==="Unknown"?(i="Utility",r+=25):i==="Utility"&&(r+=10)),i==="Unknown"&&o>0&&a>0){let d=o/(o+a);d>.3&&d<.7&&(n.push(`Balanced traffic: in=${o}, out=${a} (likely Logic layer)`),i="Logic",r+=25)}return i==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:i,confidence:r,signals:n}}function nu(s,e){let t=e.imports.countDependents(s),n=e.imports.countByFile(s);return{inDegree:t,outDegree:n}}function kt(s,e){let t=s.files.getAllPaths().map(m=>({path:m})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let m of t){let f=Ut(m.path,s);n.set(m.path,f),i[f.layer].push({path:m.path,classification:f})}let r={Entry:Tt(i.Entry,e),Logic:Tt(i.Logic,e),Data:Tt(i.Data,e),Utility:Tt(i.Utility,e),Infrastructure:Tt(i.Infrastructure,e),Test:Tt(i.Test,e),Types:Tt(i.Types,e),Unknown:Tt(i.Unknown,e)},o={};t.forEach(m=>{let f=xa.extname(m.path).toLowerCase();f&&(o[f]=(o[f]||0)+1)});let a={".ts":"TypeScript",".tsx":"Typescript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".php":"PHP",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".vue":"Vue"},l={};Object.entries(o).forEach(([m,f])=>{let b=a[m];b&&(l[b]=(l[b]||0)+f)});let c=Object.entries(l).sort((m,f)=>f[1]-m[1]),p=c.length>0?c[0][0]:"Unknown",{pattern:u,patternConfidence:d,insights:h}=iu(r,t.length,s);return{pattern:u,patternConfidence:d,layers:r,insights:h,primaryStack:p}}function Tt(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:xa.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function iu(s,e,t){let n=[],i="Unknown",r=0,o=s.Entry.count/e*100,a=s.Logic.count/e*100,l=s.Data.count/e*100,c=s.Utility.count/e*100,p=s.Unknown.count/e*100;o>5&&a>10&&l>5&&p<40?(i="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${a.toFixed(1)}%), Data (${l.toFixed(1)}%)`)):c>20?(i="Modular",r=50+c/2,n.push(`High shared module usage: ${c.toFixed(1)}% utility files`)):p>60&&(i="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let u=t.configs.countByKind("Service");return u>3&&(i="Microservices",r=55+u*5,n.push(`Detected ${u} service definitions (likely microservices)`)),s.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),s.Data.count===0&&n.push("\u26A0\uFE0F No data layer detected - repository may not use traditional ORM patterns"),c>30&&n.push(`High utility concentration (${c.toFixed(1)}%) - good reusability`),{pattern:i,patternConfidence:Math.min(100,r),insights:n}}var Ws,Hs,tu,jt=ee(()=>{"use strict";Ds();Os();Fs();Ws=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],Hs=[/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],tu=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});function id(s){try{return JSON.stringify(s)}catch{return String(s)}}function qt(s){if(s instanceof Error)return s.message;if(typeof s=="string")return s;if(s&&typeof s=="object"&&"message"in s){let e=s.message;if(typeof e=="string"&&e.trim())return e}return id(s)}function Re(s){if(s instanceof Error){let e;return"cause"in s&&s.cause!==void 0&&(e=qt(s.cause)),{errorName:s.name||"Error",errorMessage:s.message,errorStack:s.stack,...e?{errorCause:e}:{}}}return s&&typeof s=="object"?{errorName:s.constructor?.name||"Object",errorMessage:qt(s)}:{errorName:typeof s,errorMessage:qt(s)}}var In=ee(()=>{"use strict"});var Za={};us(Za,{HologramService:()=>Ae});var Xe,Ae,cn=ee(()=>{"use strict";Y();jt();G();In();Xe=x.child({module:"hologram"}),Ae=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=F.getInstance(e)}updateTopography(e){Xe.debug({repoPath:this.repoPath},"Updating topography snapshot");let t=Object.values(e.layers).reduce((r,o)=>r+o.count,0),n={};for(let[r,o]of Object.entries(e.layers)){let a=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(a*10)/10,topFiles:o.topFiles.slice(0,3).map(l=>({path:l.path,confidence:l.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)),Xe.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=kt(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){Xe.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)),Xe.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){Xe.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)),Xe.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){Xe.debug({repoPath:this.repoPath,section:n.section,...Re(i)},"Skipping malformed hologram section")}return t}getSection(e){let t=this.repos.hologram.getSection(e);if(!t)return null;try{return JSON.parse(t.data)}catch(n){return Xe.debug({repoPath:this.repoPath,section:e,...Re(n)},"Skipping malformed hologram section"),null}}computeGravityZones(){Xe.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=Ut(i,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(i);if(o.length===0)continue;let a=this.repos.imports.countDependents(i),l=this.repos.imports.countByFile(i),c=a*2+l;if(c>0){let p=o.find(d=>d.kind!=="TsTypeAliasDeclaration"&&d.kind!=="TsInterfaceDeclaration")||o[0],u=`${i}::${p.name}`;t.set(u,{symbol:p.name,filePath:i,inDegree:a,outDegree:l,gravity:c})}}let n=Array.from(t.values()).sort((i,r)=>r.gravity-i.gravity).slice(0,50);return Xe.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),Xe.info({repoPath:this.repoPath},"Hologram cleared")}}});var Gc={};us(Gc,{GraphExporterService:()=>mr});var jc,mr,qc=ee(()=>{"use strict";Y();G();jc=x.child({module:"graph-exporter"}),mr=class{constructor(e){this.repoPath=e;this.repos=F.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;jc.info({focusMissionId:i,depth:r,format:n,includeCompleted:t},"Generating mission graph");let a=this.buildMissionTree(i,t,r,o);return n==="json"?JSON.stringify(a,null,2):this.generateMermaidDiagram(a)}buildMissionTree(e,t,n,i){if(e){let c=this.repos.missions.findById(e);if(!c)return[];let p={count:0,max:i},u=this.buildFocusedTree(c,t,n,p);return u?[u]:[]}let o=this.repos.missions.findAll().filter(c=>!c.parent_id);t||(o=o.filter(c=>c.status!=="completed"));let a={count:0,max:i},l=[];for(let c of o){if(a.count>=i)break;let p=this.buildNode(c,t,n,1,a,"descendant");p&&l.push(p)}return l}buildFocusedTree(e,t,n,i){let r=this.getMissionLineage(e),o=r.length>i.max?r.slice(r.length-i.max):r,a=null,l=null;for(let c=0;c<o.length&&!(i.count>=i.max);c++){let p=o[c],u=c===o.length-1,d=u?"focus":"ancestor",h=this.createMissionNode(p,d,u,u);i.count+=1,a?l&&l.children.push(h):a=h,l=h}return!a||!l?null:(this.attachChildren(l,e,t,n,1,i),a)}buildNode(e,t,n,i,r,o="descendant"){if(i>n||r.count>=r.max)return null;let a=this.createMissionNode(e,o,!1,!0);return r.count+=1,this.attachChildren(a,e,t,n,i,r),a}attachChildren(e,t,n,i,r,o){if(r>=i||o.count>=o.max)return;let a=this.repos.missions.findByParentId(t.id),l=n?a:a.filter(c=>c.status!=="completed");for(let c of l){if(o.count>=o.max)break;let p=this.buildNode(c,n,i,r+1,o,"descendant");p&&e.children.push(p)}}createMissionNode(e,t,n,i){let r;if(i&&e.strategy_graph)try{let o=JSON.parse(e.strategy_graph);r=this.parseStrategySteps(o)}catch(o){jc.debug({missionId:e.id,err:o},"Failed to parse strategy graph")}return{id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,relation:t,focus:n,children:[],steps:r}}getMissionLineage(e){let t=[e],n=new Set([e.id]),i=e;for(;i.parent_id!=null;){let r=this.repos.missions.findById(i.parent_id);if(!r||n.has(r.id))break;t.unshift(r),n.add(r.id),i=r}return t}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}generateMermaidDiagram(e){let t=["graph TD"];for(let n of e)this.addMermaidNode(n,t);return t.join(`
623
+ `)}addMermaidNode(e,t,n){let i=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),a=`${r} ${e.name}${e.focus?" [focus]":""}`;if(t.push(` ${i}["${this.escapeMermaid(a)}"]:::${o}`),n&&t.push(` ${n} --> ${i}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let l of e.steps){let c=`S${e.id}_${l.id}`,p=l.status||"pending",u=this.getStatusIcon(p),d=this.getStatusClass(p),h=`${u} ${l.description}`;if(t.push(` ${c}["${this.escapeMermaid(h)}"]:::${d}`),t.push(` ${i} -.-> ${c}`),l.dependencies&&l.dependencies.length>0)for(let m of l.dependencies){let f=`S${e.id}_${m}`;t.push(` ${f} --> ${c}`)}}for(let l of e.children)this.addMermaidNode(l,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 $m}from"clerc";G();import Rr from"fs";import Rl from"path";import Tr from"js-yaml";var kr={ignore:[],include:[],maxDepth:10},Tl=[{name:".liquid-shadow.yaml",parse:s=>Tr.load(s)??{}},{name:".liquid-shadow.yml",parse:s=>Tr.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 lt(s){for(let{name:e,parse:t}of Tl){let n=Rl.join(s,e);if(Rr.existsSync(n))try{let i=Rr.readFileSync(n,"utf8"),r=t(i);return x.debug({repoPath:s,configFile:e},"Loaded repository configuration"),{...kr,...r}}catch(i){x.error({repoPath:s,file:e,err:i},"Failed to parse configuration file")}}return kr}function ds(s,e){let n=lt(s).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}Y();import cp from"path";var ye=Sl(co(),1);import*as nt from"@clack/prompts";var te={red:ye.default.red,green:ye.default.green,yellow:ye.default.yellow,blue:ye.default.blue,magenta:ye.default.magenta,cyan:ye.default.cyan,white:ye.default.white,gray:ye.default.gray,bold:ye.default.bold,dim:ye.default.dim,italic:ye.default.italic,underline:ye.default.underline,inverse:ye.default.inverse},St=s=>s.replace(/\x1b\[[0-9;]*m/g,""),ge=s=>nt.intro(ye.default.bgCyan(ye.default.black(ye.default.bold(` ${s} `)))),Je=s=>nt.outro(ye.default.cyan(s)),ue=(s,e,t="blue")=>{let n=e.split(`
624
+ `),i=St(s),r=Math.max(i.length+4,...n.map(l=>St(l).length))+2,o="\u2500".repeat(r),a=te[t];console.log(a(`\u250C${o}\u2510`)),console.log(a("\u2502 ")+te.bold(s).padEnd(r+(s.length-i.length)-1)+a("\u2502")),console.log(a(`\u251C${o}\u2524`)),n.forEach(l=>{let c=St(l),p=" ".repeat(r-c.length-1);console.log(a("\u2502 ")+l+p+a("\u2502"))}),console.log(a(`\u2514${o}\u2518`))},ri=(s,e)=>{let t=s.map((i,r)=>Math.max(St(i).length,...e.map(o=>St(o[r]||"").length))+2),n=te.cyan("\u2502");console.log(n),console.log(n+" "+s.map((i,r)=>te.bold(te.cyan(i)).padEnd(t[r]+(i.length-St(i).length))).join(te.gray(" "))+" "),e.forEach(i=>{console.log(n+" "+i.map((r,o)=>(r||"").padEnd(t[o]+(r.length-St(r).length))).join(te.gray(" "))+" ")}),console.log(n)},lo=(s,e="\u2022")=>{s.forEach(t=>{console.log(`${te.cyan("\u2502")} ${te.cyan(e)} ${t}`)})},oi=(s,e=40)=>{let t=Math.max(...s.map(i=>i.value)),n=Math.max(...s.map(i=>St(i.label).length));console.log(te.cyan("\u2502")),s.forEach(i=>{let r=Math.round(i.value/t*e),o="\u2588".repeat(r)+te.dim("\u2591".repeat(e-r)),a=i.color?te[i.color]:te.cyan,l=i.label.padEnd(n);console.log(`${te.cyan("\u2502")} ${te.bold(l)} ${a(o)} ${te.white(i.value.toString())}`)}),console.log(te.cyan("\u2502"))},ws=(s,e="")=>{s.forEach((t,n)=>{let i=n===s.length-1,r=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?te[t.color]:t.children?te.blue:te.white,a=t.info?` ${te.gray(`(${t.info})`)}`:"";if(console.log(`${te.cyan("\u2502")} ${e}${te.gray(r)}${o(t.name)}${a}`),t.children&&t.children.length>0){let l=e+(i?" ":"\u2502 ");ws(t.children,l)}})},Fe=()=>nt.spinner();async function ai(s,e,t){if(e.length===0)return;let n=await nt.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(!nt.isCancel(n))return n}var ap=s=>{console.error("");let e=s instanceof Error?s.message:String(s);console.error(` ${te.red("\u2716")} ${te.bold("Error: ")} ${e}`),s instanceof Error&&"cause"in s&&console.error(` ${te.dim("Cause: "+String(s.cause))}`),console.error(""),process.exit(1)},Z=async s=>{try{await s()}catch(e){ap(e)}},_=te;Ve();dt();G();async function ne(s){x.debug("Performing graceful shutdown...");try{await qn()}catch(e){x.error({err:e},"Error shutting down worker pool")}try{s&&Bn(s)}catch(e){x.error({err:e},"Error closing database")}x.debug("Shutdown complete")}async function po(s){let e=cp.resolve(s);try{await Z(async()=>{ge("\u{1F311} Liquid Shadow: Scouting Report");let t=F.getInstance(e),n=lt(e),i=n.ignore&&n.ignore.length>0,r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),l=t.exports.getKindDistribution(5);ue("Intelligence Summary",`${_.bold("\u{1F4E1} Topology")}: ${_.cyan(r.toString())} files mapped
625
+ ${_.bold("\u{1F9E9} Symbols")}: ${_.cyan(o.toString())} exports detected
626
+ ${_.bold("\u{1F552} Last Sync")}: ${a?_.yellow(new Date(a).toLocaleString()):_.red("Never")}
627
+ ${_.bold("\u2699\uFE0F Config")}: ${i?_.green("Custom Intelligence"):_.gray("Standard Sieve")}`,"blue"),l.length>0&&(console.log(""),console.log(` ${_.bold("Symbol Distribution (Top 5)")}`),oi(l.map(c=>({label:c.kind,value:c.c,color:"cyan"})),30)),console.log(""),console.log(` ${_.dim("Pro-tip: Try")} ${_.bold(_.cyan("liquid-shadow dashboard"))} ${_.dim("for the full tactical view.")}`),console.log(""),Je("Scouting complete.")})}finally{await ne(e)}}Y();dt();import bo from"path";var vs=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];searchHistoryFailureCount=0;recordIndexStart(){this.indexRuns+=1}recordIndexCacheHit(){this.indexCacheHits+=1}recordIndexEnd(e){this.lastIndexDurationMs=e,this.lastIndexCompletedAt=Date.now()}recordIndexPhase(e,t){this.lastRunPhases.push({phase:e,durationMs:t})}clearIndexPhases(){this.lastRunPhases=[]}recordQueryStart(){let e=performance.now();return()=>{this.queryCount+=1;let t=performance.now()-e;if(this.lastQueryLatencyMs=t,this.recentLatencies.push(t),this.recentLatencies.length>100){let n=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-n+t}else this.recentLatencySumMs+=t,this.recentLatencyCount=this.recentLatencies.length}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((n,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}},xt=new vs;function uo(){xt.recordIndexStart()}function Rs(){xt.recordIndexCacheHit()}function mo(s){xt.recordIndexEnd(s)}function Sn(s,e){xt.recordIndexPhase(s,e)}function fo(){xt.clearIndexPhases()}function ci(){return xt.recordQueryStart()}function Xt(){xt.recordSearchHistoryFailure()}function li(){return xt.getSnapshot()}G();Dt();import re from"fs";import lp from"os";import it from"path";var Ot=x.child({module:"git-hooks"}),pp="Generated by liquid-shadow",up=1e6,ho=["post-merge","post-checkout","post-commit"];function dp(){let s=process.env.LIQUID_SHADOW_CLI_ENTRY;if(s){let t=it.resolve(s);if(re.existsSync(t))return t}let e=Le("dist/entry/cli/index.js");return re.existsSync(e)?e:null}function Ts(s){return s.includes("liquid-shadow")||s.includes("mcp-liquid-shadow")||s.includes(pp)}function mp(){let s=it.join(lp.homedir(),".mcp-liquid-shadow","logs"),e=it.join(s,"post-checkout.log");try{if(!re.existsSync(e)||re.statSync(e).size<=up)return null;re.mkdirSync(s,{recursive:!0});let n=`${e}.1`;return re.existsSync(n)&&re.unlinkSync(n),re.renameSync(e,n),null}catch(t){return`Failed to rotate post-checkout.log: ${t}`}}function fp(s,e){return{"post-merge":`#!/bin/sh
551
628
  # Liquid Shadow: Auto-refresh index after merge/pull
552
629
  # Generated by liquid-shadow
553
630
 
@@ -574,8 +651,8 @@ LOG_FILE="$LOG_DIR/post-checkout.log"
574
651
 
575
652
  mkdir -p "$LOG_DIR"
576
653
 
577
- # Run incremental index in background (force=false default preserves fast-path)
578
- nohup "${s}" "${e}" index "$REPO_PATH" --deep >> "$LOG_FILE" 2>&1 &
654
+ # Run incremental index in background (default mode preserves fast-path)
655
+ nohup "${s}" "${e}" index "$REPO_PATH" >> "$LOG_FILE" 2>&1 &
579
656
 
580
657
  exit 0
581
658
  `,"post-commit":`#!/bin/sh
@@ -588,30 +665,30 @@ REPO_PATH="$(git rev-parse --show-toplevel)"
588
665
  nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
589
666
 
590
667
  exit 0
591
- `}}function zr(s){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=s,i=Be.join(e,".git","hooks"),r=[],o=[],a=[];if(!ee.existsSync(Be.join(e,".git")))return a.push("Not a git repository"),{installed:r,skipped:o,errors:a};ee.existsSync(i)||ee.mkdirSync(i,{recursive:!0});let c=Dl();if(!c)return a.push(`Unable to resolve CLI entry at install time. Expected ${_e("dist/entry/cli/index.js")} to exist.`),{installed:r,skipped:o,errors:a};let l=Fl(process.execPath,c),p=new Set;if(t&&(p.add("post-merge"),p.add("post-checkout")),n&&p.add("post-commit"),p.has("post-checkout")){let u=Ol();u&&(a.push(u),wt.warn({rotationError:u},"Post-checkout log rotation failed"))}for(let u of p){let d=Be.join(i,u),h=l[u];if(!h){a.push(`No template found for hook: ${u}`);continue}try{if(ee.existsSync(d)){let m=ee.readFileSync(d,"utf-8"),f=as(m);if(f&&m===h){ee.chmodSync(d,493),o.push(u),wt.info({hookName:u},"Hook already installed, skipping");continue}if(!f){let _=`${d}.backup-${Date.now()}`;ee.copyFileSync(d,_),wt.info({hookName:u,backupPath:_},"Backed up existing hook")}}ee.writeFileSync(d,h,{mode:493}),ee.chmodSync(d,493),r.push(u),wt.info({hookName:u},"Installed git hook")}catch(m){a.push(`Failed to install ${u}: ${m}`),wt.error({hookName:u,err:m},"Failed to install hook")}}return{installed:r,skipped:o,errors:a}}function Ur(s){let e=Be.join(s,".git","hooks"),t=[],n=[];if(!ee.existsSync(e))return{removed:t,errors:n};for(let i of Hr){let r=Be.join(e,i);try{if(ee.existsSync(r)){let o=ee.readFileSync(r,"utf-8");as(o)&&(ee.unlinkSync(r),t.push(i),wt.info({hookName:i},"Removed git hook"))}}catch(o){n.push(`Failed to remove ${i}: ${o}`),wt.error({hookName:i,err:o},"Failed to remove hook")}}return{removed:t,errors:n}}function Wl(s,e){let t=Be.join(s,".git","hooks"),n=Be.join(t,e);if(!ee.existsSync(t)||!ee.existsSync(n))return"missing";try{let i=ee.readFileSync(n,"utf-8");return as(i)?(ee.statSync(n).mode&73)!==0?"installed":"disabled":"foreign"}catch{return"foreign"}}function Wt(s){let e=[],t=[],n=[],i=[],r={};for(let a of Hr){let c=Wl(s,a);r[a]=c,c==="installed"&&e.push(a),c==="missing"&&t.push(a),c==="foreign"&&n.push(a),c==="disabled"&&i.push(a)}let o=[...t,...n,...i];return{installed:e,notInstalled:o,missing:t,foreign:n,disabled:i,statuses:r}}async function cs(s){let e=jr.resolve(s);try{await Y(async()=>{pe("Liquid Shadow Intelligence Dashboard");let t=O.getInstance(e),n=Vn(),i=Wt(e),r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);if(se("Operational Core",`${y.bold("State")}: ${Xe(e)?y.green("IDENTIFIED (Stable)"):y.red("UNKNOWN (Needs Index)")}
592
- ${y.bold("Repository")}: ${y.cyan(jr.basename(e))}
593
- ${y.bold("Infrastructure")}: ${i.installed.length>0?y.green("Git-Hooked"):y.yellow("Standalone")}
594
- ${y.bold("Last Sync")}: ${a?y.yellow(new Date(a).toLocaleString()):y.red("Never")}`,"blue"),console.log(""),se("Intelligence Density",`${y.bold("Files Target")}: ${y.cyan(r.toString())}
595
- ${y.bold("Symbols Mapped")}: ${y.cyan(o.toString())}
596
- ${y.bold("Graph Edges")}: ${y.cyan(t.imports.getCount().toString())}
597
- ${y.bold("Hotspots")}: ${y.yellow(c.length.toString())}`,"cyan"),n.query.count>0||n.index.runs>0){console.log("");let l=n.index.runs>0?(n.index.cacheHits/n.index.runs*100).toFixed(1):"0.0";se("Reasoning Efficiency",`${y.bold("Query Count")}: ${y.cyan(n.query.count.toString())}
598
- ${y.bold("Avg Latency")}: ${y.yellow(`${n.query.avgLatencyMs?.toFixed(2)||0}ms`)}
599
- ${y.bold("Cache Hit Rate")}: ${y.green(`${l}%`)}`,"green")}c.length>0&&(console.log(""),console.log(` ${y.bold("Intelligence Landscape")}`),Bn(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),35)),console.log(""),Pe("Liquid Shadow is observing.")})}finally{await Q(e)}}V();Ze();import Hl from"path";async function Br(s){let e=Hl.resolve(s);try{await Y(async()=>{let t=O.getInstance(e),n=Wt(e),i=Vn(),r=Math.floor(i.uptimeMs/1e3),o=Math.floor(r/60),a=Math.floor(o/60),c=a>0?`${a}h ${o%60}m`:o>0?`${o}m ${r%60}s`:`${r}s`,l=i.index.lastCompletedAt?new Date(i.index.lastCompletedAt).toLocaleString():"Never",p=i.index.lastDurationMs?`${(i.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",u=i.query.avgLatencyMs?`${i.query.avgLatencyMs.toFixed(2)}ms`:"N/A",d=i.query.lastLatencyMs?`${i.query.lastLatencyMs.toFixed(2)}ms`:"N/A",h=i.index.runs>0?(i.index.cacheHits/i.index.runs*100).toFixed(1):"0.0";se("Performance Metrics",`${y.bold("Uptime")}: ${y.cyan(c)}
600
- ${y.bold("Indexed")}: ${Xe(e)?y.green("Yes"):y.red("No")}
601
- ${y.bold("Files")}: ${y.cyan(t.files.getCount().toString())}
602
- ${y.bold("Exports")}: ${y.cyan(t.exports.getCount().toString())}
603
- ${y.bold("Imports")}: ${y.cyan(t.imports.getCount().toString())}
604
- ${y.bold("Last Indexed Commit")}: ${nn(e)?y.yellow(nn(e).substring(0,7)):y.red("None")}
605
- ${y.bold("Git Hooks")}: ${n.installed.length>0?y.green("Installed"):y.yellow("Not Installed")}`,"blue"),console.log(""),se("Index Metrics",`${y.bold("Total Runs")}: ${y.cyan(i.index.runs.toString())}
606
- ${y.bold("Cache Hits")}: ${y.cyan(i.index.cacheHits.toString())}
607
- ${y.bold("Cache Hit Rate")}: ${y.cyan(`${h}%`)}
608
- ${y.bold("Last Duration")}: ${y.yellow(p)}
609
- ${y.bold("Last Completed")}: ${y.yellow(l)}`,"cyan"),i.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${y.bold("Last Index Run Phases:")}`),i.index.lastRunPhases.forEach(m=>{let f=`${(m.durationMs/1e3).toFixed(2)}s`;console.log(` ${y.gray(m.phase.padEnd(20))} ${y.cyan(f)}`)})),console.log(""),se("Query Metrics",`${y.bold("Total Queries")}: ${y.cyan(i.query.count.toString())}
610
- ${y.bold("Avg Latency")}: ${y.yellow(u)}
611
- ${y.bold("Last Latency")}: ${y.yellow(d)}
612
- ${y.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?y.red(i.query.searchHistoryFailures.toString()):y.green("0")}`,"green")})}finally{await Q(e)}}import Up from"path";q();import ra from"path";import zp from"ignore";import oa from"fs";import Jn from"path";var zl=50;function Yn(s,e,t,n){let i={name:Jn.basename(e)||e,type:"directory",path:e,children:[]};return s.forEach(r=>{let a=Jn.relative(e,r.path).split(Jn.sep),c=i;for(let l=0;l<a.length;l++){let p=a[l];if(n!==void 0&&l>=n)return;let u=l===a.length-1;if(n===1&&l===0&&u)return;let d=n!==void 0&&l===n-1&&!u,h=Jn.join(e,...a.slice(0,l+1)),m=c.children?.find(f=>f.name===p);if(!m){if(c.children&&c.children.length>=zl){c.children.find(g=>g.type==="truncated")||c.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}m={name:p,type:u?"file":"directory",path:h,children:u||d?void 0:[],summary:u?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},m.summary&&(t==="structure"||t==="signatures")&&(delete m.summary.chunks,delete m.summary.imports),c.children?.push(m)}c=m}}),i}import Ul from"fast-glob";import qr from"fs";import jl from"ignore";import Vr from"path";var Kn=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],Gr=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],ke={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},ge={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},ls={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},Qn={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function Jr(s,e=[]){let t=jl(),n=Vr.join(s,".gitignore");return qr.existsSync(n)&&t.add(qr.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await Ul(Gr,{cwd:s,absolute:!0,ignore:Kn,stats:!0})).filter(o=>{let a=Vr.relative(s,o.path);return!t.ignores(a)}).map(o=>({path:o.path,mtime:o.stats.mtimeMs}))}import po from"fs";function Yr(s){let e=s.split(`
613
- `),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function te(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 Xn(s,e){return e.slice(0,s).toString("utf8").length}function Kr(s){if(s.toString("utf8").length===s.length)return n=>n;let t=new Map;return n=>{let i=t.get(n);return i===void 0&&(i=s.slice(0,n).toString("utf8").length,t.set(n,i)),i}}function Qr(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 Xr(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 Ge(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 Zr(s){if(!s)return"";let t=s.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
614
- `)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function Zn(s,e,t){let n=s.toLowerCase(),i=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||i.startsWith("use")?"Hook":n.includes("models/")||i.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||i.endsWith("service")||i.endsWith("controller")||i.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||i.endsWith("repository")||i.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function cn(s){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(s)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(s)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(s)||/\.query\s*\(|\.execute\s*\(/i.test(s)&&/db|database|client|pool/i.test(s))&&e.push("Database"),(/\bfs\./i.test(s)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(s)||/import\s+.*\bfs\b/.test(s))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(s)||/\bdocument\.cookie\b/.test(s))&&e.push("Browser Storage"),e}function Ce(s,e){if(!s)return"";let t=s.trimStart();for(;/^\/\*[\s\S]*?\*\//.test(t);)t=t.replace(/^\/\*[\s\S]*?\*\/\s*/,"");for(;/^\/\/[^\n]*\n/.test(t);)t=t.replace(/^\/\/[^\n]*\n\s*/,"");if(t=t.replace(/^(?:import[^\n]*\n)+/,"").replace(/^(?:export\s+\{[^}]*\}\s+from\s+['"][^'"]+['"];?\s*\n?)+/,"").trim(),e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,i=0,r=t.length;for(let a=0;a<t.length;a++){let c=t[a];if(c==="(")n++;else if(c===")")n--;else if(c==="<")i++;else if(c===">")i--;else if(c==="{"){if(n===0&&i===0){r=a;break}}else if(c===";"&&n===0&&i===0){r=a;break}else if(c==="="&&t[a+1]===">"&&n===0&&i===0){r=a+2;break}}let o=t.substring(0,r).trim();return o.length>500?o.slice(0,497)+"...":o}function eo(s){let e=[];for(let t of s)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join(", ")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function Bl(s,e){for(let t of s){if((t.type==="FunctionDeclaration"||t.type==="ClassDeclaration")&&(t.identifier?.value||t.id?.value)===e)return t.span;if(t.type==="VariableDeclaration"){for(let n of t.declarations)if(n.id?.type==="Identifier"&&n.id.value===e)return n.span||t.span}if((t.type==="TsTypeAliasDeclaration"||t.type==="TsInterfaceDeclaration"||t.type==="TsEnumDeclaration")&&(t.id?.value||t.identifier?.value)===e)return t.span;if(t.type==="ExportDeclaration"){let n=t.declaration;if(!n)continue;if((n.type==="FunctionDeclaration"||n.type==="ClassDeclaration")&&(n.identifier?.value||n.id?.value)===e)return n.span||t.span;if(n.type==="VariableDeclaration"){for(let i of n.declarations)if(i.id?.type==="Identifier"&&i.id.value===e)return i.span||n.span||t.span}}}return null}function to(s,e,t,n,i,r,o,a,c){let l=c??(u=>Xn(u,t)),p=[];for(let u of s){if(u.type==="ExportDeclaration"){let d=u.declaration,h=d.type,m="";h==="VariableDeclaration"?m=d.declarations.map(x=>x.id.value).join("",""):m=d.id?.value||d.identifier?.value||"anonymous";let f=l(u.span.start-e),_=l(u.span.end-e),g=Ge(f,r,n),b=a(u.span),w=[];if(u.type==="ExportDeclaration"&&(h==="ClassDeclaration"||h==="ClassExpression")){let x=d.body||[];for(let R of x)if(R.type==="ClassMethod"||R.type==="ClassProperty"){let k=R.key.value;if(!k)continue;let D=l(R.span.start-e),U=l(R.span.end-e),P=a(R.span),E=Ge(D,r,n);w.push({name:k,kind:R.type,signature:Ce(P,R.type),line:te(D,i),endLine:te(U,i),doc:E,classification:R.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(h==="FunctionDeclaration"&&d.body?.type==="BlockStatement")w=ps(d.body.stmts,e,t,n,i,r,a,l);else if(h==="VariableDeclaration"){for(let x of d.declarations)if(x.init&&(x.init.type==="ArrowFunctionExpression"||x.init.type==="FunctionExpression")&&x.init.body?.type==="BlockStatement"){w=ps(x.init.body.stmts,e,t,n,i,r,a,l);break}}p.push({name:m,kind:h,signature:Ce(b,h),line:te(f,i),endLine:te(_,i),doc:g,classification:Zn(o,m,h),capabilities:JSON.stringify(cn(b)),members:w})}if(u.type==="ExportNamedDeclaration"){for(let d of u.specifiers)if(d.type==="ExportSpecifier"){let h=d.orig.value,m=d.exported?.value||h,_=Bl(s,h)||u.span,g=l(_.start-e),b=l(_.end-e),w=Ge(g,r,n);p.push({name:m,kind:"ExportSpecifier",signature:`export { ${h} }`,line:te(g,i),endLine:te(b,i),doc:w,classification:"Export mapping",capabilities:"[]"})}}if(u.type==="ExportDefaultDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=Ge(d,r,n),f=a(u.span),_=[];if(u.decl.type==="ClassExpression"||u.decl.type==="ClassDeclaration"){let g=u.decl.body||[];for(let b of g)if(b.type==="ClassMethod"||b.type==="ClassProperty"){let w=b.key.value;if(!w)continue;let x=l(b.span.start-e),R=l(b.span.end-e),k=a(b.span),D=Ge(x,r,n);_.push({name:w,kind:b.type,signature:Ce(k,b.type),line:te(x,i),endLine:te(R,i),doc:D,classification:b.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(u.decl.type==="FunctionExpression"||u.decl.type==="FunctionDeclaration"||u.decl.type==="ArrowFunctionExpression")&&u.decl.body?.type==="BlockStatement"&&(_=ps(u.decl.body.stmts,e,t,n,i,r,a,l));p.push({name:"default",kind:"DefaultExport",signature:Ce(f,"DefaultExport"),line:te(d,i),endLine:te(h,i),doc:m,classification:"Default Export",capabilities:JSON.stringify(cn(f)),members:_})}if(u.type==="ExportAllDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=u.source.value,f=Ge(d,r,n);p.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${m}"`,line:te(d,i),endLine:te(h,i),doc:f,classification:"Re-export",capabilities:"[]"})}}return p}function ps(s,e,t,n,i,r,o,a){let c=[];for(let l of s){if(l.type==="VariableDeclaration")for(let p of l.declarations){let u=[],d=m=>{if(m.type==="Identifier")u.push({name:m.value,span:m.span});else if(m.type==="ArrayPattern")for(let f of m.elements)f&&d(f);else if(m.type==="ObjectPattern")for(let f of m.properties)f.type==="AssignmentPatternProperty"?u.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&d(f.value)};d(p.id);let h=p.init&&(p.init.type==="ArrowFunctionExpression"||p.init.type==="FunctionExpression");for(let m of u){let f=h?p.init.span||p.span||m.span:p.span||m.span,_=h?p.init.type:"VariableDeclaration",g=h?"Internal Function":"Internal Variable",b=a(f.start-e),w=a(f.end-e),x=o(f),R=Ge(b,r,n);c.push({name:m.name,kind:_,signature:Ce(x,_),line:te(b,i),endLine:te(w,i),doc:R,classification:g,capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let p=l.identifier?.value||l.ident?.value||"anonymous",u=a(l.span.start-e),d=a(l.span.end-e),h=o(l.span),m=Ge(u,r,n);c.push({name:p,kind:"FunctionDeclaration",signature:Ce(h,"FunctionDeclaration"),line:te(u,i),endLine:te(d,i),doc:m,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let p of l.argument.properties){let u="",d=p.span||p.key?.span||p.ident?.span;if(p.type==="KeyValueProperty"){let h=p.key;u=h?.value||h?.raw||(h?.type==="Identifier"?h.value:"")}else p.type==="MethodProperty"?u=p.key?.value||p.key?.raw||"":p.type==="ShorthandProperty"?u=p.ident?.value||"":p.type==="Identifier"&&(u=p.value||"");if(u&&d){let h=a(d.start-e),m=a(d.end-e),f=o(d),_=Ge(h,r,n);c.push({name:u,kind:"ReturnProperty",signature:Ce(f,"ReturnProperty"),line:te(h,i),endLine:te(m,i),doc:_,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let p=l.expression;if(p.callee.type==="MemberExpression"&&(p.callee.property?.value==="on"||p.callee.property?.value==="once")){let u=p.arguments[0]?.expression?.value,d=p.arguments[1]?.expression;if(u&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let h=a(d.span.start-e),m=a(d.span.end-e),f=o(d.span);c.push({name:`on:${u}`,kind:d.type,signature:Ce(f,d.type),line:te(h,i),endLine:te(m,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(p.callee.type==="Identifier"&&p.callee.value==="addRoute"&&p.arguments.length>=3){let u=p.arguments[2].expression;if(u.type==="StringLiteral"){let d=u.value,h=a(p.span.start-e),m=a(p.span.end-e),f=o(p.span);c.push({name:d,kind:"HTTP Route",signature:Ce(f,"HTTP Route"),line:te(h,i),endLine:te(m,i),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:d})})}}}}return c}function no(s,e,t,n,i,r){let o=r??(l=>Xn(l,t)),a=[];function c(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let p=Gl(l);if(p){let u=o(l.span.start-e);a.push({...p,line:te(u,n),snippet:i(l.span)})}}for(let p of Object.keys(l)){if(p==="span")continue;let u=l[p];Array.isArray(u)?u.forEach(c):typeof u=="object"&&c(u)}}}return s.forEach(c),a}function Gl(s){let{callee:e,arguments:t}=s;if(!t||t.length===0)return null;if(e.type==="Identifier"&&e.value,e.type==="Identifier"&&e.value==="addRoute"&&t.length>=3){let n=t[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value,o=e.object.type==="Identifier"?e.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(o))return{type:"api_route",name:r,direction:"produce"};if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function ln(s){let{classification:e,capabilities:t,exports:n,fileName:i}=s,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(m=>r[m]).filter(Boolean).join(" and "),c={Component:(m,f)=>{let _=f.find(b=>b.kind==="FunctionDeclaration"||b.kind==="ClassDeclaration")?.name,g=_?`React component: ${_}`:"React UI component";return m?`${g} with ${m}`:g},Hook:(m,f)=>{let _=f.find(b=>b.name.startsWith("use"))?.name,g=_?`Custom React hook: ${_}`:"Custom React hook";return m?`${g} for ${m}`:g},Service:(m,f)=>{let g=`Service layer: ${f[0]?.name||"Service"}`;return m?`${g} handling ${m}`:g},Repository:(m,f)=>`Data repository: ${f[0]?.name||"Repository"} for ${m||"data access"}`,"Type Definition":(m,f)=>`Type definitions: ${f.slice(0,3).map(g=>g.name).join("")}${f.length>3?"...":""}`,Model:(m,f)=>`Data model: ${f[0]?.name||"Model"}`,"HTTP Route":(m,f)=>{let _=f.filter(g=>g.classification==="Service Boundary");return _.length>0?`API endpoints: ${_.slice(0,3).map(g=>g.name).join("")}`:"API route handler"},"Micro IR (PHP)":(m,f)=>{let _=f.some(b=>b.classification==="Service Boundary"),g=f.find(b=>b.kind==="ClassDeclaration")?.name;return _?"PHP controller with API routes":g?`PHP class: ${g}`:"PHP module"},"Micro IR (Python)":(m,f)=>{let _=f.some(b=>b.classification==="Service Boundary"),g=f.find(b=>b.kind==="ClassDeclaration")?.name;return _?"Python API handler with routes":g?`Python class: ${g}`:"Python module"},"Micro IR (Go/TS) ":(m,f)=>{let _=f.some(b=>b.kind==="TypeDeclaration"),g=f.filter(b=>b.kind==="FunctionDeclaration");return _&&g.length>0?`Go package: types and ${g.length} function(s)`:_?"Go package: type definitions":g.length>0?`Go package: ${g[0].name} and ${g.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(m,f)=>{let _=f.find(w=>w.kind==="TraitDeclaration")?.name,g=f.find(w=>w.kind==="StructDeclaration")?.name,b=f.filter(w=>w.kind==="FunctionDeclaration");return _?m.includes("Rust trait")?`Rust module: trait ${_}`:`Rust module: ${_}`:g?`Rust module: struct ${g}`:b.length>0?`Rust module: ${b.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return i?`Module: ${i}`:"Module with no exports";let l=n.filter(m=>m.kind==="FunctionDeclaration"),p=n.filter(m=>m.kind==="ClassDeclaration"),u=n.filter(m=>m.kind==="TsInterfaceDeclaration"||m.kind==="TsTypeAliasDeclaration"),d=[];if(p.length>0&&d.push(`Class: ${p[0].name}`),l.length>0){let m=l.slice(0,2).map(f=>f.name).join("");d.push(`Functions: ${m}`)}u.length>0&&d.push(`Types: ${u.length}`);let h=d.length>0?d.join(" | "):`Module with ${n.length} export(s)`;return o?`${h} \u2014 ${o}`:h}function io(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&oe(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&oe(n,e);for(let i in n){if(i==="span"||i==="comments"||i==="interpreter")continue;let r=n[i];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return s.forEach(n=>t(n)),Array.from(e)}function oe(s,e){if(s){if(s.type==="TsTypeAnnotation"){oe(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&so(s.typeName,e),s.typeParams&&oe(s.typeParams,e)),s.type==="TsArrayType"&&oe(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>oe(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>oe(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>oe(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>oe(t.typeAnnotation,e)),s.typeAnnotation&&oe(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&oe(t.constraint,e),t.default&&oe(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>oe(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&oe(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(oe(s.objectType,e),oe(s.indexType,e)),s.type==="TsConditionalType"&&(oe(s.checkType,e),oe(s.extendsType,e),oe(s.trueType,e),oe(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&oe(t.typeAnnotation,e)})}}function so(s,e){s.type==="TsQualifiedName"?(s.left&&so(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}import uo from"path";import us from"path";q();St();import oo from"path";import ql from"fs";import{fileURLToPath as Vl}from"url";import*as xt from"web-tree-sitter";var Rf=oo.dirname(Vl(import.meta.url)),ro=S.child({module:"parser:tree-sitter"}),ei=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=xt.Parser||xt;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=_e("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!ql.existsSync(t))return ro.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await xt.Language.load(t);return this.languages.set(e,n),n}catch(n){return ro.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
668
+ `}}function go(s){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=s,i=it.join(e,".git","hooks"),r=[],o=[],a=[];if(!re.existsSync(it.join(e,".git")))return a.push("Not a git repository"),{installed:r,skipped:o,errors:a};re.existsSync(i)||re.mkdirSync(i,{recursive:!0});let l=dp();if(!l)return a.push(`Unable to resolve CLI entry at install time. Expected ${Le("dist/entry/cli/index.js")} to exist.`),{installed:r,skipped:o,errors:a};let c=fp(process.execPath,l),p=new Set;if(t&&(p.add("post-merge"),p.add("post-checkout")),n&&p.add("post-commit"),p.has("post-checkout")){let u=mp();u&&(a.push(u),Ot.warn({rotationError:u},"Post-checkout log rotation failed"))}for(let u of p){let d=it.join(i,u),h=c[u];if(!h){a.push(`No template found for hook: ${u}`);continue}try{if(re.existsSync(d)){let m=re.readFileSync(d,"utf-8"),f=Ts(m);if(f&&m===h){re.chmodSync(d,493),o.push(u),Ot.info({hookName:u},"Hook already installed, skipping");continue}if(!f){let b=`${d}.backup-${Date.now()}`;re.copyFileSync(d,b),Ot.info({hookName:u,backupPath:b},"Backed up existing hook")}}re.writeFileSync(d,h,{mode:493}),re.chmodSync(d,493),r.push(u),Ot.info({hookName:u},"Installed git hook")}catch(m){a.push(`Failed to install ${u}: ${m}`),Ot.error({hookName:u,err:m},"Failed to install hook")}}return{installed:r,skipped:o,errors:a}}function yo(s){let e=it.join(s,".git","hooks"),t=[],n=[];if(!re.existsSync(e))return{removed:t,errors:n};for(let i of ho){let r=it.join(e,i);try{if(re.existsSync(r)){let o=re.readFileSync(r,"utf-8");Ts(o)&&(re.unlinkSync(r),t.push(i),Ot.info({hookName:i},"Removed git hook"))}}catch(o){n.push(`Failed to remove ${i}: ${o}`),Ot.error({hookName:i,err:o},"Failed to remove hook")}}return{removed:t,errors:n}}function hp(s,e){let t=it.join(s,".git","hooks"),n=it.join(t,e);if(!re.existsSync(t)||!re.existsSync(n))return"missing";try{let i=re.readFileSync(n,"utf-8");return Ts(i)?(re.statSync(n).mode&73)!==0?"installed":"disabled":"foreign"}catch{return"foreign"}}function en(s){let e=[],t=[],n=[],i=[],r={};for(let a of ho){let l=hp(s,a);r[a]=l,l==="installed"&&e.push(a),l==="missing"&&t.push(a),l==="foreign"&&n.push(a),l==="disabled"&&i.push(a)}let o=[...t,...n,...i];return{installed:e,notInstalled:o,missing:t,foreign:n,disabled:i,statuses:r}}async function ks(s){let e=bo.resolve(s);try{await Z(async()=>{ge("Liquid Shadow Intelligence Dashboard");let t=F.getInstance(e),n=li(),i=en(e),r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),l=t.exports.getKindDistribution(5);if(ue("Operational Core",`${_.bold("State")}: ${ut(e)?_.green("IDENTIFIED (Stable)"):_.red("UNKNOWN (Needs Index)")}
669
+ ${_.bold("Repository")}: ${_.cyan(bo.basename(e))}
670
+ ${_.bold("Infrastructure")}: ${i.installed.length>0?_.green("Git-Hooked"):_.yellow("Standalone")}
671
+ ${_.bold("Last Sync")}: ${a?_.yellow(new Date(a).toLocaleString()):_.red("Never")}`,"blue"),console.log(""),ue("Intelligence Density",`${_.bold("Files Target")}: ${_.cyan(r.toString())}
672
+ ${_.bold("Symbols Mapped")}: ${_.cyan(o.toString())}
673
+ ${_.bold("Graph Edges")}: ${_.cyan(t.imports.getCount().toString())}
674
+ ${_.bold("Hotspots")}: ${_.yellow(l.length.toString())}`,"cyan"),n.query.count>0||n.index.runs>0){console.log("");let c=n.index.runs>0?(n.index.cacheHits/n.index.runs*100).toFixed(1):"0.0";ue("Reasoning Efficiency",`${_.bold("Query Count")}: ${_.cyan(n.query.count.toString())}
675
+ ${_.bold("Avg Latency")}: ${_.yellow(`${n.query.avgLatencyMs?.toFixed(2)||0}ms`)}
676
+ ${_.bold("Cache Hit Rate")}: ${_.green(`${c}%`)}`,"green")}l.length>0&&(console.log(""),console.log(` ${_.bold("Intelligence Landscape")}`),oi(l.map(c=>({label:c.kind,value:c.c,color:"cyan"})),35)),console.log(""),Je("Liquid Shadow is observing.")})}finally{await ne(e)}}Y();dt();import gp from"path";async function _o(s){let e=gp.resolve(s);try{await Z(async()=>{let t=F.getInstance(e),n=en(e),i=li(),r=Math.floor(i.uptimeMs/1e3),o=Math.floor(r/60),a=Math.floor(o/60),l=a>0?`${a}h ${o%60}m`:o>0?`${o}m ${r%60}s`:`${r}s`,c=i.index.lastCompletedAt?new Date(i.index.lastCompletedAt).toLocaleString():"Never",p=i.index.lastDurationMs?`${(i.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",u=i.query.avgLatencyMs?`${i.query.avgLatencyMs.toFixed(2)}ms`:"N/A",d=i.query.lastLatencyMs?`${i.query.lastLatencyMs.toFixed(2)}ms`:"N/A",h=i.index.runs>0?(i.index.cacheHits/i.index.runs*100).toFixed(1):"0.0";ue("Performance Metrics",`${_.bold("Uptime")}: ${_.cyan(l)}
677
+ ${_.bold("Indexed")}: ${ut(e)?_.green("Yes"):_.red("No")}
678
+ ${_.bold("Files")}: ${_.cyan(t.files.getCount().toString())}
679
+ ${_.bold("Exports")}: ${_.cyan(t.exports.getCount().toString())}
680
+ ${_.bold("Imports")}: ${_.cyan(t.imports.getCount().toString())}
681
+ ${_.bold("Last Indexed Commit")}: ${yn(e)?_.yellow(yn(e).substring(0,7)):_.red("None")}
682
+ ${_.bold("Git Hooks")}: ${n.installed.length>0?_.green("Installed"):_.yellow("Not Installed")}`,"blue"),console.log(""),ue("Index Metrics",`${_.bold("Total Runs")}: ${_.cyan(i.index.runs.toString())}
683
+ ${_.bold("Cache Hits")}: ${_.cyan(i.index.cacheHits.toString())}
684
+ ${_.bold("Cache Hit Rate")}: ${_.cyan(`${h}%`)}
685
+ ${_.bold("Last Duration")}: ${_.yellow(p)}
686
+ ${_.bold("Last Completed")}: ${_.yellow(c)}`,"cyan"),i.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${_.bold("Last Index Run Phases:")}`),i.index.lastRunPhases.forEach(m=>{let f=`${(m.durationMs/1e3).toFixed(2)}s`;console.log(` ${_.gray(m.phase.padEnd(20))} ${_.cyan(f)}`)})),console.log(""),ue("Query Metrics",`${_.bold("Total Queries")}: ${_.cyan(i.query.count.toString())}
687
+ ${_.bold("Avg Latency")}: ${_.yellow(u)}
688
+ ${_.bold("Last Latency")}: ${_.yellow(d)}
689
+ ${_.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?_.red(i.query.searchHistoryFailures.toString()):_.green("0")}`,"green")})}finally{await ne(e)}}import bu from"path";G();import Aa from"path";import yu from"ignore";import Na from"fs";import st from"path";var yp=50;function pi(s,e,t,n){let i={name:st.basename(e)||e,type:"directory",path:e,children:[]};return[...s].sort((o,a)=>{let l=st.relative(e,o.path),c=st.relative(e,a.path),p=l.includes(st.sep),u=c.includes(st.sep);if(p!==u)return p?-1:1;let d=l.split(st.sep).length,h=c.split(st.sep).length;return d!==h?d-h:l.localeCompare(c)}).forEach(o=>{let l=st.relative(e,o.path).split(st.sep),c=i;for(let p=0;p<l.length;p++){let u=l[p];if(n!==void 0&&p>=n)return;let d=p===l.length-1;if(n===1&&p===0&&d)return;let h=n!==void 0&&p===n-1&&!d,m=st.join(e,...l.slice(0,p+1)),f=c.children?.find(b=>b.name===u);if(!f){if(c.children&&c.children.length>=yp){c.children.find(y=>y.type==="truncated")||c.children.push({name:"... (truncated)",type:"truncated",path:"",children:void 0});return}f={name:u,type:d?"file":"directory",path:m,children:d||h?void 0:[],summary:d?{classification:o.classification,summaryText:o.summary,exports:o.exports,imports:o.imports,chunks:o.chunks}:void 0},f.summary&&(t==="structure"||t==="signatures")&&(delete f.summary.chunks,delete f.summary.imports),c.children?.push(f)}c=f}}),i}import bp from"fast-glob";import So from"fs";import _p from"ignore";import xo from"path";var ui=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],Eo=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],We={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},ve={FILTERED_QUERY_LIMIT_MULTIPLIER:3,SCORE_BASE:1e3,EXACT_MATCH_BONUS:500,RECENT_FILE_BOOST:80,OLDER_FILE_BOOST:30,RECENT_FILE_THRESHOLD_DAYS:7,OLDER_FILE_THRESHOLD_DAYS:30,FUZZY_MATCH_LIMIT:30,ENABLE_LEXICAL_SCORING:process.env.ENABLE_LEXICAL_SCORING!=="false",LEXICAL_WEIGHT:parseFloat(process.env.LEXICAL_WEIGHT??String(.4)),GRAVITY_STRUCTURAL_WEIGHT:.5},Cs={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},di={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function wo(s,e=[]){let t=_p(),n=xo.join(s,".gitignore");return So.existsSync(n)&&t.add(So.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await bp(Eo,{cwd:s,absolute:!0,ignore:ui,stats:!0})).filter(o=>{let a=xo.relative(s,o.path);return!t.ignores(a)}).map(o=>({path:o.path,mtime:o.stats.mtimeMs}))}import Wo from"fs";function vo(s){let e=s.split(`
690
+ `),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function ie(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 mi(s,e){return e.slice(0,s).toString("utf8").length}function Ro(s){if(s.toString("utf8").length===s.length)return n=>n;let t=new Map;return n=>{let i=t.get(n);return i===void 0&&(i=s.slice(0,n).toString("utf8").length,t.set(n,i)),i}}function To(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 ko(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 Ye(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 Co(s){if(!s)return"";let t=s.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
691
+ `)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function fi(s,e,t){let n=s.toLowerCase(),i=e.toLowerCase(),r=n.split("/").pop()||n;return t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"||t==="TsEnumDeclaration"?"Type Definition":r.startsWith("use")||i.startsWith("use")?"Hook":n.includes("components/")||n.endsWith(".tsx")?"Component":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":"Other"}function tn(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 Me(s,e){if(!s)return"";let t=s.trimStart();for(;/^\/\*[\s\S]*?\*\//.test(t);)t=t.replace(/^\/\*[\s\S]*?\*\/\s*/,"");for(;/^\/\/[^\n]*\n/.test(t);)t=t.replace(/^\/\/[^\n]*\n\s*/,"");if(t=t.replace(/^(?:import[^\n]*\n)+/,"").replace(/^(?:export\s+\{[^}]*\}\s+from\s+['"][^'"]+['"];?\s*\n?)+/,"").trim(),e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,i=0,r=t.length;for(let a=0;a<t.length;a++){let l=t[a];if(l==="(")n++;else if(l===")")n--;else if(l==="<")i++;else if(l===">")i--;else if(l==="{"){if(n===0&&i===0){r=a;break}}else if(l===";"&&n===0&&i===0){r=a;break}else if(l==="="&&t[a+1]===">"&&n===0&&i===0){r=a+2;break}}let o=t.substring(0,r).trim();return o.length>500?o.slice(0,497)+"...":o}function Io(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 Ep(s,e){for(let t of s){if((t.type==="FunctionDeclaration"||t.type==="ClassDeclaration")&&(t.identifier?.value||t.id?.value)===e)return t.span;if(t.type==="VariableDeclaration"){for(let n of t.declarations)if(n.id?.type==="Identifier"&&n.id.value===e)return n.span||t.span}if((t.type==="TsTypeAliasDeclaration"||t.type==="TsInterfaceDeclaration"||t.type==="TsEnumDeclaration")&&(t.id?.value||t.identifier?.value)===e)return t.span;if(t.type==="ExportDeclaration"){let n=t.declaration;if(!n)continue;if((n.type==="FunctionDeclaration"||n.type==="ClassDeclaration")&&(n.identifier?.value||n.id?.value)===e)return n.span||t.span;if(n.type==="VariableDeclaration"){for(let i of n.declarations)if(i.id?.type==="Identifier"&&i.id.value===e)return i.span||n.span||t.span}}}return null}function Lo(s,e,t,n,i,r,o,a,l){let c=l??(u=>mi(u,t)),p=[];for(let u of s){if(u.type==="ExportDeclaration"){let d=u.declaration,h=d.type,m="";h==="VariableDeclaration"?m=d.declarations.map(k=>k.id.value).join("",""):m=d.id?.value||d.identifier?.value||"anonymous";let f=c(u.span.start-e),b=c(u.span.end-e),g=Ye(f,r,n),y=a(u.span),E=[];if(u.type==="ExportDeclaration"&&(h==="ClassDeclaration"||h==="ClassExpression")){let k=d.body||[];for(let R of k)if(R.type==="ClassMethod"||R.type==="ClassProperty"){let w=R.key.value;if(!w)continue;let N=c(R.span.start-e),U=c(R.span.end-e),H=a(R.span),C=Ye(N,r,n);E.push({name:w,kind:R.type,signature:Me(H,R.type),line:ie(N,i),endLine:ie(U,i),doc:C,classification:R.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(h==="FunctionDeclaration"&&d.body?.type==="BlockStatement")E=Is(d.body.stmts,e,t,n,i,r,a,c);else if(h==="VariableDeclaration"){for(let k of d.declarations)if(k.init&&(k.init.type==="ArrowFunctionExpression"||k.init.type==="FunctionExpression")&&k.init.body?.type==="BlockStatement"){E=Is(k.init.body.stmts,e,t,n,i,r,a,c);break}}p.push({name:m,kind:h,signature:Me(y,h),line:ie(f,i),endLine:ie(b,i),doc:g,classification:fi(o,m,h),capabilities:JSON.stringify(tn(y)),members:E})}if(u.type==="ExportNamedDeclaration"){for(let d of u.specifiers)if(d.type==="ExportSpecifier"){let h=d.orig.value,m=d.exported?.value||h,b=Ep(s,h)||u.span,g=c(b.start-e),y=c(b.end-e),E=Ye(g,r,n);p.push({name:m,kind:"ExportSpecifier",signature:`export { ${h} }`,line:ie(g,i),endLine:ie(y,i),doc:E,classification:"Export mapping",capabilities:"[]"})}}if(u.type==="ExportDefaultDeclaration"){let d=c(u.span.start-e),h=c(u.span.end-e),m=Ye(d,r,n),f=a(u.span),b=[];if(u.decl.type==="ClassExpression"||u.decl.type==="ClassDeclaration"){let g=u.decl.body||[];for(let y of g)if(y.type==="ClassMethod"||y.type==="ClassProperty"){let E=y.key.value;if(!E)continue;let k=c(y.span.start-e),R=c(y.span.end-e),w=a(y.span),N=Ye(k,r,n);b.push({name:E,kind:y.type,signature:Me(w,y.type),line:ie(k,i),endLine:ie(R,i),doc:N,classification:y.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(u.decl.type==="FunctionExpression"||u.decl.type==="FunctionDeclaration"||u.decl.type==="ArrowFunctionExpression")&&u.decl.body?.type==="BlockStatement"&&(b=Is(u.decl.body.stmts,e,t,n,i,r,a,c));p.push({name:"default",kind:"DefaultExport",signature:Me(f,"DefaultExport"),line:ie(d,i),endLine:ie(h,i),doc:m,classification:"Default Export",capabilities:JSON.stringify(tn(f)),members:b})}if(u.type==="ExportDefaultExpression"){let d=c(u.span.start-e),h=c(u.span.end-e),m=Ye(d,r,n),f=a(u.span),b=u.expression,g=b?.type==="Identifier"?b.value:b?.identifier?.value||b?.id?.value||void 0;p.push({name:"default",kind:"DefaultExport",signature:Me(f,"DefaultExport"),line:ie(d,i),endLine:ie(h,i),doc:m,classification:"Default Export",capabilities:JSON.stringify(tn(f)),members:[],defaultTarget:g})}if(u.type==="ExportAllDeclaration"){let d=c(u.span.start-e),h=c(u.span.end-e),m=u.source.value,f=Ye(d,r,n);p.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${m}"`,line:ie(d,i),endLine:ie(h,i),doc:f,classification:"Re-export",capabilities:"[]"})}}return p}function Is(s,e,t,n,i,r,o,a){let l=[];for(let c of s){if(c.type==="VariableDeclaration")for(let p of c.declarations){let u=[],d=m=>{if(m.type==="Identifier")u.push({name:m.value,span:m.span});else if(m.type==="ArrayPattern")for(let f of m.elements)f&&d(f);else if(m.type==="ObjectPattern")for(let f of m.properties)f.type==="AssignmentPatternProperty"?u.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&d(f.value)};d(p.id);let h=p.init&&(p.init.type==="ArrowFunctionExpression"||p.init.type==="FunctionExpression");for(let m of u){let f=h?p.init.span||p.span||m.span:p.span||m.span,b=h?p.init.type:"VariableDeclaration",g=h?"Internal Function":"Internal Variable",y=a(f.start-e),E=a(f.end-e),k=o(f),R=Ye(y,r,n);l.push({name:m.name,kind:b,signature:Me(k,b),line:ie(y,i),endLine:ie(E,i),doc:R,classification:g,capabilities:"[]"})}}if(c.type==="FunctionDeclaration"){let p=c.identifier?.value||c.ident?.value||"anonymous",u=a(c.span.start-e),d=a(c.span.end-e),h=o(c.span),m=Ye(u,r,n);l.push({name:p,kind:"FunctionDeclaration",signature:Me(h,"FunctionDeclaration"),line:ie(u,i),endLine:ie(d,i),doc:m,classification:"Internal Function",capabilities:"[]"})}if(c.type==="ReturnStatement"&&c.argument?.type==="ObjectExpression")for(let p of c.argument.properties){let u="",d=p.span||p.key?.span||p.ident?.span;if(p.type==="KeyValueProperty"){let h=p.key;u=h?.value||h?.raw||(h?.type==="Identifier"?h.value:"")}else p.type==="MethodProperty"?u=p.key?.value||p.key?.raw||"":p.type==="ShorthandProperty"?u=p.ident?.value||"":p.type==="Identifier"&&(u=p.value||"");if(u&&d){let h=a(d.start-e),m=a(d.end-e),f=o(d),b=Ye(h,r,n);l.push({name:u,kind:"ReturnProperty",signature:Me(f,"ReturnProperty"),line:ie(h,i),endLine:ie(m,i),doc:b,classification:"Return Member",capabilities:"[]"})}}if(c.type==="ExpressionStatement"&&c.expression.type==="CallExpression"){let p=c.expression;if(p.callee.type==="MemberExpression"&&(p.callee.property?.value==="on"||p.callee.property?.value==="once")){let u=p.arguments[0]?.expression?.value,d=p.arguments[1]?.expression;if(u&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let h=a(d.span.start-e),m=a(d.span.end-e),f=o(d.span);l.push({name:`on:${u}`,kind:d.type,signature:Me(f,d.type),line:ie(h,i),endLine:ie(m,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(p.callee.type==="Identifier"&&p.callee.value==="addRoute"&&p.arguments.length>=3){let u=p.arguments[2].expression;if(u.type==="StringLiteral"){let d=u.value,h=a(p.span.start-e),m=a(p.span.end-e),f=o(p.span);l.push({name:d,kind:"HTTP Route",signature:Me(f,"HTTP Route"),line:ie(h,i),endLine:ie(m,i),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:d})})}}}}return l}function Mo(s,e,t,n,i,r){let o=r??(c=>mi(c,t)),a=[];function l(c){if(!(!c||typeof c!="object")){if(c.type==="CallExpression"){let p=Sp(c);if(p){let u=o(c.span.start-e);a.push({...p,line:ie(u,n),snippet:i(c.span)})}}for(let p of Object.keys(c)){if(p==="span")continue;let u=c[p];Array.isArray(u)?u.forEach(l):typeof u=="object"&&l(u)}}}return s.forEach(l),a}function Sp(s){let{callee:e,arguments:t}=s;if(!t||t.length===0)return null;if(e.type==="Identifier"&&e.value,e.type==="Identifier"&&e.value==="addRoute"&&t.length>=3){let n=t[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value,o=e.object.type==="Identifier"?e.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(o))return{type:"api_route",name:r,direction:"produce"};if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function xn(s){let{classification:e,capabilities:t,exports:n,fileName:i}=s,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(m=>r[m]).filter(Boolean).join(" and "),l={Component:(m,f)=>{let b=f.find(y=>y.kind==="FunctionDeclaration"||y.kind==="ClassDeclaration")?.name,g=b?`React component: ${b}`:"React UI component";return m?`${g} with ${m}`:g},Hook:(m,f)=>{let b=f.find(y=>y.name.startsWith("use"))?.name,g=b?`Custom React hook: ${b}`:"Custom React hook";return m?`${g} for ${m}`:g},Service:(m,f)=>{let g=`Service layer: ${f[0]?.name||"Service"}`;return m?`${g} handling ${m}`:g},Repository:(m,f)=>`Data repository: ${f[0]?.name||"Repository"} for ${m||"data access"}`,"Type Definition":(m,f)=>`Type definitions: ${f.slice(0,3).map(g=>g.name).join("")}${f.length>3?"...":""}`,Model:(m,f)=>`Data model: ${f[0]?.name||"Model"}`,"HTTP Route":(m,f)=>{let b=f.filter(g=>g.classification==="Service Boundary");return b.length>0?`API endpoints: ${b.slice(0,3).map(g=>g.name).join("")}`:"API route handler"},"Micro IR (PHP)":(m,f)=>{let b=f.some(y=>y.classification==="Service Boundary"),g=f.find(y=>y.kind==="ClassDeclaration")?.name;return b?"PHP controller with API routes":g?`PHP class: ${g}`:"PHP module"},"Micro IR (Python)":(m,f)=>{let b=f.some(y=>y.classification==="Service Boundary"),g=f.find(y=>y.kind==="ClassDeclaration")?.name;return b?"Python API handler with routes":g?`Python class: ${g}`:"Python module"},"Micro IR (Go/TS) ":(m,f)=>{let b=f.some(y=>y.kind==="TypeDeclaration"),g=f.filter(y=>y.kind==="FunctionDeclaration");return b&&g.length>0?`Go package: types and ${g.length} function(s)`:b?"Go package: type definitions":g.length>0?`Go package: ${g[0].name} and ${g.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(m,f)=>{let b=f.find(E=>E.kind==="TraitDeclaration")?.name,g=f.find(E=>E.kind==="StructDeclaration")?.name,y=f.filter(E=>E.kind==="FunctionDeclaration");return b?m.includes("Rust trait")?`Rust module: trait ${b}`:`Rust module: ${b}`:g?`Rust module: struct ${g}`:y.length>0?`Rust module: ${y.length} function(s)`:"Rust module"}}[e];if(l)return l(o,n);if(n.length===0)return i?`Module: ${i}`:"Module with no exports";let c=n.filter(m=>m.kind==="FunctionDeclaration"),p=n.filter(m=>m.kind==="ClassDeclaration"),u=n.filter(m=>m.kind==="TsInterfaceDeclaration"||m.kind==="TsTypeAliasDeclaration"),d=[];if(p.length>0&&d.push(`Class: ${p[0].name}`),c.length>0){let m=c.slice(0,2).map(f=>f.name).join("");d.push(`Functions: ${m}`)}u.length>0&&d.push(`Types: ${u.length}`);let h=d.length>0?d.join(" | "):`Module with ${n.length} export(s)`;return o?`${h} \u2014 ${o}`:h}function $o(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&de(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&de(n,e);for(let i in n){if(i==="span"||i==="comments"||i==="interpreter")continue;let r=n[i];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return s.forEach(n=>t(n)),Array.from(e)}function de(s,e){if(s){if(s.type==="TsTypeAnnotation"){de(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&Ao(s.typeName,e),s.typeParams&&de(s.typeParams,e)),s.type==="TsArrayType"&&de(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>de(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>de(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>de(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>de(t.typeAnnotation,e)),s.typeAnnotation&&de(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&de(t.constraint,e),t.default&&de(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>de(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&de(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(de(s.objectType,e),de(s.indexType,e)),s.type==="TsConditionalType"&&(de(s.checkType,e),de(s.extendsType,e),de(s.trueType,e),de(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&de(t.typeAnnotation,e)})}}function Ao(s,e){s.type==="TsQualifiedName"?(s.left&&Ao(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}import Ho from"path";import Ls from"path";G();Dt();import Po from"path";import xp from"fs";import{fileURLToPath as wp}from"url";import*as Ft from"web-tree-sitter";var pg=Po.dirname(wp(import.meta.url)),No=x.child({module:"parser:tree-sitter"}),hi=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=Ft.Parser||Ft;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=Le("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!xp.existsSync(t))return No.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await Ft.Language.load(t);return this.languages.set(e,n),n}catch(n){return No.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
615
692
  (function_definition name: (name) @name) @func
616
693
  (class_declaration name: (name) @name) @class
617
694
  (interface_declaration name: (name) @name) @interface
@@ -635,55 +712,58 @@ ${y.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?y.red(i.
635
712
  (trait_item name: (_type_identifier) @name) @trait
636
713
  (type_item name: (_type_identifier) @name) @type
637
714
  (use_declaration argument: (_) @name) @import
638
- `;default:return""}}mapKind(e,t){if(e==="import")return"ImportDeclaration";if(t===".php"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration";if(e==="interface")return"InterfaceDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="method")return"MethodDeclaration"}if(t===".py"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration"}if(t===".go"){if(e==="func")return"FunctionDeclaration";if(e==="type")return"TypeDeclaration"}if(t===".rs"){if(e==="func")return"FunctionDeclaration";if(e==="struct")return"StructDeclaration";if(e==="enum")return"EnumDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(e){return e==="import"?"Dependency":e==="func"||e==="method"?"Function":e==="class"||e==="interface"||e==="trait"||e==="struct"||e==="enum"||e==="type"?"Class":"Other"}async parse(e,t){await this.ensureInitialized();let n=oo.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(`
639
- `),a=this.getQueries(n);if(!a)return[];let l=new xt.Query(i,a).matches(r.rootNode),p=[];for(let u of l){let d=u.captures.find(f=>f.name==="name")?.node,h=u.captures[0].node,m=u.captures[0].name;if(d){let f=h.startPosition.row+1,_=h.endPosition.row+1,g=o[h.startPosition.row].trim();p.push({name:d.text,kind:this.mapKind(m,n),classification:this.mapClassification(m),signature:g,line:f,endLine:_,doc:"",capabilities:"{}"})}}return p}};var ti=class{parse(e,t=!1){let n=[],i=[],r=e.split(`
640
- `),o="",a="",c=0,l=0,p=-1,u=-1,d=[],h=[],m=!1,f=t?"api":"",_="",g=/^namespace\s+([a-zA-Z0-9_\\]+);/,b=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,w=/^interface\s+([a-zA-Z0-9_]+)/,x=/^trait\s+([a-zA-Z0-9_]+)/,R=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,k=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,D=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,U=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,P=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let E=0;E<r.length;E++){let T=r[E].trim();if(!T)continue;let I=(T.match(/{/g)||[]).length,M=(T.match(/}/g)||[]).length,N=l;if(l+=I-M,a&&l<=u){let z=n.find(G=>G.name===a&&G.line===c);z&&(z.endLine=E+1),a="",u=-1}if(o&&l<=p){let z=n.find(G=>G.name===o&&(G.kind==="ClassDeclaration"||G.kind==="TraitDeclaration"||G.kind==="InterfaceDeclaration"));z&&(z.endLine=E+1),o="",p=-1}let $=T.match(P);if($&&(f=$[1]),T.includes("});")&&(f=""),T.startsWith("/**")){m=!0,h=[];continue}if(m){T.endsWith("*/")?m=!1:h.push(T.replace(/^\*\s?/,""));continue}let W=T.match(D);if(W){d.push(W[1]);continue}let L=T.match(g);if(L){_=L[1]||"",d=[],h=[];continue}let A=T.match(b);if(A){o=A[1],p=l-I;let z={attributes:d};_&&(z.namespace=_),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:E+1,endLine:E+1,doc:h.join(`
641
- `).trim(),capabilities:JSON.stringify(z),members:[]}),d=[],h=[];continue}let H=T.match(w);if(H){let z=H[1];o=z,p=l-I,n.push({name:z,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${z}`,line:E+1,endLine:E+1,doc:h.join(`
642
- `).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let F=T.match(x);if(F){let z=F[1];o=z,p=l-I,n.push({name:z,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${z}`,line:E+1,endLine:E+1,doc:h.join(`
643
- `).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let v=T.match(R);if(v){let z=v[1],G=!!o;a=z,c=E+1,u=l-I;let we=!1,xe={};for(let le of d)le.toLowerCase().includes("route")&&(we=!0,xe={type:"route",method:"GET",path:"/"});let he=h.join(`
644
- `).trim();if(we){let le=xe.path||"/";n.push({name:le,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${z}`,line:E+1,endLine:E+1,doc:he,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${z}`:z,...xe})}),i.push({type:"api_route",name:le,direction:"consume",line:E+1,snippet:T})}n.push({name:z,kind:G?"MethodDeclaration":"FunctionDeclaration",classification:G?"Method":"Function",signature:`${G?o+":: ":""}${z}`,line:E+1,endLine:E+1,doc:he,capabilities:JSON.stringify({attributes:d})}),d=[],h=[];continue}let C=T.match(k);if(C){let z=C[1]||"",G=C[2]||z.split("\\").pop()||"";n.push({name:G,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${z}`,line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:z})}),d=[],h=[];continue}let B=T.match(U);if(B){let z=B[1].toUpperCase(),G=B[2];if(T.includes("Route::")||T.includes("router->")||T.includes("action")||T.includes(",")&&!T.includes("view(")){if(f){let re=f.startsWith("/")?f:`/${f}`,He=G.startsWith("/")?G:`/${G}`;G=(re+He).replace(/\/+/g,"/")}let xe=null,he=T.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(he)xe=`${he[1]}@${he[2]}`;else if(T.includes("::class")){let re=T.match(/([a-zA-Z0-9_]+)::class/);re&&(xe=re[1])}let le=T;!T.endsWith(");")&&E+1<r.length&&(le+=" "+r[E+1].trim(),!le.endsWith(");")&&E+2<r.length&&(le+=" "+r[E+2].trim())),n.push({name:G,kind:"HTTP Route",classification:"Service Boundary",signature:le,line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({type:"route",method:z,path:G,handler:xe})}),i.push({type:"api_route",name:G,direction:"consume",line:E+1,snippet:le,method:z,url:G}),h=[];continue}}let j=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,J=T.match(j);if(J){let z=(J[1]||J[3]).toUpperCase(),G=(J[2]||J[4]).trim();(G.startsWith("'")&&G.endsWith("'")||G.startsWith('"')&&G.endsWith('"'))&&(G=G.substring(1,G.length-1)),i.push({type:"api_route",name:G,direction:"produce",line:E+1,snippet:T,method:z,url:G})}!T.startsWith("#[")&&!T.startsWith("//")&&!T.startsWith("*")&&!m&&(d=[],h=[])}return{nodes:n,events:i}}};var ni=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],i=e.split(`
645
- `),r=[{indent:-1,name:"root",type:"root"}],o=[],a=/^class\s+([a-zA-Z0-9_]+)/,c=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,l=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,p=/^@(.*)/;function u(g){return g.trim().split(/[.(]/)[0]?.trim()||g}function d(g){let b=g.decorators.map(x=>u(x.raw)),w={decorators:g.decorators,decoratorNames:b};return g.async===!0&&(w.async=!0),JSON.stringify(w)}let h=!1,m="",f=[],_=[];for(let g=0;g<i.length;g++){let b=i[g],w=b.trim();if(!w||w.startsWith("#"))continue;let x=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,R=w.match(x);if(R&&(this.currentRoutePrefix=R[2]),h){if(w.endsWith(m)||w.includes(m)){h=!1;let A=w.replace(m,"").trim();A&&f.push(A);let H=r[r.length-1];H.node&&(H.node.doc=f.join(`
646
- `).trim()),f=[]}else f.push(w);continue}let k=b.search(/\S/),D=b.trim(),U=D.match(/^(['"]{3})/);if(U){let A=U[1],H=r[r.length-1];if(H.node&&!H.node.doc){if(D.substring(3).includes(A)){let F=D.replace(new RegExp(A,"g"),"").trim();H.node.doc=F}else{h=!0,m=A;let F=D.substring(3).trim();F&&f.push(F)}continue}}for(;r.length>1&&r[r.length-1].indent>=k;)r.pop();let P=r[r.length-1],E=D.match(p);if(E){o.push({raw:E[1].trim(),line:g+1});continue}let T=D.match(a);if(T){let A=T[1],H={name:A,kind:"ClassDeclaration",classification:"Class",signature:`class ${A}`,line:g+1,endLine:g+1,doc:"",capabilities:d({decorators:o}),members:[]};_.push(H),P.node?(P.node.members||(P.node.members=[]),P.node.members.push(H)):t.push(H),r.push({indent:k,name:A,type:"class",node:H}),o=[];continue}let I=D.match(c);if(I){let A=!!I[1],H=I[1]||I[2],F=P.type==="class",v=!1,C={};for(let G of o)if(G.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){v=!0;let xe=["get","post","put","delete","patch"].find(re=>G.raw.toLowerCase().includes(`.${re}`))?.toUpperCase()||"GET",he=G.raw.match(/['"]([^'"]+)['"]/),le=he?he[1]:"/";if(this.currentRoutePrefix){let re=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,He=le.startsWith("/")?le:`/${le}`;le=re+He}C={type:"route",method:xe,path:le}}if(v){let G=C.path||"",we={name:G||H,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${H}`,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({handler:F?`${P.name}.${H}`:H,async:A,...C})};_.push(we),t.push(we),n.push({type:"api_route",name:G,direction:"consume",line:g+1,snippet:D})}let B=o.some(G=>G.raw==="staticmethod"),j=o.some(G=>G.raw==="classmethod"),J=`${A?"async ":""}${F?(B?"@staticmethod ":j?"@classmethod ":"")+P.name+".":""}${H}`,z={name:H,kind:A&&F?"AsyncMethodDeclaration":A?"AsyncFunctionDeclaration":F?"MethodDeclaration":"FunctionDeclaration",classification:F?B||j?"Static Method":"Method":"Function",signature:J,line:g+1,endLine:g+1,doc:"",capabilities:d({decorators:o,async:A}),members:[]};_.push(z),P.node?(P.node.members||(P.node.members=[]),P.node.members.push(z)):t.push(z),r.push({indent:k,name:H,type:"function",node:z}),o=[];continue}let M=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,N=D.match(M);if(N){let A=N[1].replace(/^\^/,""),H={name:A,kind:"HTTP Route",classification:"Service Boundary",signature:D.trim(),line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:A})};_.push(H),t.push(H),n.push({type:"api_route",name:A,direction:"consume",line:g+1,snippet:D});continue}let $=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,W=D.match($);if(W){let A=W[1].toUpperCase(),H=W[2].trim();(H.startsWith("'")&&H.endsWith("'")||H.startsWith('"')&&H.endsWith('"'))&&(H=H.substring(1,H.length-1)),n.push({type:"api_route",name:H,direction:"produce",line:g+1,snippet:D,method:A,url:H})}let L=D.match(l);if(L){let A=L[1]||L[2],H={name:A,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${A}`,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"import",module:A})};_.push(H),t.push(H),o=[];continue}o=[],P.node&&(P.node.endLine=g+1)}return{nodes:_,events:n}}};function Jl(s,e){let t=0,n=!1;for(let i=e;i<s.length;i++){let r=s[i];for(let o of r)if(o==="{")t++,n=!0;else if(o==="}"&&(t--,n&&t<=0))return i+1;if(!n&&i>e&&/[;}]$/.test(r.trim()))return i+1}return Math.min(s.length,e+41)}var ao=[{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 Yl(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 ii=class{phpParser=new ti;pythonParser=new ni;treeSitterParser=new ei;supports(e){return ao.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=us.extname(e).toLowerCase(),i=[],r=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let l=this.pythonParser.parse(t);i=l.nodes,r=l.events}else if(n===".php"){let l=e.toLowerCase().endsWith("api.php"),p=this.phpParser.parse(t,l);i=p.nodes,r=p.events}else try{i=await this.treeSitterParser.parse(e,t)}catch{}if(i.length>0){let l=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",p=i.filter(m=>m.classification!=="Dependency"),u=i.filter(m=>m.classification==="Dependency"),d=Yl(n,i),h=ln({classification:l,capabilities:d,exports:p.map(m=>({name:m.name,kind:m.kind,classification:m.classification})),fileName:us.basename(e)});return{exports:p,imports:u.map(m=>({module:m.name,name:m.name,kind:m.kind,classification:m.classification})),events:r,classification:l,summary:h||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=ao.find(l=>l.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};let a=t.split(`
647
- `);for(let l of o.rules){l.regex.lastIndex=0;let p;for(;(p=l.regex.exec(t))!==null;){let u=l.onMatch(p),d=t.substring(0,p.index).split(`
648
- `).length,h=Jl(a,d-1);i.push({name:u.name||"anonymous",kind:u.kind||"Unknown",classification:u.classification||"Other",signature:u.signature||p[0],line:d,endLine:h,doc:"",capabilities:JSON.stringify(u.meta||{})})}}let c=ln({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:i.map(l=>({name:l.name,kind:l.kind,classification:l.classification})),fileName:us.basename(e)});return{exports:i,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:c||"Module",parseStatus:i.length>0?"success":"partial"}}};q();import*as ds from"@swc/core";function co(s){if(!s||typeof s!="object")return!1;let e=s;return typeof e.parse=="function"&&typeof e.parseSync=="function"}function Kl(){if(co(ds))return ds;let s=ds;if(co(s.default))return s.default;throw new Error("SWC runtime unavailable: couldn't resolve parse/parseSync from @swc/core exports")}var lo=Kl();function ms(s,e,t){return lo.parse(s,e,t)}function si(s,e,t){return lo.parseSync(s,e,t)}var hs=new ii;async function pn(s){let e=uo.extname(s);if(hs.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=await po.promises.readFile(s,"utf-8");return{...await hs.parse(s,r),content:r}}catch(r){return S.error({filePath:s,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:r.message}}let t;try{t=await po.promises.readFile(s)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),i=Yr(n);try{let r=s.endsWith(".tsx"),o=s.endsWith(".d.ts")||s.endsWith(".d.tsx"),a,c={syntax:"typescript",tsx:r,decorators:!0,comments:!0};if(o)try{a=si(n,c)}catch{a=si(n,{...c,isModule:!1})}else a=si(n,c);let l=a.span.start,p=Kr(t),u=Xr(n),d=R=>Qr(R,l,t),h=eo(a.body),m=io(a.body);m.length>0&&S.debug({filePath:s,count:m.length},"Extracted type references"),m.forEach(R=>{h.push({module:"__type_reference__",name:R})});let f=to(a.body,l,t,n,i,u,s,d,p),_=no(a.body,l,t,i,d,p),g=Zn(s,"","Module"),w=u.length>0&&n.slice(0,u[0].start).trim().length===0?u[0].text:f.find(R=>R.doc)?.doc||"",x=Zr(w);if(!x&&f.length>0){let R=cn(n);x=ln({classification:g,capabilities:R,exports:f.map(k=>({name:k.name,kind:k.kind,classification:k.classification})),fileName:uo.basename(s)})}return{exports:f,imports:h,events:_,classification:g,summary:x,content:n,parseStatus:"success"}}catch(r){S.warn({filePath:s,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=await hs.parse(s,n);return{...o,content:n,classification:o.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return S.error({filePath:s,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}q();import xs from"p-limit";Ze();import vs from"path";import Dp from"fs";import Op from"os";import Ne from"path";import zt from"fs";import{loadConfig as Zl,createMatchPath as ep}from"tsconfig-paths";import lt from"path";import un from"fs";var pt=class extends Error{constructor(t,n,i){super(n);this.code=t;this.cause=i;this.name="FileSystemError"}};function mo(s){let e;try{e=un.statSync(s).isDirectory()?s:lt.dirname(s)}catch(t){throw t.code==="ENOENT"?new pt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new pt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new pt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==lt.dirname(e);){let t=lt.join(e,"tsconfig.json");if(un.existsSync(t))return e;e=lt.dirname(e)}return null}function ho(s){let e;try{e=un.statSync(s).isDirectory()?s:lt.dirname(s)}catch(t){throw t.code==="ENOENT"?new pt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new pt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new pt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==lt.dirname(e);){let t=lt.join(e,"package.json");if(un.existsSync(t))try{if(JSON.parse(un.readFileSync(t,"utf8")).workspaces)return e}catch{}e=lt.dirname(e)}return null}import Ht from"path";import vt from"fs";function fo(s,e){let t=new Map,n=e.workspaces||[];for(let i of n){let r=i.replace("/*",""),o=Ht.join(s,r);if(!vt.existsSync(o))continue;let a=vt.readdirSync(o);for(let c of a){let l=Ht.join(o,c,"package.json");if(vt.existsSync(l))try{let p=JSON.parse(vt.readFileSync(l,"utf8"));p.name&&t.set(p.name,{name:p.name,path:Ht.dirname(l),main:p.main||"dist/index.js"})}catch{}}}return t}function go(s){let e=new Map;try{let t=JSON.parse(vt.readFileSync(s,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[i,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),a=Ht.dirname(s),c=Ht.resolve(a,o),l=Ht.join(c,"package.json");if(vt.existsSync(l))try{let p=JSON.parse(vt.readFileSync(l,"utf8"));e.set(i,{name:i,path:c,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import yo from"path";import Me from"fs";var Ql=[".ts",".tsx",".d.ts",".js",".jsx"];function ut(s){let e=yo.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 Ql){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=yo.join(s,"index"+t);if(Me.existsSync(n))return n}return""}import{builtinModules as Xl,createRequire as og}from"node:module";var lg=new Set(Xl.map(s=>s.replace(/^node:/,"")));var oi=new Map;function ri(s){let e=mo(s);if(!e)return null;if(oi.has(e))return oi.get(e)||null;let t=Zl(e);if(t.resultType==="failed")return oi.set(e,null),null;let n=t,i=n.absoluteBaseUrl;!i&&n.paths&&Object.keys(n.paths).length>0&&(i=n.configFileAbsolutePath?Ne.dirname(n.configFileAbsolutePath):e);let r=ep(i,n.paths,n.mainFields,n.addMatchAll),o=ho(e),a=new Map;if(o){let u=Ne.join(o,"package.json");if(zt.existsSync(u))try{let d=JSON.parse(zt.readFileSync(u,"utf8"));a=fo(o,d)}catch{}}let c=Ne.join(e,"package.json");zt.existsSync(c)&&go(c).forEach((d,h)=>a.set(h,d));let l={baseUrl:i||"",paths:n.paths,matchPath:r,workspacePackages:a,imports:new Map},p=Ne.join(e,"package.json");if(zt.existsSync(p))try{let u=JSON.parse(zt.readFileSync(p,"utf8"));if(u.imports){for(let[d,h]of Object.entries(u.imports))if(typeof h=="string"||typeof h=="object"&&h!==null){let m=h;Array.isArray(h)&&(m=h[0]),typeof m=="object"&&(m=m.default||m.node),typeof m=="string"&&l.imports.set(d,m)}}}catch{}return oi.set(e,l),l}function Tt(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=Tt(i,e,t);if(r)return r}}if(s.startsWith(".")){let i=Ne.dirname(e),r=Ne.resolve(i,s);return ut(r)}let n=ri(e);if(n){let i=n.matchPath(s);if(i)return ut(i);if(!s.startsWith("@")||s.startsWith("@/")){let o=Ne.resolve(n.baseUrl,s),a=ut(o);if(a)return a}for(let[o,a]of n.imports.entries())if(o.includes("*")){let c="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",l=new RegExp(c),p=s.match(l);if(p){let u=p[1],d=a.replace("*",u),h=Ne.resolve(n.baseUrl,d);return ut(h)}}else if(o===s){let c=Ne.resolve(n.baseUrl,a);return ut(c)}let r=n.workspacePackages.get(s);if(r){let o=Ne.join(r.path,"src/index.ts");if(zt.existsSync(o))return o;let a=Ne.join(r.path,r.main),c=ut(a);if(c)return c}}return""}import tp from"fs";import np from"path";import _o from"js-yaml";function bo(s){let e=np.basename(s),t=tp.readFileSync(s,"utf8"),n=[];if(e.endsWith(".prisma"))return{...op(t,s),content:t};if(e.endsWith(".graphql")||e.endsWith(".gql"))return{...ap(t,s),content:t};let i="Configuration";return e==="lerna.json"?{...lp(t,s),content:t}:e==="turbo.json"?{...pp(t,s),content:t}:e==="pnpm-workspace.yaml"?{...up(t,s),content:t}:(e.includes("Dockerfile")?(i="Infrastructure (Docker) ",ip(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(i="Infrastructure (YAML) ",sp(t,n)):e.startsWith(".env")?(i="Configuration (Env) ",rp(t,n)):e==="package.json"&&(i="Project Manifest",cp(t,n)),{configs:n,classification:i,content:t})}function ip(s,e){let t=s.split(`
649
- `);for(let n of t){let i=n.trim();if(i.startsWith("FROM "))e.push({key:"base_image",value:i.substring(5).trim(),kind:"Image"});else if(i.startsWith("EXPOSE "))e.push({key:"port",value:i.substring(7).trim(),kind:"Port"});else if(i.startsWith("ENV ")){let r=i.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],a=r.slice(1).join("= ").trim()||"undefined",c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:a,kind:c})}}}}function sp(s,e){try{let t=_o.load(s);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[i,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${i}`,value:i,kind:"Service"}),o.image&&e.push({key:`service:${i}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(a=>{e.push({key:`service:${i}:port`,value:String(a),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(a=>{let[c,...l]=a.split("= ");c&&l.length>0&&e.push({key:`service:${i}:env:${c}`,value:l.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[a,c]of Object.entries(o.environment))e.push({key:`service:${i}:env:${a}`,value:String(c),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(a=>{e.push({key:`service:${i}:depends_on`,value:a,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let a of Object.keys(o.depends_on))e.push({key:`service:${i}:depends_on`,value:a,kind:"Dependency"})}let n=(i,r="")=>{if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,a]of Object.entries(i)){let c=r?`${r}.${o}`:o;if(t.services&&(c.startsWith("services.")||c==="services")){a&&typeof a=="object"&&!Array.isArray(a)&&n(a,c);continue}if(a&&typeof a=="object"&&!Array.isArray(a))n(a,c);else if(a!=null){let l=String(a);if(l==="[object Object]"||l.includes("[object Object]"))continue;let p="Env",u=/^[a-z0-9_-]+$/i.test(l),d=l.includes("://");o.toLowerCase().includes("service")&&(u||d)&&(p="Service"),o.toLowerCase().includes("image")&&(p="Image"),o.toLowerCase().includes("port")&&(p="Port"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&d&&(p="Service"),e.push({key:c,value:l.length>200?l.substring(0,197)+"...":l,kind:p})}}};n(t)}catch{let n=s.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(i=>{let r=i.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function rp(s,e){let t=s.split(`
650
- `);for(let n of t){let i=n.trim();if(i&&!i.startsWith("#")){let r=i.split("=");if(r[0]){let o=r[0].trim(),a=r.slice(1).join("=");a=a.trim().replace(/^['"](.*)['"]$/,"$1");let c="Env",l=a.includes("://");(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&l&&(c="Service"),e.push({key:o,value:a,kind:c})}}}}function op(s,e){let t=[],n="Contract (Prisma) ",i=/^model\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(s))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let a=/provider\s*=\s*"([^"]+)"/,c=s.match(a);return c&&t.push({key:"datasource_provider",value:c[1],kind:"Database Config"}),{classification:n,configs:t,content:s}}function ap(s,e){let t=[],n="Contract (GraphQL) ",i=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;){let o=r[0],a="GraphQL Type";o.startsWith("input")&&(a="GraphQL Input"),o.startsWith("interface")&&(a="GraphQL Interface"),o.startsWith("enum")&&(a="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:a})}return{classification:n,configs:t,content:s}}function cp(s,e){try{let t=JSON.parse(s);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"Env"}),t.workspaces){let r=Array.isArray(t.workspaces)?t.workspaces.join("",""):JSON.stringify(t.workspaces);e.push({key:"workspaces",value:r,kind:"Env"})}if(t.scripts){let r=["start","dev","build","test","docker"];for(let o of Object.keys(t.scripts))r.some(a=>o.includes(a))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},i=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(i.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Dependency"})}}catch{}}function lp(s,e){let t=[],n="Monorepo (Lerna) ";try{let i=JSON.parse(s);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),i.version&&t.push({key:"lerna_version",value:i.version,kind:"Monorepo"}),i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),i.npmClient&&t.push({key:"npm_client",value:i.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:s}}function pp(s,e){let t=[],n="Monorepo (Turborepo) ";try{let i=JSON.parse(s);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),i.pipeline)for(let r of Object.keys(i.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=i.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(i.tasks)for(let r of Object.keys(i.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:s}}function up(s,e){let t=[],n="Monorepo (pnpm) ";try{let i=_o.load(s);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),i&&i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n,content:s}}V();Ae();import{execSync as Rt}from"child_process";import dn from"path";import fs from"fs";function me(s){try{if(!fs.existsSync(dn.join(s,".git")))return null;let e=Rt("git rev-parse --abbrev-ref HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return e==="HEAD"?Rt("git rev-parse --short HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():e.replace(/[\/\\:*"<>|?]/g,"-")}catch{return null}}function De(s){try{return fs.existsSync(dn.join(s,".git"))?Rt("git rev-parse HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function So(s,e=50){try{let t=Rt(`git rev-list --max-count=${e} HEAD`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return t?t.split(`
651
- `):[]}catch{return[]}}function wo(s,e,t){try{return Rt(`git merge-tree --write-tree ${e} ${t}`,{cwd:s,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}var dp=new Set([".ts",".tsx",".yaml",".yml",".php",".py",".go",".prisma",".graphql",".gql"]),mp=new Set(["package.json","lerna.json","turbo.json","pnpm-workspace.yaml"]),hp=new Set(["node_modules",".git","dist","build","vendor",".next",".cache","coverage"]);function Eo(s){let e=s.split("/");for(let i of e)if(hp.has(i))return!1;if(s.endsWith(".min.js"))return!1;let t=dn.basename(s);if(t.startsWith("Dockerfile")||t.startsWith(".env")||mp.has(t))return!0;let n=dn.extname(t).toLowerCase();return dp.has(n)}function fp(s){let e=s.trim(),t=e.indexOf(" -> ");if(t!==-1)return e.substring(t+4);let n=e.split(/\s+/);return n.length>=2?n[n.length-1]:e}function xo(s,e){try{if(!fs.existsSync(dn.join(s,".git")))return!0;let t=De(s);if(!t)return!0;if(e&&e!==t){let i=Rt(`git diff --name-only ${e} ${t}`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(i&&i.split(`
652
- `).some(r=>r&&Eo(r)))return!0}let n=Rt("git status --porcelain",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return n?n.split(`
653
- `).some(i=>i?Eo(fp(i)):!1):!1}catch{return!0}}V();q();import{execSync as vo}from"child_process";var kt=S.child({module:"nano-repair"}),qe=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:i}=O.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};kt.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let i of e){let r=this.exports.findByNameAndFile(i.symbol_name,i.file_path);if(r.length>0){let a=r.find(c=>c.signature===i.signature)||r[0];this.intentLogs.update(i.id,{symbol_id:a.id}),kt.info({logId:i.id,symbol:i.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(i.symbol_name);if(o.length>0){let a=o.filter(c=>c.file_path!==i.file_path);if(a.length>0){let c=a.find(l=>l.signature===i.signature)||a[0];this.intentLogs.update(i.id,{symbol_id:c.id,file_path:c.file_path}),kt.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&&kt.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(e={}){let t=e.enableContextPivot===!0,n=e.enableMergeSentinel===!0,i="HEAD";try{i=vo("git rev-parse --abbrev-ref HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return{suspended:0,resumed:0,completed:0,contextPivotEnabled:t,mergeSentinelEnabled:n}}if(!i)return{suspended:0,resumed:0,completed:0,contextPivotEnabled:t,mergeSentinelEnabled:n};let r=0,o=0;if(t){let c=this.missions.findActive();for(let l of c)l.git_branch&&l.git_branch!==i&&(this.missions.updateStatus(l.id,"suspended"),kt.info({missionId:l.id,branch:l.git_branch,current:i},"Context Pivot: Suspended mission"),r++);o=this.missions.resumeByBranch(i)}let a=0;if(n){let c=[];try{c=vo(`git branch --merged "${i}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
654
- `).map(p=>p.trim().replace(/^\* /,"")).filter(p=>p&&p!==i)}catch{}if(c.length>0){let l=this.missions.findMergedMissions(i,c);for(let p of l)this.missions.updateStatus(p.id,"completed"),kt.info({missionId:p.id,branch:p.git_branch},"Merge Sentinel: Auto-completed mission"),a++}}return(r>0||o>0||a>0)&&kt.info({suspended:r,resumed:o,completed:a},"Git-Native Lifecycle Sync complete"),{suspended:r,resumed:o,completed:a,contextPivotEnabled:t,mergeSentinelEnabled:n}}};q();St();import{Worker as gp}from"node:worker_threads";import{cpus as yp}from"node:os";import{fileURLToPath as bp}from"node:url";import{dirname as _p,join as Ep}from"node:path";import{existsSync as Sp}from"node:fs";var To=bp(import.meta.url),wp=_p(To),xp=To.endsWith(".ts");function vp(){if(xp)return null;let s=Ep(wp,"worker.js");return Sp(s)?s:_e("dist/logic/parser/worker.js")}var gs=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(4,yp().length-1)),this.initTimeout=e.initTimeout??3e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{S.info({numWorkers:this.numWorkers},"Initializing parser worker pool");let t=new Promise((n,i)=>{e=setTimeout(()=>i(new Error(`Parser pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0;return}this.initialized=!0,S.info({numWorkers:this.workers.length},"Parser worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=vp();if(!e)throw new Error("Parser worker pool not available in development mode (tsx). Use main-thread fallback.");S.debug({workerPath:e},"Resolved parser worker path");let t=[];for(let n=0;n<this.numWorkers;n++)t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Parser worker ${t} initialization timed out`))},this.initTimeout),o=new gp(e,{execArgv:process.execArgv}),a={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){o.terminate().catch(()=>{}),n();return}this.workers.push(a),S.debug({workerIndex:t},"Parser worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(a,c.id,c.result):c.type==="error"&&c.id&&this.handleTaskError(a,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),S.error({err:c,workerIndex:t},"Parser worker error"),a.currentTaskId&&this.handleTaskError(a,a.currentTaskId,c),!this.initialized){i(c);return}let l=this.workers.indexOf(a);l!==-1&&this.workers.splice(l,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{S.error({err:p},"Failed to replace crashed parser worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&S.warn({workerIndex:t,code:c},"Parser worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"parse",id:t.id,filePath:t.filePath}))}async parseFile(e){return this.initialized||await this.initialize(),new Promise((t,n)=>{let r={id:`parse_${++this.taskIdCounter}`,filePath:e,resolve:t,reject:n};this.taskQueue.push(r),this.processQueue()})}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}S.info({numWorkers:this.workers.length},"Shutting down parser worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,this.initPromise=void 0,S.info("Parser worker pool shutdown complete")}},Ut=null;function Ro(s){return Ut||(Ut=new gs(s)),Ut}async function ko(){Ut&&(await Ut.shutdown(),Ut=null)}V();q();It();ys();bs();_s();import{execSync as Yo}from"child_process";var fi=S.child({module:"heritage-analyzer"}),gi=class{repos;repoPath;constructor(e){this.repos=O.getInstance(e),this.repoPath=e}analyzeHeritage(e=20){try{fi.info({limit:e},"Analyzing repository heritage...");let t=Yo(`git log -n ${e} --pretty=format:"%H|%at|%an|%s"`,{cwd:this.repoPath,encoding:"utf-8"});if(!t)return;let n=t.split(`
655
- `).filter(Boolean);for(let i of n){let[r,o,a,c]=i.split("|"),l=this.analyzeCommitImpact(r);if(l.significant){let p=Array.from(l.layers).join(", "),u=`Heritage: ${c} (by ${a}). Touched ${l.fileCount} files across [${p}].`;this.repos.intentLogs.importHeritage(u,r,parseInt(o,10),.7),fi.debug({sha:r,subject:c},"Logged heritage move")}}fi.info("Heritage analysis complete.")}catch(t){fi.warn({err:t.message},"Failed to run heritage analysis")}}analyzeCommitImpact(e){let t=new Set,n=0;try{let r=Yo(`git diff-tree --no-commit-id --name-only -r ${e}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
656
- `).filter(Boolean);n=r.length;for(let c of r){let l=this.classifyPathOnly(c);l!=="Unknown"&&t.add(l)}let o=t.has("Entry")||t.has("Data")||t.has("Infrastructure"),a=t.size>=2||n>5;return{significant:o||a,layers:t,fileCount:n}}catch{return{significant:!1,layers:t,fileCount:0}}}classifyPathOnly(e){let t=e.startsWith("/")?e:"/"+e;return Es.some(n=>n.test(t))?"Test":ci.some(n=>n.test(t))||ai.some(n=>n.test(t))?"Entry":mn.some(n=>n.test(t))?"Data":pi.some(n=>n.test(t))?"Utility":ui.some(n=>n.test(t))?"Entry":di.some(n=>n.test(t))?"Data":mi.some(n=>n.test(t))?"Entry":hi.some(n=>n.test(t))?"Data":Ss.some(n=>n.test(t))?"Infrastructure":/\.(service|logic|usecase|interactor|manager)\.(ts|js|php|py)$/i.test(t)||li.some(n=>n.test(t))?"Logic":"Unknown"}};Ze();St();import{spawn as Cp}from"node:child_process";import ws from"node:os";import{resolve as Ip}from"node:path";import{existsSync as Ko}from"node:fs";import{fileURLToPath as Lp}from"node:url";import{dirname as $p}from"node:path";var Qo=Lp(import.meta.url),Ap=$p(Qo),Pp=ws.constants.priority.PRIORITY_LOWEST??ws.constants.priority.PRIORITY_LOW;function Mp(){if(Qo.endsWith(".ts"))return null;let s=Ip(Ap,"../../entry/ember/index.js");if(Ko(s))return s;let e=_e("dist/entry/ember/index.js");return Ko(e)?e:null}function Xo(s){try{let t=Te(s).prepare("SELECT key, value FROM ember_state WHERE key IN ('status','progress','pid')").all(),n=new Map(t.map(i=>[i.key,i.value??""]));return{status:n.get("status")??"idle",progress:n.get("progress")??"0/0",pid:n.get("pid")??null}}catch{return{status:"idle",progress:"0/0",pid:null}}}function Np(s,e){let t=Te(s);t.transaction(()=>{let n=t.prepare("INSERT OR REPLACE INTO ember_state (key, value, updated_at) VALUES (?, ?, unixepoch())");n.run("pid",String(e)),n.run("status","running"),n.run("repo_path",s)})()}function Zo(s){let{pid:e}=Xo(s);if(!e)return!1;let t=parseInt(e,10);if(!Number.isFinite(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function ea(s){let e=Mp();if(!e)return;let t=Cp(process.execPath,[e,s],{detached:!0,stdio:"ignore",env:{...process.env,EMBER_MODE:"1"}});if(t.pid!=null){try{ws.setPriority(t.pid,Pp)}catch{}t.unref(),Np(s,t.pid)}}function yi(s){let{status:e,progress:t}=Xo(s);return{status:e,progress:t}}var Fp=Op.cpus().length||4,Wp=Qn.DEFAULT_CONCURRENCY;function ia(s,e=[]){if(!Array.isArray(s))return e;for(let t of s)!t||typeof t!="object"||(e.push(t),Array.isArray(t.members)&&t.members.length>0&&ia(t.members,e));return e}function ta(s){if(typeof s!="number"||!Number.isFinite(s))return null;let e=Math.trunc(s);return e>0?e:null}function sa(s){let e=typeof s?.content=="string"&&s.content.length>0?s.content.split(`
657
- `).length:0,t=ia(s?.exports),n=0,i=0,r=0,o=0;for(let a of t){let c=ta(a?.line??a?.start_line),l=ta(a?.endLine??a?.end_line??c);if(!c||!l||l<c||e>0&&l>e){i++;continue}n++,l>c&&o++,e>0&&c===e&&l===e&&r++}return{total:t.length,valid:n,invalid:i,eofCollapsed:r,multiLine:o,lineCount:e}}function Hp(s){let e=sa(s);if(e.total===0||e.lineCount===0)return!1;if(e.invalid>0)return!0;let t=e.eofCollapsed/e.total;return e.eofCollapsed>=3&&t>=.5||e.total>=2&&e.eofCollapsed===e.total}function na(s){let e=sa(s);return e.valid*2+e.multiLine*2-e.eofCollapsed*3-e.invalid*4}async function X(s,e=Wp,t=!1,n=!0,i){let r=O.getInstance(s),o=r.files.database,a=Ke(s),c=a.concurrency??e;if(Or(),!t&&Xe(s)){let g=nn(s),b=De(s);if(g&&!xo(s,g))return os(),S.debug({repoPath:s,commit:b},"Index is current, skipping re-index (fast-path)"),o}ri(s);let l=r.files.findAll(),p=new Map(l.map(g=>[g.path,{mtime:g.mtime,hash:g.content_hash}])),u=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let d=await Jr(s,a.ignore),h=new Map(d.map(g=>[g.path,g.mtime])),m=l.filter(g=>!h.has(g.path)).map(g=>g.path),f=l.length===0,_=[];if(t||f)_.push(...d);else{let g=d.filter(R=>{let k=p.get(R.path);return!k||k.mtime!==R.mtime}),b=xs(c*4),w=g.map(R=>b(async()=>{let k=p.get(R.path);if(!k||!k.hash)return R;try{let D=await Dp.promises.readFile(R.path,"utf8");return sr(D,k.hash)?R:(r.files.updateMtime(R.path,R.mtime),null)}catch{return null}})),x=await Promise.all(w);_.push(...x.filter(R=>R!==null))}if(m.length===0&&_.length===0){os();let g=De(s);return Yi(s,g||void 0),o}if(f?S.info({totalFiles:d.length},"Starting initial repository indexing..."):S.info({toDelete:m.length,toProcess:_.length},"Syncing repository updates..."),m.length>0&&r.files.deletePaths(m),_.length>0){Wr(),n?(Pn(!0),Ot().initialize().catch(()=>{})):Pn(!1);let g=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,b=[],w=[];for(let $ of _)g.test(vs.basename($.path))?b.push($):w.push($);let x=0,R=_.length,k=!1,D=Ro();try{await D.initialize(),k=!0,S.info({workers:D.workerCount},"Parser worker pool active")}catch($){S.warn({err:$},"Parser worker pool failed to initialize, falling back to main-thread parsing"),k=!1}let U=async($,W)=>{let L=W;if(k&&Hp(W))try{let F=await pn($.path);na(F)>na(W)&&(S.warn({filePath:$.path},"Detected suspicious worker parse ranges; using main-thread parse output"),L=F)}catch(F){S.warn({filePath:$.path,err:F instanceof Error?F.message:String(F)},"Main-thread parse retry failed after suspicious worker parse")}let A=L.imports?.map(F=>({...F,resolved_path:Tt(F.module,$.path,s)})),H=L.content?Nt(L.content):null;return x++,(x%50===0||x===R)&&S.info({completed:x,total:R},"Parsing files..."),i?.({phase:"parse",current:x,total:R,message:`Parsing ${vs.basename($.path)}`}),{meta:$,...L,imports:A,embedding:null,kind:"code",contentHash:H}},P;if(k)P=b.map($=>D.parseFile($.path).then(W=>U($,W),W=>(x++,S.error({path:$.path,error:W},"Worker parse failed"),{meta:$,exports:[],imports:[],content:"",kind:"error"})));else{let $=f?Math.max(c,Math.min(Fp-1,16)):c,W=xs($);P=b.map(L=>W(async()=>{try{let A=await pn(L.path);return U(L,A)}catch(A){return x++,S.error({path:L.path,error:A},"Failed to parse file"),{meta:L,exports:[],imports:[],content:"",kind:"error"}}}))}let E=xs(c),T=w.map($=>E(async()=>{try{let W=bo($.path),L=W.content?Nt(W.content):null;return x++,(x%50===0||x===R)&&S.info({completed:x,total:R},"Parsing configs..."),i?.({phase:"parse",current:x,total:R,message:`Parsing config ${vs.basename($.path)}`}),{meta:$,...W,embedding:null,kind:"config",contentHash:L}}catch(W){return x++,S.error({path:$.path,error:W},"Failed to parse config"),{meta:$,exports:[],imports:[],content:"",kind:"error"}}}));S.info({total:R,codeFiles:b.length,configFiles:w.length,useParserPool:k},"Phase 1: Parsing all files...");let I=Date.now(),M=(await Promise.all([...P,...T])).filter(Boolean),N=Date.now()-I;if(an("parse",N),S.info({count:M.length,time:`${(N/1e3).toFixed(1)}s`},"Phase 1 complete"),k&&ko().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let $=[];M.forEach((C,B)=>{"summary"in C&&C.summary&&$.push({fileIdx:B,text:C.summary})}),S.info("Phase 2+3: Generating file-summary embeddings + persisting in parallel..."),i?.({phase:"embed",current:0,total:M.length,message:"Generating embeddings..."});let W=Date.now(),L=(async()=>{let C=[];return $.length>0&&(S.info({count:$.length}," \u2192 Generating file summary embeddings..."),C=await ns($.map(B=>B.text),256),S.info({count:$.length}," \u2713 File summaries complete")),C})();i?.({phase:"persist",current:0,total:M.length,message:"Saving to database..."});let A=Date.now();r.files.batchSaveIndexResults(M,s,Nt,Tt);let H=Date.now()-A;an("persist",H),S.info({time:`${(H/1e3).toFixed(1)}s`},"Structural persist complete");let F=await L,v=Date.now()-W;if(an("embed",v),S.info({time:`${(v/1e3).toFixed(1)}s`},"File-summary embeddings complete"),F.length>0){let C=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),B=o.transaction(J=>{for(let z of J)C.run(z.embedding?JSON.stringify(z.embedding):null,z.path)}),j=$.map((J,z)=>({path:M[J.fileIdx].meta.path,embedding:F[z]}));B(j),S.info({count:j.length},"File embedding column updated")}}else{i?.({phase:"persist",current:0,total:M.length,message:"Saving to database..."});let $=Date.now();r.files.batchSaveIndexResults(M,s,Nt,Tt),an("persist",Date.now()-$)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(f||_.length>0){let g=De(s);Yi(s,g||void 0)}if(n&&!Zo(s)&&ea(s),(_.length>0||m.length>0)&&new qe(s).detectAndRepairShifts(),f||n)try{new gi(s).analyzeHeritage(50)}catch(g){S.warn({err:g.message},"Heritage sync deferred")}return Fr(Date.now()-u),i?.({phase:"complete",current:_.length,total:_.length,message:"Indexing complete"}),o}V();async function bi(s,e=Qn.DEFAULT_CONCURRENCY,t="detailed",n,i){S.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await X(s,e);let{files:r,exports:o,imports:a}=O.getInstance(s),c=n?r.findInSubPath(s,n):r.findAll(),l=Ke(s),p=zp(),u=ra.join(s,".gitignore");if(oa.existsSync(u)&&p.add(oa.readFileSync(u,"utf8")),l.ignore&&l.ignore.length>0&&p.add(l.ignore),p.add(Kn),c=c.filter(b=>{let w=ra.relative(s,b.path);return!p.ignores(w)}),S.info({count:c.length},"Fetching data from DB..."),t==="lite"){let b=c.map(w=>({path:w.path,mtime:w.mtime}));return Yn(b,s,t,i)}if(t==="summaries"){let b=c.map(w=>({path:w.path,mtime:w.mtime,classification:w.classification||void 0,summary:w.summary||void 0}));return Yn(b,s,t,i)}let d=c.map(b=>b.path),h=o.findByFiles(d),m=t==="detailed"?a.findByFiles(d):[],f=new Map;for(let b of h){let w=f.get(b.file_path)||[];w.push(b),f.set(b.file_path,w)}let _=new Map;for(let b of m){let w=_.get(b.file_path)||[];w.push(b),_.set(b.file_path,w)}let g=c.map(b=>{let x=(f.get(b.path)||[]).map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.start_line}));t==="structure"?x=x.map(k=>({name:k.name,kind:k.kind,line:k.line})):t==="signatures"&&(x=x.map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.line})));let R=[];return t==="detailed"&&(R=(_.get(b.path)||[]).map(D=>({module:D.module_specifier,resolved_path:D.resolved_path}))),{path:b.path,mtime:b.mtime,classification:b.classification||void 0,summary:b.summary||void 0,exports:x,imports:R.length>0?R:void 0,chunks:[]}});return S.info({count:g.length},"Building hierarchical project tree..."),Yn(g,s,t,i)}async function aa(s,e){let t=Up.resolve(s);try{await Y(async()=>{pe("\u{1F311} Liquid Shadow: Topological Mapping");let n=parseInt(e.depth,10),i=await bi(t,n,"detailed",e.subPath);console.log(` ${y.bold("Root")}: ${y.cyan(t)}`),e.subPath&&console.log(` ${y.bold("Subpath")}: ${y.yellow(e.subPath)}`),console.log("");let r=o=>({name:o.name,info:o.type==="directory"?`${o.children?.length||0} items`:o.size,color:o.type==="directory"?"blue":"white",children:o.children?.map(r)});ss([r(i)]),console.log(""),Pe("Mapping concluded.")})}finally{await Q(t)}}import la from"path";import jp from"fs";q();import ce from"path";import Ts from"fs";var _i=S.child({module:"path-resolver"}),hn=class{repoPath;constructor(e){this.repoPath=ce.isAbsolute(e)?ce.normalize(e):ce.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw _i.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(ce.isAbsolute(e)?t=ce.normalize(e):t=ce.join(this.repoPath,e),t=ce.normalize(t),!this.isWithinRoot(t))throw _i.warn({inputPath:e,resolved:t},"Path traversal attempt blocked"),new Error(`Access denied: path '${e}' is outside the repository root`);return t}resolveAndValidate(e){try{let t=this.resolve(e);return Ts.existsSync(t)?t:(_i.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return _i.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=ce.resolve(e),n=ce.resolve(this.repoPath),i=ce.relative(n,t);if(i.startsWith("..")||ce.isAbsolute(i))return!1;if(Ts.existsSync(t)){let o=Ts.realpathSync(t),a=ce.relative(n,o);if(a.startsWith("..")||ce.isAbsolute(a))return!1}return!0}catch{return!1}}getRelative(e){let t=ce.normalize(e);return ce.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return ce.normalize(e)}static isPathWithinRoot(e,t){let n=ce.resolve(e),i=ce.resolve(t),r=ce.relative(n,i);return r===""||!r.startsWith("..")&&!ce.isAbsolute(r)}};function ca(s){return new hn(s)}async function pa(s,e){let t=la.resolve(s);await Y(async()=>{if(pe("\u{1F311} Liquid Shadow: Intelligence Deployment"),console.log(` ${y.bold("Target")}: ${y.cyan(t)}`),console.log(` ${y.bold("Objective")}: ${e.output?y.magenta("Data Extraction"):y.green("Semantic Mapping")}`),console.log(""),!e.output){let i=Re();i.start("Engaging intelligence engines...");let r="",o=a=>{if(a.phase!==r){r=a.phase;let c={scan:"\u{1F4E1} Scanning topography",parse:"\u{1F9E9} Parsing symbols",embed:"\u{1F9E0} Generating vectors",persist:"\u{1F4BE} Hardening index",complete:"\u{1F3C1} Mapping complete"}[a.phase]||a.phase;i.message(`${c}...`)}if(a.total>0&&a.current>0){let c=Math.round(a.current/a.total*100);i.message(`${r==="parse"?"Parsing":"Processing"}: ${a.current}/${a.total} (${c}%)`)}};try{await X(t,void 0,e.force,e.deep??!0,o),i.message("\u{1FA79} Running Nano-Repair healing...");let c=new qe(t).detectAndRepairShifts();i.stop("Intelligence mapping successfully concluded."),console.log(""),console.log(` ${y.bold("Next Steps:")}`),console.log(` ${y.dim("view your repo stats")} -> ${y.bold(y.cyan("liquid-shadow dashboard"))}`),console.log(` ${y.dim("start a chat search")} -> ${y.bold(y.cyan('liquid-shadow search-concept "your query"'))}`),console.log(""),Pe("Liquid Shadow is online.")}catch(a){throw i.stop(`Operation failed: ${a.message}`),a}finally{await Q(t)}return}let n=Re();n.start("Engaging intelligence engines...");try{let i=await bi(t,5,e.level,e.subPath),r=la.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!hn.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");jp.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Data extraction saved: ${y.bold(y.cyan(r))}`),Pe("Extraction complete.")}catch(i){throw n.stop(`Extraction failed: ${i.message}`),i}finally{await Q(t)}})}import{performance as ua}from"perf_hooks";import Bp from"path";V();async function da(s){let e=Bp.resolve(s);await Y(async()=>{console.log(`
658
- ${y.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${y.gray("Repository: ")} ${e}`),console.log(` ${y.yellow("Starting fresh index (DB deleted)...")}
659
- `);let t=ua.now();try{await X(e,10,!0);let n=ua.now()-t,i=O.getInstance(e),r=i.files.getCount(),o=i.exports.getCount(),a=i.exports.getWithEmbeddingsCount();se("Benchmark Results",`${y.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
660
- ${y.bold("Files Processed")}: ${y.cyan(r.toString())}
661
- ${y.bold("Symbols Extracted")}: ${y.cyan(o.toString())}
662
- ${y.bold("Symbols Embedded")}: ${y.cyan(a.toString())} (${(a/o*100).toFixed(1)}%)
715
+ `;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=Po.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(`
716
+ `),a=this.getQueries(n);if(!a)return[];let c=new Ft.Query(i,a).matches(r.rootNode),p=[];for(let u of c){let d=u.captures.find(f=>f.name==="name")?.node,h=u.captures[0].node,m=u.captures[0].name;if(d){let f=h.startPosition.row+1,b=h.endPosition.row+1,g=o[h.startPosition.row].trim();p.push({name:d.text,kind:this.mapKind(m,n),classification:this.mapClassification(m),signature:g,line:f,endLine:b,doc:"",capabilities:"{}"})}}return p}};var gi=class{parse(e,t=!1){let n=[],i=[],r=e.split(`
717
+ `),o="",a="",l=0,c=0,p=-1,u=-1,d=[],h=[],m=!1,f=t?"api":"",b="",g=/^namespace\s+([a-zA-Z0-9_\\]+);/,y=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,E=/^interface\s+([a-zA-Z0-9_]+)/,k=/^trait\s+([a-zA-Z0-9_]+)/,R=/^enum\s+([a-zA-Z0-9_]+)(?:\s*:\s*(string|int))?\s*/,w=/^((?:(?:public|protected|private|static)\s+)*)function\s+([a-zA-Z0-9_]+)\s*\(/,N=/^(public|protected|private)\s+(static\s+)?(readonly\s+)?(?:(\?\s*)?([a-zA-Z0-9_\\|]+)\s+)?\$([a-zA-Z0-9_]+)/,U=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,H=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,C=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,M=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/,D=/\$this->(hasMany|hasOne|belongsTo|belongsToMany|morphTo|morphMany|morphOne|morphToMany|morphedByMany)\s*\(\s*([a-zA-Z0-9_\\]+)(?:::class)?/,P=/^->(hasMany|hasOne|belongsTo|belongsToMany|morphTo|morphMany|morphOne|morphToMany|morphedByMany)\s*\(\s*([a-zA-Z0-9_\\]+)(?:::class)?/,B=/(public|protected|private)\s+(readonly\s+)?(?:(\?\s*)?([a-zA-Z0-9_\\|]+)\s+)?\$([a-zA-Z0-9_]+)/g,L=/(?:protected|public)\s+\$(fillable|casts|guarded|hidden|appends|with)\s*=/;function A(S){try{let v=JSON.parse(S||"{}");if(v&&typeof v=="object"&&!Array.isArray(v))return v}catch{}return{}}function $(S,v){let T=[],I=S,z=0,j=0;for(;I<r.length;){let Q=r[I].trim();T.push(Q),z+=(Q.match(/\[/g)||[]).length-(Q.match(/]/g)||[]).length,j+=(Q.match(/\(/g)||[]).length-(Q.match(/\)/g)||[]).length;let fe=Q.includes(v),Ce=z<=0&&j<=0;if(fe&&Ce)break;I+=1}return{text:T.join(" "),endIndex:I}}function W(S,v){let T=v.replace(/^[^=]+=\s*/,"").replace(/;$/,"").trim();if(S==="casts"){let Q={},fe=/['"]([^'"]+)['"]\s*=>\s*['"]([^'"]+)['"]/g,Ce=null;for(;Ce=fe.exec(T);)Q[Ce[1]]=Ce[2];return Q}let I=[],z=/['"]([^'"]+)['"]/g,j=null;for(;j=z.exec(T);)I.push(j[1]);return I}function J(S,v){for(let T=v;T>=0;T-=1){let I=S[T]?.trim()||"";if(I)return I}return""}function O(S,v,T,I){if(!o)return;let z=v.split("\\").pop()||v;i.push({type:"eloquent_relation",name:z,direction:"produce",line:T,snippet:I,method:S,url:`${o}->${z}`})}for(let S=0;S<r.length;S++){let v=r[S].trim();if(!v)continue;let T=(v.match(/{/g)||[]).length,I=(v.match(/}/g)||[]).length,z=c;if(c+=T-I,a&&c<=u){let V=n.find(q=>q.name===a&&q.line===l);V&&(V.endLine=S+1),a="",u=-1}if(o&&c<=p){let V=n.find(q=>q.name===o&&(q.kind==="ClassDeclaration"||q.kind==="TraitDeclaration"||q.kind==="InterfaceDeclaration"||q.kind==="EnumDeclaration"));V&&(V.endLine=S+1),o="",p=-1}let j=v.match(M);if(j&&(f=j[1]),v.includes("});")&&(f=""),v.startsWith("/**")){m=!0,h=[];continue}if(m){v.endsWith("*/")?m=!1:h.push(v.replace(/^\*\s?/,""));continue}let Q=v.match(H);if(Q){d.push(Q[1]);continue}let fe=v.match(g);if(fe){b=fe[1]||"",d=[],h=[];continue}let Ce=v.match(y);if(Ce){o=Ce[1],p=c-T;let V={attributes:d};b&&(V.namespace=b),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:S+1,endLine:S+1,doc:h.join(`
718
+ `).trim(),capabilities:JSON.stringify(V),members:[]}),d=[],h=[];continue}let Ie=v.match(E);if(Ie){let V=Ie[1];o=V,p=c-T,n.push({name:V,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${V}`,line:S+1,endLine:S+1,doc:h.join(`
719
+ `).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let gt=v.match(k);if(gt){let V=gt[1];o=V,p=c-T,n.push({name:V,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${V}`,line:S+1,endLine:S+1,doc:h.join(`
720
+ `).trim(),capabilities:JSON.stringify({attributes:d}),members:[]}),d=[],h=[];continue}let he=v.match(R);if(he){let V=he[1],q=he[2]||null;o=V,p=c-T;let X={attributes:d,backedType:q};b&&(X.namespace=b),n.push({name:V,kind:"EnumDeclaration",classification:"Enum",signature:q?`enum ${V}: ${q}`:`enum ${V}`,line:S+1,endLine:S+1,doc:h.join(`
721
+ `).trim(),capabilities:JSON.stringify(X),members:[]}),d=[],h=[];continue}let Ne=v.match(w);if(Ne){let V=(Ne[1]||"").trim(),q=Ne[2],X=!!o,we=/\bprivate\b/.test(V)?"private":/\bprotected\b/.test(V)?"protected":"public",ce=/\bstatic\b/.test(V),Ge=$(S,")"),ct=Ge.text.match(/\)\s*:\s*([?a-zA-Z0-9_\\|]+)/),On=ct?ct[1]:null,ul=T>0&&I>=T;a=q,l=S+1,u=c-T;let _r=!1,as={};for(let De of d)De.toLowerCase().includes("route")&&(_r=!0,as={type:"route",method:"GET",path:"/"});let Er=h.join(`
722
+ `).trim();if(_r){let De=as.path||"/";n.push({name:De,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${q}`,line:S+1,endLine:S+1,doc:Er,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${q}`:q,...as})}),i.push({type:"api_route",name:De,direction:"consume",line:S+1,snippet:v})}let Sr={name:q,kind:X?"MethodDeclaration":"FunctionDeclaration",classification:X?"Method":"Function",signature:`${X?o+":: ":""}${q}`,line:S+1,endLine:S+1,doc:Er,capabilities:JSON.stringify(X?{attributes:d,visibility:we,static:ce,returnType:On}:{attributes:d,returnType:On})};n.push(Sr);let cs=X?v.match(D):null;if(cs&&O(cs[1],cs[2],S+1,v),X&&q==="__construct"){let De=null;for(;De=B.exec(Ge.text);){let xr=De[1],wr=!!De[2],ls=De[4]?`${De[3]?"?":""}${De[4]}`:null,vr=De[5],dl=`${xr} ${wr?"readonly ":""}${ls?`${ls} `:""}$${vr}`.trim();n.push({name:vr,kind:"PropertyDeclaration",classification:"Property",signature:dl,line:S+1,endLine:S+1,doc:"",capabilities:JSON.stringify({visibility:xr,static:!1,readonly:wr,type:ls}),members:[]})}B.lastIndex=0}ul&&(Sr.endLine=S+1,a="",u=-1),d=[],h=[];continue}let Pe=!1,Ee=!1,K=S,ae=o&&!a?v.match(N):null;if(ae){Pe=!0;let V=ae[1],q=!!ae[2],X=!!ae[3],we=ae[5]?`${ae[4]?"?":""}${ae[5]}`:null,ce=ae[6],Ge=`${V} ${q?"static ":""}${X?"readonly ":""}${we?`${we} `:""}$${ce}`.trim();n.push({name:ce,kind:"PropertyDeclaration",classification:"Property",signature:Ge,line:S+1,endLine:S+1,doc:h.join(`
723
+ `).trim(),capabilities:JSON.stringify({visibility:V,static:q,readonly:X,type:we}),members:[]})}let at=o&&!a?v.match(L):null;if(at){Ee=!0;let V=at[1],q=$(S,";");K=q.endIndex;let X=W(V,q.text),we=[...n].reverse().find(ce=>ce.name===o&&ce.kind==="ClassDeclaration");if(we){let ce=A(we.capabilities);(!ce.modelConfig||typeof ce.modelConfig!="object"||Array.isArray(ce.modelConfig))&&(ce.modelConfig={}),ce.modelConfig[V]=X,we.capabilities=JSON.stringify(ce)}}if(Pe||Ee){Ee&&K>S&&(S=K),d=[],h=[];continue}let yt=v.match(U);if(yt){let V=yt[1]||"",q=yt[2]||V.split("\\").pop()||"";n.push({name:q,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${V}`,line:S+1,endLine:S+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:V})}),d=[],h=[];continue}let Ue=v.match(C);if(Ue){let V=Ue[1].toUpperCase(),q=Ue[2];if(v.includes("Route::")||v.includes("router->")||v.includes("action")||v.includes(",")&&!v.includes("view(")){if(f){let ct=f.startsWith("/")?f:`/${f}`,On=q.startsWith("/")?q:`/${q}`;q=(ct+On).replace(/\/+/g,"/")}let we=null,ce=v.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(ce)we=`${ce[1]}@${ce[2]}`;else if(v.includes("::class")){let ct=v.match(/([a-zA-Z0-9_]+)::class/);ct&&(we=ct[1])}let Ge=v;!v.endsWith(");")&&S+1<r.length&&(Ge+=" "+r[S+1].trim(),!Ge.endsWith(");")&&S+2<r.length&&(Ge+=" "+r[S+2].trim())),n.push({name:q,kind:"HTTP Route",classification:"Service Boundary",signature:Ge,line:S+1,endLine:S+1,doc:"",capabilities:JSON.stringify({type:"route",method:V,path:q,handler:we})}),i.push({type:"api_route",name:q,direction:"consume",line:S+1,snippet:Ge,method:V,url:q}),h=[];continue}}let je=o&&a?v.match(D):null,Nt=o&&a?v.match(P):null;if(je)O(je[1],je[2],S+1,v);else if(Nt){let V=J(r,S-1);/\$this\b/.test(V)&&O(Nt[1],Nt[2],S+1,v)}let br=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,xe=v.match(br);if(xe){let V=(xe[1]||xe[3]).toUpperCase(),q=(xe[2]||xe[4]).trim();(q.startsWith("'")&&q.endsWith("'")||q.startsWith('"')&&q.endsWith('"'))&&(q=q.substring(1,q.length-1)),i.push({type:"api_route",name:q,direction:"produce",line:S+1,snippet:v,method:V,url:q})}!v.startsWith("#[")&&!v.startsWith("//")&&!v.startsWith("*")&&!m&&(d=[],h=[])}return{nodes:n,events:i}}};var yi=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],i=e.split(`
724
+ `),r=[{indent:-1,name:"root",type:"root"}],o=[],a=/^class\s+([a-zA-Z0-9_]+)/,l=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,c=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,p=/^@(.*)/;function u(E){return E.trim().split(/[.(]/)[0]?.trim()||E}function d(E){let k=E.decorators.map(w=>u(w.raw)),R={decorators:E.decorators,decoratorNames:k};return E.async===!0&&(R.async=!0),E.accessor&&(R.accessor=E.accessor),E.contextmanager===!0&&(R.contextmanager=!0),JSON.stringify(R)}function h(E,k){return(E.match(new RegExp(`\\${k}`,"g"))||[]).length}function m(E){let k=[],R=E,w=0,N=0,U=0,H=!1;do{let C=i[R].trim();if(k.push(C),w+=h(C,"(")-h(C,")"),N+=h(C,"[")-h(C,"]"),U+=h(C,"{")-h(C,"}"),H=C.endsWith("\\"),R+1>=i.length||w<=0&&N<=0&&U<=0&&!H)break;R+=1}while(!0);return{text:k.join(" "),endIndex:R}}let f=!1,b="",g=[],y=[];for(let E=0;E<i.length;E++){let k=i[E],R=k.trim();if(!R||R.startsWith("#"))continue;let w=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,N=R.match(w);if(N&&(this.currentRoutePrefix=N[2]),f){if(R.endsWith(b)||R.includes(b)){f=!1;let I=R.replace(b,"").trim();I&&g.push(I);let z=r[r.length-1];z.node&&(z.node.doc=g.join(`
725
+ `).trim()),g=[]}else g.push(R);continue}let U=k.search(/\S/),H=k.trim(),C=H.match(/^(['"]{3})/);if(C){let I=C[1],z=r[r.length-1];if(z.node&&!z.node.doc){if(H.substring(3).includes(I)){let j=H.replace(new RegExp(I,"g"),"").trim();z.node.doc=j}else{f=!0,b=I;let j=H.substring(3).trim();j&&g.push(j)}continue}}for(;r.length>1&&r[r.length-1].indent>=U;)r.pop();let M=r[r.length-1],D=M.type==="root"&&U===0;if(D&&/^__all__\s*=/.test(H)){let I=m(E),z=[],j=/['"]([^'"]+)['"]/g,Q=null;for(;Q=j.exec(I.text);)z.push(Q[1]);let fe={name:"__all__",kind:"ModuleExports",classification:"ExportList",signature:"__all__ = [...]",line:E+1,endLine:I.endIndex+1,doc:"",capabilities:JSON.stringify({exports:z}),members:[]};y.push(fe),t.push(fe),E=I.endIndex,o=[];continue}let B=/^([A-Z][A-Z0-9_]*)(?:\s*:\s*[^=]+)?\s*=/,L=D?H.match(B):null;if(L){let I=m(E),z=I.text.length>120?`${I.text.slice(0,117)}...`:I.text,j={name:L[1],kind:"VariableDeclaration",classification:"Constant",signature:z,line:E+1,endLine:I.endIndex+1,doc:"",capabilities:"{}",members:[]};y.push(j),t.push(j),E=I.endIndex,o=[];continue}let A=H.match(p);if(A){o.push({raw:A[1].trim(),line:E+1});continue}let $=H.match(a);if($){let I=$[1],z={name:I,kind:"ClassDeclaration",classification:"Class",signature:`class ${I}`,line:E+1,endLine:E+1,doc:"",capabilities:d({decorators:o}),members:[]};y.push(z),M.node?(M.node.members||(M.node.members=[]),M.node.members.push(z)):t.push(z),r.push({indent:U,name:I,type:"class",node:z}),o=[];continue}let W=H.match(l);if(W){let I=!!W[1],z=W[1]||W[2],j=M.type==="class",Q=o.some(K=>/(?:^|\.)contextmanager$/.test(K.raw.trim())),fe;o.some(K=>K.raw.trim()==="property")&&(fe="getter");for(let K of o){let ae=K.raw.trim().match(/^[a-zA-Z_][a-zA-Z0-9_]*\.(setter|deleter)$/);if(ae){fe=ae[1];break}}let Ce=!1,Ie={};for(let K of o)if(K.raw.match(/(?:app|router)\.(get|post|put|delete|patch|websocket)/)){Ce=!0;let at=["get","post","put","delete","patch","websocket"].find(je=>K.raw.toLowerCase().includes(`.${je}`))?.toUpperCase()||"GET",yt=K.raw.match(/['"]([^'"]+)['"]/),Ue=yt?yt[1]:"/";if(this.currentRoutePrefix){let je=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,Nt=Ue.startsWith("/")?Ue:`/${Ue}`;Ue=je+Nt}Ie={type:"route",method:at,path:Ue}}if(Ce){let K=Ie.path||"",ae=Ie.method==="WEBSOCKET",at={name:K||z,kind:ae?"WebSocket Route":"HTTP Route",classification:"Service Boundary",signature:`Function: ${z}`,line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({handler:j?`${M.name}.${z}`:z,async:I,...Ie})};y.push(at),t.push(at),n.push({type:ae?"websocket_route":"api_route",name:K,direction:"consume",line:E+1,snippet:H})}for(let K of o){let ae=K.raw.match(/(?:^|\.)receiver\s*\(\s*([a-zA-Z0-9_\.]+)/);ae&&n.push({type:"signal",name:ae[1].split(".").pop()||ae[1],direction:"consume",line:K.line,snippet:`@${K.raw}`})}let gt=o.some(K=>K.raw==="staticmethod"),he=o.some(K=>K.raw==="classmethod"),Ne=`${I?"async ":""}${j?(gt?"@staticmethod ":he?"@classmethod ":"")+M.name+".":""}${z}`,Pe=!!fe,Ee={name:z,kind:Pe?"PropertyDeclaration":I&&j?"AsyncMethodDeclaration":I?"AsyncFunctionDeclaration":j?"MethodDeclaration":"FunctionDeclaration",classification:Pe?"Property":j?gt||he?"Static Method":"Method":"Function",signature:Ne,line:E+1,endLine:E+1,doc:"",capabilities:d({decorators:o,async:I,accessor:fe,contextmanager:Q}),members:[]};y.push(Ee),M.node?(M.node.members||(M.node.members=[]),M.node.members.push(Ee)):t.push(Ee),r.push({indent:U,name:z,type:"function",node:Ee}),o=[];continue}let J=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,O=H.match(J);if(O){let I=O[1].replace(/^\^/,""),z={name:I,kind:"HTTP Route",classification:"Service Boundary",signature:H.trim(),line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:I})};y.push(z),t.push(z),n.push({type:"api_route",name:I,direction:"consume",line:E+1,snippet:H});continue}let S=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,v=H.match(S);if(v){let I=v[1].toUpperCase(),z=v[2].trim();(z.startsWith("'")&&z.endsWith("'")||z.startsWith('"')&&z.endsWith('"'))&&(z=z.substring(1,z.length-1)),n.push({type:"api_route",name:z,direction:"produce",line:E+1,snippet:H,method:I,url:z})}let T=H.match(c);if(T){let I=T[1]||T[2],z={name:I,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${I}`,line:E+1,endLine:E+1,doc:"",capabilities:JSON.stringify({type:"import",module:I})};y.push(z),t.push(z),o=[];continue}o=[],M.node&&(M.node.endLine=E+1)}return{nodes:y,events:n}}};function vp(s,e){let t=0,n=!1;for(let i=e;i<s.length;i++){let r=s[i];for(let o of r)if(o==="{")t++,n=!0;else if(o==="}"&&(t--,n&&t<=0))return i+1;if(!n&&i>e&&/[;}]$/.test(r.trim()))return i+1}return Math.min(s.length,e+41)}var Do=[{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 Rp(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 bi=class{phpParser=new gi;pythonParser=new yi;treeSitterParser=new hi;supports(e){return Do.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=Ls.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"),p=this.phpParser.parse(t,c);i=p.nodes,r=p.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) ",p=i.filter(m=>m.classification!=="Dependency"),u=i.filter(m=>m.classification==="Dependency"),d=Rp(n,i),h=xn({classification:c,capabilities:d,exports:p.map(m=>({name:m.name,kind:m.kind,classification:m.classification})),fileName:Ls.basename(e)});return{exports:p,imports:u.map(m=>({module:m.name,name:m.name,kind:m.kind,classification:m.classification})),events:r,classification:c,summary:h||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Do.find(c=>c.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};let a=t.split(`
726
+ `);for(let c of o.rules){c.regex.lastIndex=0;let p;for(;(p=c.regex.exec(t))!==null;){let u=c.onMatch(p),d=t.substring(0,p.index).split(`
727
+ `).length,h=vp(a,d-1);i.push({name:u.name||"anonymous",kind:u.kind||"Unknown",classification:u.classification||"Other",signature:u.signature||p[0],line:d,endLine:h,doc:"",capabilities:JSON.stringify(u.meta||{})})}}let l=xn({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:i.map(c=>({name:c.name,kind:c.kind,classification:c.classification})),fileName:Ls.basename(e)});return{exports:i,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:l||"Module",parseStatus:i.length>0?"success":"partial"}}};G();import*as Ms from"@swc/core";function Oo(s){if(!s||typeof s!="object")return!1;let e=s;return typeof e.parse=="function"&&typeof e.parseSync=="function"}function Tp(){if(Oo(Ms))return Ms;let s=Ms;if(Oo(s.default))return s.default;throw new Error("SWC runtime unavailable: couldn't resolve parse/parseSync from @swc/core exports")}var Fo=Tp();function $s(s,e,t){return Fo.parse(s,e,t)}function _i(s,e,t){return Fo.parseSync(s,e,t)}var As=new bi;async function wn(s){let e=Ho.extname(s);if(As.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=await Wo.promises.readFile(s,"utf-8");return{...await As.parse(s,r),content:r}}catch(r){return x.error({filePath:s,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:r.message}}let t;try{t=await Wo.promises.readFile(s)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),i=vo(n);try{let r=s.endsWith(".tsx"),o=s.endsWith(".d.ts")||s.endsWith(".d.tsx"),a,l={syntax:"typescript",tsx:r,decorators:!0,comments:!0};if(o)try{a=_i(n,l)}catch{a=_i(n,{...l,isModule:!1})}else a=_i(n,l);let c=a.span.start,p=Ro(t),u=ko(n),d=R=>To(R,c,t),h=Io(a.body),m=$o(a.body);m.length>0&&x.debug({filePath:s,count:m.length},"Extracted type references"),m.forEach(R=>{h.push({module:"__type_reference__",name:R})});let f=Lo(a.body,c,t,n,i,u,s,d,p),b=Mo(a.body,c,t,i,d,p),g=fi(s,"","Module"),E=u.length>0&&n.slice(0,u[0].start).trim().length===0?u[0].text:f.find(R=>R.doc)?.doc||"",k=Co(E);if(!k&&f.length>0){let R=tn(n);k=xn({classification:g,capabilities:R,exports:f.map(w=>({name:w.name,kind:w.kind,classification:w.classification})),fileName:Ho.basename(s)})}return{exports:f,imports:h,events:b,classification:g,summary:k,content:n,parseStatus:"success"}}catch(r){x.warn({filePath:s,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=await As.parse(s,n);return{...o,content:n,classification:o.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return x.error({filePath:s,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}G();import Bs from"p-limit";dt();import Us from"path";import du from"fs";import mu from"os";import Qe from"path";import sn from"fs";import{loadConfig as Ip,createMatchPath as Lp}from"tsconfig-paths";import wt from"path";import vn from"fs";var vt=class extends Error{constructor(t,n,i){super(n);this.code=t;this.cause=i;this.name="FileSystemError"}};function zo(s){let e;try{e=vn.statSync(s).isDirectory()?s:wt.dirname(s)}catch(t){throw t.code==="ENOENT"?new vt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new vt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new vt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==wt.dirname(e);){let t=wt.join(e,"tsconfig.json");if(vn.existsSync(t))return e;e=wt.dirname(e)}return null}function Bo(s){let e;try{e=vn.statSync(s).isDirectory()?s:wt.dirname(s)}catch(t){throw t.code==="ENOENT"?new vt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new vt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new vt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==wt.dirname(e);){let t=wt.join(e,"package.json");if(vn.existsSync(t))try{if(JSON.parse(vn.readFileSync(t,"utf8")).workspaces)return e}catch{}e=wt.dirname(e)}return null}import nn from"path";import Wt from"fs";function Uo(s,e){let t=new Map,n=e.workspaces||[];for(let i of n){let r=i.replace("/*",""),o=nn.join(s,r);if(!Wt.existsSync(o))continue;let a=Wt.readdirSync(o);for(let l of a){let c=nn.join(o,l,"package.json");if(Wt.existsSync(c))try{let p=JSON.parse(Wt.readFileSync(c,"utf8"));p.name&&t.set(p.name,{name:p.name,path:nn.dirname(c),main:p.main||"dist/index.js"})}catch{}}}return t}function jo(s){let e=new Map;try{let t=JSON.parse(Wt.readFileSync(s,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[i,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),a=nn.dirname(s),l=nn.resolve(a,o),c=nn.join(l,"package.json");if(Wt.existsSync(c))try{let p=JSON.parse(Wt.readFileSync(c,"utf8"));e.set(i,{name:i,path:l,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import Go from"path";import Ke from"fs";var kp=[".ts",".tsx",".d.ts",".js",".jsx"];function Rt(s){let e=Go.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(Ke.existsSync(r)&&Ke.statSync(r).isFile())return r}if(Ke.existsSync(s)&&Ke.statSync(s).isFile())return s}if(Ke.existsSync(s)&&Ke.statSync(s).isFile())return s;for(let t of kp){let n=s+t;if(Ke.existsSync(n)&&Ke.statSync(n).isFile())return n}if(Ke.existsSync(s)&&Ke.statSync(s).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=Go.join(s,"index"+t);if(Ke.existsSync(n))return n}return""}import{builtinModules as Cp,createRequire as jg}from"node:module";var Vg=new Set(Cp.map(s=>s.replace(/^node:/,"")));var Si=new Map;function Ei(s){let e=zo(s);if(!e)return null;if(Si.has(e))return Si.get(e)||null;let t=Ip(e);if(t.resultType==="failed")return Si.set(e,null),null;let n=t,i=n.absoluteBaseUrl;!i&&n.paths&&Object.keys(n.paths).length>0&&(i=n.configFileAbsolutePath?Qe.dirname(n.configFileAbsolutePath):e);let r=Lp(i,n.paths,n.mainFields,n.addMatchAll),o=Bo(e),a=new Map;if(o){let u=Qe.join(o,"package.json");if(sn.existsSync(u))try{let d=JSON.parse(sn.readFileSync(u,"utf8"));a=Uo(o,d)}catch{}}let l=Qe.join(e,"package.json");sn.existsSync(l)&&jo(l).forEach((d,h)=>a.set(h,d));let c={baseUrl:i||"",paths:n.paths,matchPath:r,workspacePackages:a,imports:new Map},p=Qe.join(e,"package.json");if(sn.existsSync(p))try{let u=JSON.parse(sn.readFileSync(p,"utf8"));if(u.imports){for(let[d,h]of Object.entries(u.imports))if(typeof h=="string"||typeof h=="object"&&h!==null){let m=h;Array.isArray(h)&&(m=h[0]),typeof m=="object"&&(m=m.default||m.node),typeof m=="string"&&c.imports.set(d,m)}}}catch{}return Si.set(e,c),c}function Ht(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=Ht(i,e,t);if(r)return r}}if(s.startsWith(".")){let i=Qe.dirname(e),r=Qe.resolve(i,s);return Rt(r)}let n=Ei(e);if(n){let i=n.matchPath(s);if(i)return Rt(i);if(!s.startsWith("@")||s.startsWith("@/")){let o=Qe.resolve(n.baseUrl,s),a=Rt(o);if(a)return a}for(let[o,a]of n.imports.entries())if(o.includes("*")){let l="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",c=new RegExp(l),p=s.match(c);if(p){let u=p[1],d=a.replace("*",u),h=Qe.resolve(n.baseUrl,d);return Rt(h)}}else if(o===s){let l=Qe.resolve(n.baseUrl,a);return Rt(l)}let r=n.workspacePackages.get(s);if(r){let o=Qe.join(r.path,"src/index.ts");if(sn.existsSync(o))return o;let a=Qe.join(r.path,r.main),l=Rt(a);if(l)return l}}return""}import Mp from"fs";import $p from"path";import Vo from"js-yaml";function qo(s){let e=$p.basename(s),t=Mp.readFileSync(s,"utf8"),n=[];if(e.endsWith(".prisma"))return{...Dp(t,s),content:t};if(e.endsWith(".graphql")||e.endsWith(".gql"))return{...Op(t,s),content:t};let i="Configuration";return e==="lerna.json"?{...Wp(t,s),content:t}:e==="turbo.json"?{...Hp(t,s),content:t}:e==="pnpm-workspace.yaml"?{...zp(t,s),content:t}:(e.includes("Dockerfile")?(i="Infrastructure (Docker) ",Ap(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(i="Infrastructure (YAML) ",Np(t,n)):e.startsWith(".env")?(i="Configuration (Env) ",Pp(t,n)):e==="package.json"&&(i="Project Manifest",Fp(t,n)),{configs:n,classification:i,content:t})}function Ap(s,e){let t=s.split(`
728
+ `);for(let n of t){let i=n.trim();if(i.startsWith("FROM "))e.push({key:"base_image",value:i.substring(5).trim(),kind:"Image"});else if(i.startsWith("EXPOSE "))e.push({key:"port",value:i.substring(7).trim(),kind:"Port"});else if(i.startsWith("ENV ")){let r=i.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],a=r.slice(1).join("= ").trim()||"undefined",l="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(l="Service"),e.push({key:o,value:a,kind:l})}}}}function Np(s,e){try{let t=Vo.load(s);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[i,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${i}`,value:i,kind:"Service"}),o.image&&e.push({key:`service:${i}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(a=>{e.push({key:`service:${i}:port`,value:String(a),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(a=>{let[l,...c]=a.split("= ");l&&c.length>0&&e.push({key:`service:${i}:env:${l}`,value:c.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[a,l]of Object.entries(o.environment))e.push({key:`service:${i}:env:${a}`,value:String(l),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(a=>{e.push({key:`service:${i}:depends_on`,value:a,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let a of Object.keys(o.depends_on))e.push({key:`service:${i}:depends_on`,value:a,kind:"Dependency"})}let n=(i,r="")=>{if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,a]of Object.entries(i)){let l=r?`${r}.${o}`:o;if(t.services&&(l.startsWith("services.")||l==="services")){a&&typeof a=="object"&&!Array.isArray(a)&&n(a,l);continue}if(a&&typeof a=="object"&&!Array.isArray(a))n(a,l);else if(a!=null){let c=String(a);if(c==="[object Object]"||c.includes("[object Object]"))continue;let p="Env",u=/^[a-z0-9_-]+$/i.test(c),d=c.includes("://");o.toLowerCase().includes("service")&&(u||d)&&(p="Service"),o.toLowerCase().includes("image")&&(p="Image"),o.toLowerCase().includes("port")&&(p="Port"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&d&&(p="Service"),e.push({key:l,value:c.length>200?c.substring(0,197)+"...":c,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 Pp(s,e){let t=s.split(`
729
+ `);for(let n of t){let i=n.trim();if(i&&!i.startsWith("#")){let r=i.split("=");if(r[0]){let o=r[0].trim(),a=r.slice(1).join("=");a=a.trim().replace(/^['"](.*)['"]$/,"$1");let l="Env",c=a.includes("://");(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&c&&(l="Service"),e.push({key:o,value:a,kind:l})}}}}function Dp(s,e){let t=[],n="Contract (Prisma) ",i=/^model\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(s))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let a=/provider\s*=\s*"([^"]+)"/,l=s.match(a);return l&&t.push({key:"datasource_provider",value:l[1],kind:"Database Config"}),{classification:n,configs:t,content:s}}function Op(s,e){let t=[],n="Contract (GraphQL) ",i=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;){let o=r[0],a="GraphQL Type";o.startsWith("input")&&(a="GraphQL Input"),o.startsWith("interface")&&(a="GraphQL Interface"),o.startsWith("enum")&&(a="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:a})}return{classification:n,configs:t,content:s}}function Fp(s,e){try{let t=JSON.parse(s);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"Env"}),t.workspaces){let r=Array.isArray(t.workspaces)?t.workspaces.join("",""):JSON.stringify(t.workspaces);e.push({key:"workspaces",value:r,kind:"Env"})}if(t.scripts){let r=["start","dev","build","test","docker"];for(let o of Object.keys(t.scripts))r.some(a=>o.includes(a))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},i=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(i.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Dependency"})}}catch{}}function Wp(s,e){let t=[],n="Monorepo (Lerna) ";try{let i=JSON.parse(s);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),i.version&&t.push({key:"lerna_version",value:i.version,kind:"Monorepo"}),i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),i.npmClient&&t.push({key:"npm_client",value:i.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:s}}function Hp(s,e){let t=[],n="Monorepo (Turborepo) ";try{let i=JSON.parse(s);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),i.pipeline)for(let r of Object.keys(i.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=i.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(i.tasks)for(let r of Object.keys(i.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:s}}function zp(s,e){let t=[],n="Monorepo (pnpm) ";try{let i=Vo.load(s);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),i&&i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n,content:s}}Y();Ve();import{execSync as zt}from"child_process";import Rn from"path";import Ns from"fs";function be(s){try{if(!Ns.existsSync(Rn.join(s,".git")))return null;let e=zt("git rev-parse --abbrev-ref HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return e==="HEAD"?zt("git rev-parse --short HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():e.replace(/[\/\\:*"<>|?]/g,"-")}catch{return null}}function Ze(s){try{return Ns.existsSync(Rn.join(s,".git"))?zt("git rev-parse HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function Yo(s,e=50){try{let t=zt(`git rev-list --max-count=${e} HEAD`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return t?t.split(`
730
+ `):[]}catch{return[]}}function Ko(s,e,t){try{return zt(`git merge-tree --write-tree ${e} ${t}`,{cwd:s,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}var Bp=new Set([".ts",".tsx",".yaml",".yml",".php",".py",".go",".prisma",".graphql",".gql"]),Up=new Set(["package.json","lerna.json","turbo.json","pnpm-workspace.yaml"]),jp=new Set(["node_modules",".git","dist","build","vendor",".next",".cache","coverage"]);function Jo(s){let e=s.split("/");for(let i of e)if(jp.has(i))return!1;if(s.endsWith(".min.js"))return!1;let t=Rn.basename(s);if(t.startsWith("Dockerfile")||t.startsWith(".env")||Up.has(t))return!0;let n=Rn.extname(t).toLowerCase();return Bp.has(n)}function Gp(s){let e=s.trim(),t=e.indexOf(" -> ");if(t!==-1)return e.substring(t+4);let n=e.split(/\s+/);return n.length>=2?n[n.length-1]:e}function Qo(s,e){try{if(!Ns.existsSync(Rn.join(s,".git")))return!0;let t=Ze(s);if(!t)return!0;if(e&&e!==t){let i=zt(`git diff --name-only ${e} ${t}`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(i&&i.split(`
731
+ `).some(r=>r&&Jo(r)))return!0}let n=zt("git status --porcelain",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return n?n.split(`
732
+ `).some(i=>i?Jo(Gp(i)):!1):!1}catch{return!0}}Y();G();import{execSync as Zo}from"child_process";var Bt=x.child({module:"nano-repair"}),rt=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:i}=F.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};Bt.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let i of e){let r=this.exports.findByNameAndFile(i.symbol_name,i.file_path);if(r.length>0){let a=r.find(l=>l.signature===i.signature)||r[0];this.intentLogs.update(i.id,{symbol_id:a.id}),Bt.info({logId:i.id,symbol:i.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(i.symbol_name);if(o.length>0){let a=o.filter(l=>l.file_path!==i.file_path);if(a.length>0){let l=a.find(c=>c.signature===i.signature)||a[0];this.intentLogs.update(i.id,{symbol_id:l.id,file_path:l.file_path}),Bt.info({logId:i.id,symbol:i.symbol_name,oldPath:i.file_path,newPath:l.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&Bt.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(e={}){let t=e.enableContextPivot===!0,n=e.enableMergeSentinel===!0,i="HEAD";try{i=Zo("git rev-parse --abbrev-ref HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return{suspended:0,resumed:0,completed:0,contextPivotEnabled:t,mergeSentinelEnabled:n}}if(!i)return{suspended:0,resumed:0,completed:0,contextPivotEnabled:t,mergeSentinelEnabled:n};let r=0,o=0;if(t){let l=this.missions.findActive();for(let c of l)c.git_branch&&c.git_branch!==i&&(this.missions.updateStatus(c.id,"suspended"),Bt.info({missionId:c.id,branch:c.git_branch,current:i},"Context Pivot: Suspended mission"),r++);o=this.missions.resumeByBranch(i)}let a=0;if(n){let l=[];try{l=Zo(`git branch --merged "${i}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
733
+ `).map(p=>p.trim().replace(/^\* /,"")).filter(p=>p&&p!==i)}catch{}if(l.length>0){let c=this.missions.findMergedMissions(i,l);for(let p of c)this.missions.updateStatus(p.id,"completed"),Bt.info({missionId:p.id,branch:p.git_branch},"Merge Sentinel: Auto-completed mission"),a++}}return(r>0||o>0||a>0)&&Bt.info({suspended:r,resumed:o,completed:a},"Git-Native Lifecycle Sync complete"),{suspended:r,resumed:o,completed:a,contextPivotEnabled:t,mergeSentinelEnabled:n}}};G();Dt();import{Worker as qp}from"node:worker_threads";import{cpus as Vp}from"node:os";import{fileURLToPath as Jp}from"node:url";import{dirname as Yp,join as Kp}from"node:path";import{existsSync as Qp}from"node:fs";var Xo=Jp(import.meta.url),Zp=Yp(Xo),Xp=Xo.endsWith(".ts");function eu(){if(Xp)return null;let s=Kp(Zp,"worker.js");return Qp(s)?s:Le("dist/logic/parser/worker.js")}var Ps=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(4,Vp().length-1)),this.initTimeout=e.initTimeout??3e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{x.info({numWorkers:this.numWorkers},"Initializing parser worker pool");let t=new Promise((n,i)=>{e=setTimeout(()=>i(new Error(`Parser pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0;return}this.initialized=!0,x.info({numWorkers:this.workers.length},"Parser worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=eu();if(!e)throw new Error("Parser worker pool not available in development mode (tsx). Use main-thread fallback.");x.debug({workerPath:e},"Resolved parser worker path");let t=[];for(let n=0;n<this.numWorkers;n++)t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Parser worker ${t} initialization timed out`))},this.initTimeout),o=new qp(e,{execArgv:process.execArgv}),a={worker:o,busy:!1,currentTaskId:null};o.on("message",l=>{if(l.type==="ready"){if(clearTimeout(r),this.shutdownRequested){o.terminate().catch(()=>{}),n();return}this.workers.push(a),x.debug({workerIndex:t},"Parser worker ready"),n()}else l.type==="result"&&l.id?this.handleTaskComplete(a,l.id,l.result):l.type==="error"&&l.id&&this.handleTaskError(a,l.id,new Error(l.error||"Unknown error"))}),o.on("error",l=>{if(clearTimeout(r),x.error({err:l,workerIndex:t},"Parser worker error"),a.currentTaskId&&this.handleTaskError(a,a.currentTaskId,l),!this.initialized){i(l);return}let c=this.workers.indexOf(a);c!==-1&&this.workers.splice(c,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{x.error({err:p},"Failed to replace crashed parser worker")})}),o.on("exit",l=>{l!==0&&!this.shutdownRequested&&x.warn({workerIndex:t,code:l},"Parser worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"parse",id:t.id,filePath:t.filePath}))}async parseFile(e){return this.initialized||await this.initialize(),new Promise((t,n)=>{let r={id:`parse_${++this.taskIdCounter}`,filePath:e,resolve:t,reject:n};this.taskQueue.push(r),this.processQueue()})}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}x.info({numWorkers:this.workers.length},"Shutting down parser worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,this.initPromise=void 0,x.info("Parser worker pool shutdown complete")}},rn=null;function ea(s){return rn||(rn=new Ps(s)),rn}async function ta(){rn&&(await rn.shutdown(),rn=null)}Y();G();jt();Ds();Os();Fs();import{execSync as wa}from"child_process";var Li=x.child({module:"heritage-analyzer"}),Mi=class{repos;repoPath;constructor(e){this.repos=F.getInstance(e),this.repoPath=e}analyzeHeritage(e=20){try{Li.info({limit:e},"Analyzing repository heritage...");let t=wa(`git log -n ${e} --pretty=format:"%H|%at|%an|%s"`,{cwd:this.repoPath,encoding:"utf-8"});if(!t)return;let n=t.split(`
734
+ `).filter(Boolean);for(let i of n){let[r,o,a,l]=i.split("|"),c=this.analyzeCommitImpact(r);if(c.significant){let p=Array.from(c.layers).join(", "),u=`Heritage: ${l} (by ${a}). Touched ${c.fileCount} files across [${p}].`;this.repos.intentLogs.importHeritage(u,r,parseInt(o,10),.7),Li.debug({sha:r,subject:l},"Logged heritage move")}}Li.info("Heritage analysis complete.")}catch(t){Li.warn({err:t.message},"Failed to run heritage analysis")}}analyzeCommitImpact(e){let t=new Set,n=0;try{let r=wa(`git diff-tree --no-commit-id --name-only -r ${e}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
735
+ `).filter(Boolean);n=r.length;for(let l of r){let c=this.classifyPathOnly(l);c!=="Unknown"&&t.add(c)}let o=t.has("Entry")||t.has("Data")||t.has("Infrastructure"),a=t.size>=2||n>5;return{significant:o||a,layers:t,fileCount:n}}catch{return{significant:!1,layers:t,fileCount:0}}}classifyPathOnly(e){let t=e.startsWith("/")?e:"/"+e;return Ws.some(n=>n.test(t))?"Test":wi.some(n=>n.test(t))||xi.some(n=>n.test(t))?"Entry":Tn.some(n=>n.test(t))?"Data":Ri.some(n=>n.test(t))?"Utility":Ti.some(n=>n.test(t))?"Entry":ki.some(n=>n.test(t))?"Data":Ci.some(n=>n.test(t))?"Entry":Ii.some(n=>n.test(t))?"Data":Hs.some(n=>n.test(t))?"Infrastructure":/\.(service|logic|usecase|interactor|manager)\.(ts|js|php|py)$/i.test(t)||vi.some(n=>n.test(t))?"Logic":"Unknown"}};dt();Dt();import{spawn as su}from"node:child_process";import zs from"node:os";import{resolve as ru}from"node:path";import{existsSync as va}from"node:fs";import{fileURLToPath as ou}from"node:url";import{dirname as au}from"node:path";var Ra=ou(import.meta.url),cu=au(Ra),lu=zs.constants.priority.PRIORITY_LOWEST??zs.constants.priority.PRIORITY_LOW;function pu(){if(Ra.endsWith(".ts"))return null;let s=ru(cu,"../../entry/ember/index.js");if(va(s))return s;let e=Le("dist/entry/ember/index.js");return va(e)?e:null}function Ta(s){try{let t=Oe(s).prepare("SELECT key, value FROM ember_state WHERE key IN ('status','progress','pid')").all(),n=new Map(t.map(i=>[i.key,i.value??""]));return{status:n.get("status")??"idle",progress:n.get("progress")??"0/0",pid:n.get("pid")??null}}catch{return{status:"idle",progress:"0/0",pid:null}}}function uu(s,e){let t=Oe(s);t.transaction(()=>{let n=t.prepare("INSERT OR REPLACE INTO ember_state (key, value, updated_at) VALUES (?, ?, unixepoch())");n.run("pid",String(e)),n.run("status","running"),n.run("repo_path",s)})()}function ka(s){let{pid:e}=Ta(s);if(!e)return!1;let t=parseInt(e,10);if(!Number.isFinite(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function Ca(s){let e=pu();if(!e)return;let t=su(process.execPath,[e,s],{detached:!0,stdio:"ignore",env:{...process.env,EMBER_MODE:"1"}});if(t.pid!=null){try{zs.setPriority(t.pid,lu)}catch{}t.unref(),uu(s,t.pid)}}function $i(s){let{status:e,progress:t}=Ta(s);return{status:e,progress:t}}var fu=mu.cpus().length||4,hu=di.DEFAULT_CONCURRENCY;function Ma(s,e=[]){if(!Array.isArray(s))return e;for(let t of s)!t||typeof t!="object"||(e.push(t),Array.isArray(t.members)&&t.members.length>0&&Ma(t.members,e));return e}function Ia(s){if(typeof s!="number"||!Number.isFinite(s))return null;let e=Math.trunc(s);return e>0?e:null}function $a(s){let e=typeof s?.content=="string"&&s.content.length>0?s.content.split(`
736
+ `).length:0,t=Ma(s?.exports),n=0,i=0,r=0,o=0;for(let a of t){let l=Ia(a?.line??a?.start_line),c=Ia(a?.endLine??a?.end_line??l);if(!l||!c||c<l||e>0&&c>e){i++;continue}n++,c>l&&o++,e>0&&l===e&&c===e&&r++}return{total:t.length,valid:n,invalid:i,eofCollapsed:r,multiLine:o,lineCount:e}}function gu(s){let e=$a(s);if(e.total===0||e.lineCount===0)return!1;if(e.invalid>0)return!0;let t=e.eofCollapsed/e.total;return e.eofCollapsed>=3&&t>=.5||e.total>=2&&e.eofCollapsed===e.total}function La(s){let e=$a(s);return e.valid*2+e.multiLine*2-e.eofCollapsed*3-e.invalid*4}async function se(s,e=hu,t=!1,n=!0,i){let r=F.getInstance(s),o=r.files.database,a=lt(s),l=a.concurrency??e;if(uo(),!t&&ut(s)){let g=yn(s),y=Ze(s);if(g&&!Qo(s,g))return Rs(),x.debug({repoPath:s,commit:y},"Index is current, skipping re-index (fast-path)"),o}Ei(s);let c=r.files.findAll(),p=new Map(c.map(g=>[g.path,{mtime:g.mtime,hash:g.content_hash}])),u=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let d=await wo(s,a.ignore),h=new Map(d.map(g=>[g.path,g.mtime])),m=c.filter(g=>!h.has(g.path)).map(g=>g.path),f=c.length===0,b=[];if(t||f)b.push(...d);else{let g=d.filter(R=>{let w=p.get(R.path);return!w||w.mtime!==R.mtime}),y=Bs(l*4),E=g.map(R=>y(async()=>{let w=p.get(R.path);if(!w||!w.hash)return R;try{let N=await du.promises.readFile(R.path,"utf8");return Mr(N,w.hash)?R:(r.files.updateMtime(R.path,R.mtime),null)}catch{return null}})),k=await Promise.all(E);b.push(...k.filter(R=>R!==null))}if(m.length===0&&b.length===0){Rs();let g=Ze(s);return fs(s,g||void 0),o}if(f?x.info({totalFiles:d.length},"Starting initial repository indexing..."):x.info({toDelete:m.length,toProcess:b.length},"Syncing repository updates..."),m.length>0&&r.files.deletePaths(m),b.length>0){fo(),n?(Jn(!0),Zt().initialize().catch(()=>{})):Jn(!1);let g=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,y=[],E=[];for(let L of b)g.test(Us.basename(L.path))?y.push(L):E.push(L);let k=0,R=b.length,w=!1,N=ea();try{await N.initialize(),w=!0,x.info({workers:N.workerCount},"Parser worker pool active")}catch(L){x.warn({err:L},"Parser worker pool failed to initialize, falling back to main-thread parsing"),w=!1}let U=async(L,A)=>{let $=A;if(w&&gu(A))try{let O=await wn(L.path);La(O)>La(A)&&(x.warn({filePath:L.path},"Detected suspicious worker parse ranges; using main-thread parse output"),$=O)}catch(O){x.warn({filePath:L.path,err:O instanceof Error?O.message:String(O)},"Main-thread parse retry failed after suspicious worker parse")}let W=$.imports?.map(O=>({...O,resolved_path:Ht(O.module,L.path,s)})),J=$.content?Kt($.content):null;return k++,(k%50===0||k===R)&&x.info({completed:k,total:R},"Parsing files..."),i?.({phase:"parse",current:k,total:R,message:`Parsing ${Us.basename(L.path)}`}),{meta:L,...$,imports:W,embedding:null,kind:"code",contentHash:J}},H;if(w)H=y.map(L=>N.parseFile(L.path).then(A=>U(L,A),A=>(k++,x.error({path:L.path,error:A},"Worker parse failed"),{meta:L,exports:[],imports:[],content:"",kind:"error"})));else{let L=f?Math.max(l,Math.min(fu-1,16)):l,A=Bs(L);H=y.map($=>A(async()=>{try{let W=await wn($.path);return U($,W)}catch(W){return k++,x.error({path:$.path,error:W},"Failed to parse file"),{meta:$,exports:[],imports:[],content:"",kind:"error"}}}))}let C=Bs(l),M=E.map(L=>C(async()=>{try{let A=qo(L.path),$=A.content?Kt(A.content):null;return k++,(k%50===0||k===R)&&x.info({completed:k,total:R},"Parsing configs..."),i?.({phase:"parse",current:k,total:R,message:`Parsing config ${Us.basename(L.path)}`}),{meta:L,...A,embedding:null,kind:"config",contentHash:$}}catch(A){return k++,x.error({path:L.path,error:A},"Failed to parse config"),{meta:L,exports:[],imports:[],content:"",kind:"error"}}}));x.info({total:R,codeFiles:y.length,configFiles:E.length,useParserPool:w},"Phase 1: Parsing all files...");let D=Date.now(),P=(await Promise.all([...H,...M])).filter(Boolean),B=Date.now()-D;if(Sn("parse",B),x.info({count:P.length,time:`${(B/1e3).toFixed(1)}s`},"Phase 1 complete"),w&&ta().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let L=[];P.forEach((v,T)=>{"summary"in v&&v.summary&&L.push({fileIdx:T,text:v.summary})}),x.info("Phase 2+3: Generating file-summary embeddings + persisting in parallel..."),i?.({phase:"embed",current:0,total:P.length,message:"Generating embeddings..."});let A=Date.now(),$=(async()=>{let v=[];return L.length>0&&(x.info({count:L.length}," \u2192 Generating file summary embeddings..."),v=await Ss(L.map(T=>T.text),256),x.info({count:L.length}," \u2713 File summaries complete")),v})();i?.({phase:"persist",current:0,total:P.length,message:"Saving to database..."});let W=Date.now();r.files.batchSaveIndexResults(P,s,Kt,Ht);let J=Date.now()-W;Sn("persist",J),x.info({time:`${(J/1e3).toFixed(1)}s`},"Structural persist complete");let O=await $,S=Date.now()-A;if(Sn("embed",S),x.info({time:`${(S/1e3).toFixed(1)}s`},"File-summary embeddings complete"),O.length>0){let v=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),T=o.transaction(z=>{for(let j of z)v.run(j.embedding?JSON.stringify(j.embedding):null,j.path)}),I=L.map((z,j)=>({path:P[z.fileIdx].meta.path,embedding:O[j]}));T(I),x.info({count:I.length},"File embedding column updated")}}else{i?.({phase:"persist",current:0,total:P.length,message:"Saving to database..."});let L=Date.now();r.files.batchSaveIndexResults(P,s,Kt,Ht),Sn("persist",Date.now()-L)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(f||b.length>0){let g=Ze(s);fs(s,g||void 0)}if(n&&!ka(s)&&Ca(s),(b.length>0||m.length>0)&&new rt(s).detectAndRepairShifts(),f||n)try{new Mi(s).analyzeHeritage(50)}catch(g){x.warn({err:g.message},"Heritage sync deferred")}return mo(Date.now()-u),i?.({phase:"complete",current:b.length,total:b.length,message:"Indexing complete"}),o}Y();async function Ai(s,e=di.DEFAULT_CONCURRENCY,t="detailed",n,i){x.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await se(s,e);let{files:r,exports:o,imports:a}=F.getInstance(s),l=n?r.findInSubPath(s,n):r.findAll(),c=lt(s),p=yu(),u=Aa.join(s,".gitignore");if(Na.existsSync(u)&&p.add(Na.readFileSync(u,"utf8")),c.ignore&&c.ignore.length>0&&p.add(c.ignore),p.add(ui),l=l.filter(y=>{let E=Aa.relative(s,y.path);return!p.ignores(E)}),x.info({count:l.length},"Fetching data from DB..."),t==="lite"){let y=l.map(E=>({path:E.path,mtime:E.mtime}));return pi(y,s,t,i)}if(t==="summaries"){let y=l.map(E=>({path:E.path,mtime:E.mtime,classification:E.classification||void 0,summary:E.summary||void 0}));return pi(y,s,t,i)}let d=l.map(y=>y.path),h=o.findByFiles(d),m=t==="detailed"?a.findByFiles(d):[],f=new Map;for(let y of h){let E=f.get(y.file_path)||[];E.push(y),f.set(y.file_path,E)}let b=new Map;for(let y of m){let E=b.get(y.file_path)||[];E.push(y),b.set(y.file_path,E)}let g=l.map(y=>{let k=(f.get(y.path)||[]).map(w=>({name:w.name,kind:w.kind,signature:w.signature,line:w.start_line}));t==="structure"?k=k.map(w=>({name:w.name,kind:w.kind,line:w.line})):t==="signatures"&&(k=k.map(w=>({name:w.name,kind:w.kind,signature:w.signature,line:w.line})));let R=[];return t==="detailed"&&(R=(b.get(y.path)||[]).map(N=>({module:N.module_specifier,resolved_path:N.resolved_path}))),{path:y.path,mtime:y.mtime,classification:y.classification||void 0,summary:y.summary||void 0,exports:k,imports:R.length>0?R:void 0,chunks:[]}});return x.info({count:g.length},"Building hierarchical project tree..."),pi(g,s,t,i)}async function Pa(s,e){let t=bu.resolve(s);try{await Z(async()=>{ge("\u{1F311} Liquid Shadow: Topological Mapping");let n=parseInt(e.depth,10),i=await Ai(t,n,"detailed",e.subPath);console.log(` ${_.bold("Root")}: ${_.cyan(t)}`),e.subPath&&console.log(` ${_.bold("Subpath")}: ${_.yellow(e.subPath)}`),console.log("");let r=o=>({name:o.name,info:o.type==="directory"?`${o.children?.length||0} items`:o.size,color:o.type==="directory"?"blue":"white",children:o.children?.map(r)});ws([r(i)]),console.log(""),Je("Mapping concluded.")})}finally{await ne(t)}}import Oa from"path";import _u from"fs";G();import me from"path";import js from"fs";var Ni=x.child({module:"path-resolver"}),kn=class{repoPath;constructor(e){this.repoPath=me.isAbsolute(e)?me.normalize(e):me.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw Ni.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(me.isAbsolute(e)?t=me.normalize(e):t=me.join(this.repoPath,e),t=me.normalize(t),!this.isWithinRoot(t))throw Ni.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 js.existsSync(t)?t:(Ni.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return Ni.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=me.resolve(e),n=me.resolve(this.repoPath),i=me.relative(n,t);if(i.startsWith("..")||me.isAbsolute(i))return!1;if(js.existsSync(t)){let o=js.realpathSync(t),a=me.relative(n,o);if(a.startsWith("..")||me.isAbsolute(a))return!1}return!0}catch{return!1}}getRelative(e){let t=me.normalize(e);return me.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return me.normalize(e)}static isPathWithinRoot(e,t){let n=me.resolve(e),i=me.resolve(t),r=me.relative(n,i);return r===""||!r.startsWith("..")&&!me.isAbsolute(r)}};function Da(s){return new kn(s)}async function Fa(s,e){let t=Oa.resolve(s);await Z(async()=>{if(ge("\u{1F311} Liquid Shadow: Intelligence Deployment"),console.log(` ${_.bold("Target")}: ${_.cyan(t)}`),console.log(` ${_.bold("Objective")}: ${e.output?_.magenta("Data Extraction"):_.green("Semantic Mapping")}`),console.log(""),!e.output){let i=Fe();i.start("Engaging intelligence engines...");let r="",o=a=>{if(a.phase!==r){r=a.phase;let l={scan:"\u{1F4E1} Scanning topography",parse:"\u{1F9E9} Parsing symbols",embed:"\u{1F9E0} Generating vectors",persist:"\u{1F4BE} Hardening index",complete:"\u{1F3C1} Mapping complete"}[a.phase]||a.phase;i.message(`${l}...`)}if(a.total>0&&a.current>0){let l=Math.round(a.current/a.total*100);i.message(`${r==="parse"?"Parsing":"Processing"}: ${a.current}/${a.total} (${l}%)`)}};try{await se(t,void 0,e.force,e.deep??!0,o),i.message("\u{1FA79} Running Nano-Repair healing...");let l=new rt(t).detectAndRepairShifts();i.stop("Intelligence mapping successfully concluded."),console.log(""),console.log(` ${_.bold("Next Steps:")}`),console.log(` ${_.dim("view your repo stats")} -> ${_.bold(_.cyan("liquid-shadow dashboard"))}`),console.log(` ${_.dim("start a chat search")} -> ${_.bold(_.cyan('liquid-shadow search-concept "your query"'))}`),console.log(""),Je("Liquid Shadow is online.")}catch(a){throw i.stop(`Operation failed: ${a.message}`),a}finally{await ne(t)}return}let n=Fe();n.start("Engaging intelligence engines...");try{let i=await Ai(t,5,e.level,e.subPath),r=Oa.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!kn.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");_u.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Data extraction saved: ${_.bold(_.cyan(r))}`),Je("Extraction complete.")}catch(i){throw n.stop(`Extraction failed: ${i.message}`),i}finally{await ne(t)}})}import{performance as Wa}from"perf_hooks";import Eu from"path";Y();async function Ha(s){let e=Eu.resolve(s);await Z(async()=>{console.log(`
737
+ ${_.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${_.gray("Repository: ")} ${e}`),console.log(` ${_.yellow("Starting fresh index (DB deleted)...")}
738
+ `);let t=Wa.now();try{await se(e,10,!0);let n=Wa.now()-t,i=F.getInstance(e),r=i.files.getCount(),o=i.exports.getCount(),a=i.exports.getWithEmbeddingsCount();ue("Benchmark Results",`${_.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
739
+ ${_.bold("Files Processed")}: ${_.cyan(r.toString())}
740
+ ${_.bold("Symbols Extracted")}: ${_.cyan(o.toString())}
741
+ ${_.bold("Symbols Embedded")}: ${_.cyan(a.toString())} (${(a/o*100).toFixed(1)}%)
663
742
  `+"\u2500".repeat(40)+`
664
- ${y.bold("Files/sec")}: ${y.green((r/(n/1e3)).toFixed(2))}
665
- ${y.bold("Symbols/sec")}: ${y.green((o/(n/1e3)).toFixed(2))}
666
- ${y.bold("ms per file")}: ${y.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
667
- Benchmark failed during execution:`,n),n}finally{await Q(e)}})}import xi from"path";import Ee from"path";import ks from"fs";var Gp=/[\x00-\x1f\x7f]/g,qp=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Rs(s){if(typeof s!="string")throw new Error("Invalid path: expected string");if(s.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(s.replace(Gp,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function Ei(s,e=4096){if(typeof s!="string")return"";let t=s.replace(qp,"").trim();return t.length>e?t.slice(0,e):t}Ze();function Vp(s){let e=Ee.isAbsolute(s)?Ee.normalize(s):Ee.resolve(process.cwd(),s),t=Ee.parse(e).root;for(;e!==t;){if(ks.existsSync(Ee.join(e,".liquid-shadow.db"))||ks.existsSync(Ee.join(e,".git"))||ks.existsSync(Ee.join(e,"package.json")))return e;let n=Ee.dirname(e);if(n===e)break;e=n}return null}function Ve(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=Rs(e)),t&&(t=Rs(t));let n;if(e)Ee.isAbsolute(e)||(e=Ee.resolve(process.cwd(),e)),n=e;else if(t){let o=Ee.resolve(process.cwd(),t);n=Vp(Ee.dirname(o))||process.cwd()}else n=process.cwd();n=Ee.normalize(n);let i=ca(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}V();q();import $t from"fs";import fe from"path";import{Visitor as Jp}from"@swc/core/Visitor.js";var Si=class extends Jp{calls=new Set;apiCalls=[];imports=new Map;axiosInstances=new Map([["axios",""],["http",""],["appApi",""],["restApi",""],["adminApi",""]]);visitImportDeclaration(e){let t=e.source.value;for(let n of e.specifiers)(n.type==="ImportDefaultSpecifier"||n.type==="ImportSpecifier")&&this.imports.set(n.local.value,t);return super.visitImportDeclaration(e)}visitCallExpression(e){if(e.callee.type==="Identifier"){let t=e.callee.value;this.calls.add(t),(t==="axios"||t==="http")&&e.arguments.length>0&&this.extractApiCallFromConfig(e.arguments[0].expression)}else if(e.callee.type==="MemberExpression"){let t=e.callee.property.value,n=r=>{if(!r)return"?";if(r.type==="Identifier")return r.value;if(r.type==="ThisExpression")return"this";if(r.type==="MemberExpression"){let o=n(r.object),a=r.property.value||"?";return`${o}.${a}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},i=n(e.callee.object);if(i!=="?"&&t){if(this.calls.add(`${i}.${t}`),i==="axios"||i==="http"||this.axiosInstances.has(i)){let r=this.axiosInstances.get(i)||"";this.extractApiCall(t,e.arguments,r)}if((i.toLowerCase().includes("pubsub")||i==="pubSubClient"||i.endsWith(".pubSubClient"))&&t!=="subscribe"){let r=t;if((t==="publish"||t==="publishMessage"||t==="publishTaskByNameAndPayload")&&e.arguments.length>0)for(let o of e.arguments){let a=o.expression;if(a.type==="ObjectExpression"){let c=a.properties.find(l=>l.key?.type==="Identifier"&&(l.key.value==="action"||l.key.value==="type")||l.key?.type==="StringLiteral"&&(l.key.value==="action"||l.key.value==="type"));if(c&&c.value?.type==="StringLiteral"){r=c.value.value;break}}if(a.type==="CallExpression"&&a.callee.type==="MemberExpression"&&a.callee.object.value==="JSON"&&a.callee.property.value==="stringify"&&a.arguments.length>0){let c=a.arguments[0].expression;if(c.type==="ObjectExpression"){let l=c.properties.find(p=>p.key?.type==="Identifier"&&(p.key.value==="action"||p.key.value==="type")||p.key?.type==="StringLiteral"&&(p.key.value==="action"||p.key.value==="type"));if(l&&l.value?.type==="StringLiteral"){r=l.value.value;break}}}}this.apiCalls.push({method:"PUBSUB",url:r})}}}return e.callee.type==="Identifier"&&e.callee.value==="fetch"&&this.extractApiCall("GET",e.arguments),super.visitCallExpression(e)}visitNewExpression(e){return e.callee.type==="Identifier"&&this.calls.add(e.callee.value),super.visitNewExpression(e)}visitVariableDeclarator(e){if(e.init&&e.init.type==="CallExpression"){let t=e.init.callee;if(t.type==="MemberExpression"&&t.property.value==="create"&&t.object.value==="axios"){let i=e.init.arguments[0]?.expression;if(i&&i.type==="ObjectExpression"){let r=i.properties.find(o=>o.key.value==="baseURL");if(r){let o="?";r.value.type==="StringLiteral"?o=r.value.value:r.value.type==="Identifier"&&(o=`\${${r.value.value}}`),e.id.type==="Identifier"&&this.axiosInstances.set(e.id.value,o)}}}}return super.visitVariableDeclarator(e)}extractApiCallFromConfig(e){if(e&&e.type==="ObjectExpression"){let t=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="url"||i.key.type==="StringLiteral"&&i.key.value==="url"),n=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="method"||i.key.type==="StringLiteral"&&i.key.value==="method");if(t&&t.value){let i=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:i.toUpperCase(),url:r})}}}resolveUrlValue(e){return e.type==="StringLiteral"?e.value:e.type==="TemplateLiteral"?e.quasis.map(t=>t.cooked).join("*"):"?"}visitTsType(e){return e}extractApiCall(e,t,n=""){if(t.length>0){let i=t[0].expression,r=this.resolveUrlValue(i);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},jt=class{calls=new Set;apiCalls=[];imports=new Map;visit(e,t){if(t===".php"){let n=/(?:([a-zA-Z0-9_$->:\(\)]*)?(?:->|::))?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&!["$this","self","parent"].includes(r)&&this.calls.add(`${r}${r.includes("::")?"::":"->"}${o}`),["save","delete","update","create","first","all","where","get","find"].includes(o)&&r&&!["Log","Route","Cache","Config","Http"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}->${o}()`}),o==="publish"&&r&&(r.includes("topic")||r.includes("pubSub"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="Http"||r==="client"||r.endsWith("request")||r.includes("Client")||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if(t===".py"){let n=/(?:([a-zA-Z0-9_\.]+)\.)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&r!=="self"&&r!=="cls"&&this.calls.add(`${r}.${o}`),["save","delete","update","create","first","all","filter","get"].includes(o)&&r&&!["logger","os","sys"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}.${o}()`}),o==="publish"&&r&&(r.includes("publisher")||r.includes("client"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="requests"||r==="httpx"||r==="client"||r==="http"||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if([".ts",".tsx",".js",".jsx"].includes(t)){let n=/import\s+[\s\S]*?from\s+['"](.*?)['"];?/g,i;for(;(i=n.exec(e))!==null;)this.imports.set("*",i[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=o[2];a?(this.calls.add(`${a}.${c}`),(a.toLowerCase().includes("pubsub")||a==="pubSubClient")&&c!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:c})):this.calls.add(c)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,i;for(;(i=n.exec(e))!==null;)this.calls.add(i[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,i;for(;(i=n.exec(e))!==null;){let r=i[1],o=r.split("\\"),a=i[2]||o[o.length-1];this.imports.set(a,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,i;for(;(i=n.exec(e))!==null;){let a=i[1];i[2].split(",").map(l=>l.trim()).forEach(l=>{this.imports.set(l,a)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=a.split("."),l=c[c.length-1];this.imports.set(l,a)}}}};var Yp=new Set(["api","v1","v2","v3","http","https","localhost","admin","internal","public","private","app","src","get","post","put","delete","patch","user","users","id","search","list","create","update","data"]),Kp=new Set(["GET","POST","PUT","DELETE","PATCH"]),Qp=[/\bRoute::(?:get|post|put|delete|patch)\b/i,/\brouter\.(?:get|post|put|delete|patch)\s*\(/i,/\bapp\.(?:get|post|put|delete|patch)\s*\(/i,/\bfastify\.(?:get|post|put|delete|patch)\s*\(/i,/\baddRoute\s*\(/i,/\bHTTPMethods\.(?:GET|POST|PUT|DELETE|PATCH)\b/i,/\bpath\s*\(/i,/\bre_path\s*\(/i,/@(?:GET|POST|PUT|DELETE|PATCH|Route)\b/i,/@(?:Get|Post|Put|Delete|Patch|RequestMapping)\b/];function Xp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fn(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Cs(s){let e=fn(s).replace(/:[^/]+/g,"__SEG__").replace(/\{[^}]+\}/g,"__SEG__").replace(/\$[^/]+/g,"__SEG__").replace(/\*/g,"__SEG__"),t=Xp(e).replace(/__SEG__/g,"[^/]+");return new RegExp(`^${t}$`)}function ma(s){let e=[/(HTTPMethods\.)?(GET|POST|PUT|DELETE|PATCH)\b/i,/Route::(get|post|put|delete|patch)\b/i,/@(GET|POST|PUT|DELETE|PATCH)\b/i],t;for(let n of e){let i=s.match(n);if(i?.[2]){t=i[2].toUpperCase();break}if(i?.[1]){t=i[1].toUpperCase();break}}return t&&Kp.has(t)?t:null}function Zp(s){return s.replace(/<[^>]+>/g," ")}function eu(s){return Qp.some(e=>e.test(s))}function tu(s){let e=[],t=/['"`]([^'"`]*\/[^'"`]*)['"`]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();i&&e.push(i)}return e}function nu(s){let e=s.replace(/^\^/,"").replace(/\$$/,"");if(e.includes("://"))try{e=new URL(e).pathname}catch{}if(!e.startsWith("/")){let t=e.indexOf("/");if(t===-1)return null;e=e.slice(t)}return fn(e)}function iu(s,e){let t=tu(s);for(let n of t){let i=nu(n);if(!i)continue;let r=Cs(i),o=e.replace(/\*/g,"test-val");if(r.test(o)||!/[:{*$]/.test(i)&&o.startsWith(`${i}/`))return!0}return!1}function su(s,e){if(e)try{let i=JSON.parse(e);if(typeof i.path=="string"&&i.path.startsWith("/"))return fn(i.path)}catch{}let t=/['"]([^'"]+)['"]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();if(i){if(i=i.replace(/^\^/,"").replace(/\$$/,""),!i.startsWith("/")){if(!i.includes("/")&&!i.includes(":"))continue;i=`/${i}`}return fn(i)}}return null}function ru(s,e){let t=s.toLowerCase();return e.reduce((n,i)=>n+(t.includes(i.toLowerCase())?20:0),0)}function ha(s,e,t){let n=e,i=e.match(/\$\{([^}]+)\}/g);if(i)for(let h of i){let m=h.substring(2,h.length-1),f=s.configs.findEnvValue(m);f&&(n=n.replace(h,f))}let r=n.split("?")[0].split("#")[0];try{r.includes("://")&&(r=new URL(r).pathname)}catch{}r=fn(r);let o=t?.toUpperCase(),a=[],c=!1,l=r.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),p=s.files.findSynapses({type:"api_route",name:l.includes("%")?l:r,direction:"consume",limit:10});for(let h of p)Cs(h.name).test(r.replace(/\*/g,"test-val"))&&(a.push({file_path:h.file_path,start_line:h.line_number||0,signature:`[Synapse] ${h.name}`,score:1e3}),c=!0);let u=r.split(/[^a-zA-Z0-9-_]/).filter(h=>h.length>=3&&!Yp.has(h.toLowerCase())&&!/^\d+$/.test(h));if(u.length>0){let f=[...u].sort((g,b)=>b.length-g.length).slice(0,2).flatMap(g=>s.exports.findRoutesByToken(g,20)),_=new Set;for(let g of f){let b=`${g.file_path}:${g.start_line}:${g.name}`;if(_.has(b))continue;_.add(b);let w=g.signature||g.name||"",x=ma(w);if(o&&x&&o!==x)continue;let R=su(w,g.capabilities);if(o&&!x&&!R)continue;let k=40;if(R){if(!Cs(R).test(r.replace(/\*/g,"test-val")))continue;k+=280,c=!0}o&&x&&o===x&&(k+=120,c=!0),k+=ru(`${w} ${R||""}`,u),a.push({file_path:g.file_path,start_line:g.start_line,signature:`[Boundary] ${w}`,capabilities:g.capabilities||void 0,score:k})}}if(a.length<3&&!c){let h=u.map(m=>m.replace(/[^a-zA-Z0-9_]/g,"")).filter(m=>m.length>0).join(" AND ");if(h.length>0){let m=s.content.search(h);for(let f of m){let _=Zp(f.snippet);if(!eu(_)||!iu(_,r))continue;let g=ma(_);if(o&&g&&g!==o)continue;let b=0,w=f.file_path.toLowerCase(),x=_.toLowerCase();(w.includes("route")||w.includes("controller"))&&(b+=10),(w.includes("src/api")||w.includes("services/api"))&&(b+=5),(x.includes("addroute")||x.includes("@get"))&&(b+=15),(x.includes("axios.")||x.includes("fetch("))&&(b-=10),(w.includes(".spec.")||w.includes(".test."))&&(b-=20),o&&x.includes(o.toLowerCase())&&(b+=20),b>0&&a.push({file_path:f.file_path,start_line:0,signature:`[FTS Match] ${_.replace(/\n/g," ")}`,score:b})}}}let d=new Map;return a.sort((h,m)=>m.score-h.score).forEach(h=>{d.has(h.file_path)||d.set(h.file_path,h)}),Array.from(d.values()).slice(0,c?2:3)}var Is=7,Lt=80,ou=2,au=4,cu=6,lu=3,pu=24,uu=new Set(["publish","publishmessage","publishtaskbynameandpayload"]),du=new Set(["Error","TypeError","RangeError","ReferenceError","SyntaxError","Promise","Map","Set","WeakMap","WeakSet","Date","Array","Object","String","Number","Boolean","RegExp","URL","URLSearchParams"]),mu=new Set(["error","errors","request","response","result","results","value","values","item","data","payload","message","messages","text","description","name","id","type","status","code"]),ga=new Set(["req","res","request","response","error","err","event","item","row","data","value","obj","window","document","console","json","math"]),hu=new Set(["length","size","value","values","name","id","type","status"]),ya=new Set(["push","pop","shift","unshift","slice","splice","map","filter","reduce","reduceRight","forEach","find","findIndex","includes","indexOf","lastIndexOf","every","some","flat","flatMap","fill","copyWithin","entries","keys","values","join","concat","sort","reverse","at","with","toSorted","toReversed","toSpliced","toString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","charAt","charCodeAt","codePointAt","split","substring","substr","trim","trimStart","trimEnd","padStart","padEnd","repeat","replace","replaceAll","match","matchAll","search","toLowerCase","toUpperCase","localeCompare","normalize","startsWith","endsWith","then","catch","finally","get","set","has","delete","clear","size","length","call","apply","bind"]);function fu(s,e){return fe.resolve(s)===fe.resolve(e)}function gu(s){if(du.has(s))return!0;let e=s.trim().toLowerCase();if(!e||e.length<2||/\[|\]|\s/.test(s)||mu.has(e))return!0;let t=s.split(/(?:\.|->|::)+/).filter(Boolean),n=(t.length>0?t[t.length-1]:e).replace(/^\$+/,"");if(hu.has(n.toLowerCase())||ya.has(n))return!0;if(t.length>1){let i=t[0].replace(/^\$+/,"").toLowerCase();if(ga.has(i))return!0}return!1}function $s(s,e){if(e.has(s))return e.get(s)??null;try{let t=$t.readFileSync(s,"utf8");return e.set(s,t),t}catch{return null}}function yu(s){return s<20?Is:s<45?Is-1:Math.max(4,Is-2)}function bu(s,e){let t=s<=2?1:s<=4?.7:.4,n=e<25?1:e<55?.8:.55,i=Math.floor(pu*t*n);return Math.max(lu,i)}function _u(s,e){let t=s.split(`
668
- `),n=new Map,i=new Map,r=[],o=new Set;for(let a=0;a<t.length;a++){let c=t[a],l=e+a+1,p=c.match(/\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/),u=c.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*[^=]/),d=p?.[1]||u?.[1];if(d){n.set(d,l);continue}for(let[h,m]of n.entries()){if(l<=m||!new RegExp(`\\b${ba(h)}\\b`).test(c))continue;let f=i.get(h)||0;if(f>=2)continue;let _=`${h}:${m}->${l}`;o.has(_)||(r.push({symbol:h,fromLine:m,toLine:l}),o.add(_),i.set(h,f+1))}}return r}function fa(s){let e=s.trim();if(!e)return"";let t=e.indexOf("/"),n=t>=0?e.slice(t):e;return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function ba(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function As(s){let e=s.split(/(?:\.|::|->)+/).filter(Boolean);return e.length>0?e[e.length-1]:s.trim()}function Eu(s,e){let t=0,n=!1;for(let i=e;i<s.length;i++){let r=s[i];for(let a of r)if(a==="{")t++,n=!0;else if(a==="}"&&(t--,n&&t<=0))return{start:e+1,end:i+1};let o=r.trim();if(!n&&/[;}]$/.test(o))return{start:e+1,end:i+1}}return{start:e+1,end:Math.min(s.length,e+40)}}function Ls(s,e,t){let n=As(e);if(!n)return null;try{let i=t?$s(s,t):$t.readFileSync(s,"utf8");if(!i)return null;let r=i.split(`
669
- `),o=ba(n),a=[new RegExp(`^\\s*(?:export\\s+)?(?:async\\s+)?function\\s+${o}\\b`),new RegExp(`^\\s*(?:(?:public|private|protected|static|readonly|async|abstract|get|set)\\s+)*${o}\\s*(?:<[^>]*>)?\\s*\\(`),new RegExp(`^\\s*(?:(?:public|private|protected|static|readonly|async|abstract)\\s+)*${o}\\s*[:=]\\s*(?:async\\s*)?(?:\\([^)]*\\)\\s*=>|function\\b)`),new RegExp(`^\\s*(?:export\\s+)?class\\s+${o}\\b`)];for(let c=0;c<r.length;c++){let l=r[c];if(l.includes(n)&&a.some(p=>p.test(l)))return Eu(r,c)}}catch{return null}return null}function _a(s,e,t,n){try{let i=n?$s(s,n):$t.readFileSync(s,"utf8");if(!i)return!0;let r=i.split(`
743
+ ${_.bold("Files/sec")}: ${_.green((r/(n/1e3)).toFixed(2))}
744
+ ${_.bold("Symbols/sec")}: ${_.green((o/(n/1e3)).toFixed(2))}
745
+ ${_.bold("ms per file")}: ${_.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
746
+ Benchmark failed during execution:`,n),n}finally{await ne(e)}})}import Wi from"path";import $e from"path";import qs from"fs";var Su=/[\x00-\x1f\x7f]/g,xu=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Gs(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(Su,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function Pi(s,e=4096){if(typeof s!="string")return"";let t=s.replace(xu,"").trim();return t.length>e?t.slice(0,e):t}dt();function wu(s){let e=$e.isAbsolute(s)?$e.normalize(s):$e.resolve(process.cwd(),s),t=$e.parse(e).root;for(;e!==t;){if(qs.existsSync($e.join(e,".liquid-shadow.db"))||qs.existsSync($e.join(e,".git"))||qs.existsSync($e.join(e,"package.json")))return e;let n=$e.dirname(e);if(n===e)break;e=n}return null}function He(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=Gs(e)),t&&(t=Gs(t));let n;if(e)$e.isAbsolute(e)||(e=$e.resolve(process.cwd(),e)),n=e;else if(t){let o=$e.resolve(process.cwd(),t);n=wu($e.dirname(o))||process.cwd()}else n=process.cwd();n=$e.normalize(n);let i=Da(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}Y();G();import Gt from"fs";import Se from"path";import{Visitor as vu}from"@swc/core/Visitor.js";var Di=class extends vu{calls=new Set;apiCalls=[];imports=new Map;axiosInstances=new Map([["axios",""],["http",""],["appApi",""],["restApi",""],["adminApi",""]]);visitImportDeclaration(e){let t=e.source.value;for(let n of e.specifiers)(n.type==="ImportDefaultSpecifier"||n.type==="ImportSpecifier")&&this.imports.set(n.local.value,t);return super.visitImportDeclaration(e)}visitCallExpression(e){if(e.callee.type==="Identifier"){let t=e.callee.value;this.calls.add(t),(t==="axios"||t==="http")&&e.arguments.length>0&&this.extractApiCallFromConfig(e.arguments[0].expression)}else if(e.callee.type==="MemberExpression"){let t=e.callee.property.value,n=r=>{if(!r)return"?";if(r.type==="Identifier")return r.value;if(r.type==="ThisExpression")return"this";if(r.type==="MemberExpression"){let o=n(r.object),a=r.property.value||"?";return`${o}.${a}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},i=n(e.callee.object);if(i!=="?"&&t){if(this.calls.add(`${i}.${t}`),i==="axios"||i==="http"||this.axiosInstances.has(i)){let r=this.axiosInstances.get(i)||"";this.extractApiCall(t,e.arguments,r)}if((i.toLowerCase().includes("pubsub")||i==="pubSubClient"||i.endsWith(".pubSubClient"))&&t!=="subscribe"){let r=t;if((t==="publish"||t==="publishMessage"||t==="publishTaskByNameAndPayload")&&e.arguments.length>0)for(let o of e.arguments){let a=o.expression;if(a.type==="ObjectExpression"){let l=a.properties.find(c=>c.key?.type==="Identifier"&&(c.key.value==="action"||c.key.value==="type")||c.key?.type==="StringLiteral"&&(c.key.value==="action"||c.key.value==="type"));if(l&&l.value?.type==="StringLiteral"){r=l.value.value;break}}if(a.type==="CallExpression"&&a.callee.type==="MemberExpression"&&a.callee.object.value==="JSON"&&a.callee.property.value==="stringify"&&a.arguments.length>0){let l=a.arguments[0].expression;if(l.type==="ObjectExpression"){let c=l.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(c&&c.value?.type==="StringLiteral"){r=c.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})}}}},on=class{calls=new Set;apiCalls=[];imports=new Map;visit(e,t){if(t===".php"){let n=/(?:([a-zA-Z0-9_$->:\(\)]*)?(?:->|::))?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&!["$this","self","parent"].includes(r)&&this.calls.add(`${r}${r.includes("::")?"::":"->"}${o}`),["save","delete","update","create","first","all","where","get","find"].includes(o)&&r&&!["Log","Route","Cache","Config","Http"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}->${o}()`}),o==="publish"&&r&&(r.includes("topic")||r.includes("pubSub"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="Http"||r==="client"||r.endsWith("request")||r.includes("Client")||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if(t===".py"){let n=/(?:([a-zA-Z0-9_\.]+)\.)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&r!=="self"&&r!=="cls"&&this.calls.add(`${r}.${o}`),["save","delete","update","create","first","all","filter","get"].includes(o)&&r&&!["logger","os","sys"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}.${o}()`}),o==="publish"&&r&&(r.includes("publisher")||r.includes("client"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="requests"||r==="httpx"||r==="client"||r==="http"||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if([".ts",".tsx",".js",".jsx"].includes(t)){let n=/import\s+[\s\S]*?from\s+['"](.*?)['"];?/g,i;for(;(i=n.exec(e))!==null;)this.imports.set("*",i[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let a=o[1],l=o[2];a?(this.calls.add(`${a}.${l}`),(a.toLowerCase().includes("pubsub")||a==="pubSubClient")&&l!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:l})):this.calls.add(l)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,i;for(;(i=n.exec(e))!==null;)this.calls.add(i[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,i;for(;(i=n.exec(e))!==null;){let r=i[1],o=r.split("\\"),a=i[2]||o[o.length-1];this.imports.set(a,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,i;for(;(i=n.exec(e))!==null;){let a=i[1];i[2].split(",").map(c=>c.trim()).forEach(c=>{this.imports.set(c,a)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let a=o[1],l=a.split("."),c=l[l.length-1];this.imports.set(c,a)}}}};var Ru=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"]),Tu=new Set(["GET","POST","PUT","DELETE","PATCH"]),ku=[/\bRoute::(?:get|post|put|delete|patch)\b/i,/\brouter\.(?:get|post|put|delete|patch)\s*\(/i,/\bapp\.(?:get|post|put|delete|patch)\s*\(/i,/\bfastify\.(?:get|post|put|delete|patch)\s*\(/i,/\baddRoute\s*\(/i,/\bHTTPMethods\.(?:GET|POST|PUT|DELETE|PATCH)\b/i,/\bpath\s*\(/i,/\bre_path\s*\(/i,/@(?:GET|POST|PUT|DELETE|PATCH|Route)\b/i,/@(?:Get|Post|Put|Delete|Patch|RequestMapping)\b/];function Cu(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cn(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Vs(s){let e=Cn(s).replace(/:[^/]+/g,"__SEG__").replace(/\{[^}]+\}/g,"__SEG__").replace(/\$[^/]+/g,"__SEG__").replace(/\*/g,"__SEG__"),t=Cu(e).replace(/__SEG__/g,"[^/]+");return new RegExp(`^${t}$`)}function za(s){let e=[/(HTTPMethods\.)?(GET|POST|PUT|DELETE|PATCH)\b/i,/Route::(get|post|put|delete|patch)\b/i,/@(GET|POST|PUT|DELETE|PATCH)\b/i],t;for(let n of e){let i=s.match(n);if(i?.[2]){t=i[2].toUpperCase();break}if(i?.[1]){t=i[1].toUpperCase();break}}return t&&Tu.has(t)?t:null}function Iu(s){return s.replace(/<[^>]+>/g," ")}function Lu(s){return ku.some(e=>e.test(s))}function Mu(s){let e=[],t=/['"`]([^'"`]*\/[^'"`]*)['"`]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();i&&e.push(i)}return e}function $u(s){let e=s.replace(/^\^/,"").replace(/\$$/,"");if(e.includes("://"))try{e=new URL(e).pathname}catch{}if(!e.startsWith("/")){let t=e.indexOf("/");if(t===-1)return null;e=e.slice(t)}return Cn(e)}function Au(s,e){let t=Mu(s);for(let n of t){let i=$u(n);if(!i)continue;let r=Vs(i),o=e.replace(/\*/g,"test-val");if(r.test(o)||!/[:{*$]/.test(i)&&o.startsWith(`${i}/`))return!0}return!1}function Nu(s,e){if(e)try{let i=JSON.parse(e);if(typeof i.path=="string"&&i.path.startsWith("/"))return Cn(i.path)}catch{}let t=/['"]([^'"]+)['"]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();if(i){if(i=i.replace(/^\^/,"").replace(/\$$/,""),!i.startsWith("/")){if(!i.includes("/")&&!i.includes(":"))continue;i=`/${i}`}return Cn(i)}}return null}function Pu(s,e){let t=s.toLowerCase();return e.reduce((n,i)=>n+(t.includes(i.toLowerCase())?20:0),0)}function Ba(s,e,t){let n=e,i=e.match(/\$\{([^}]+)\}/g);if(i)for(let h of i){let m=h.substring(2,h.length-1),f=s.configs.findEnvValue(m);f&&(n=n.replace(h,f))}let r=n.split("?")[0].split("#")[0];try{r.includes("://")&&(r=new URL(r).pathname)}catch{}r=Cn(r);let o=t?.toUpperCase(),a=[],l=!1,c=r.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),p=s.files.findSynapses({type:"api_route",name:c.includes("%")?c:r,direction:"consume",limit:10});for(let h of p)Vs(h.name).test(r.replace(/\*/g,"test-val"))&&(a.push({file_path:h.file_path,start_line:h.line_number||0,signature:`[Synapse] ${h.name}`,score:1e3}),l=!0);let u=r.split(/[^a-zA-Z0-9-_]/).filter(h=>h.length>=3&&!Ru.has(h.toLowerCase())&&!/^\d+$/.test(h));if(u.length>0){let f=[...u].sort((g,y)=>y.length-g.length).slice(0,2).flatMap(g=>s.exports.findRoutesByToken(g,20)),b=new Set;for(let g of f){let y=`${g.file_path}:${g.start_line}:${g.name}`;if(b.has(y))continue;b.add(y);let E=g.signature||g.name||"",k=za(E);if(o&&k&&o!==k)continue;let R=Nu(E,g.capabilities);if(o&&!k&&!R)continue;let w=40;if(R){if(!Vs(R).test(r.replace(/\*/g,"test-val")))continue;w+=280,l=!0}o&&k&&o===k&&(w+=120,l=!0),w+=Pu(`${E} ${R||""}`,u),a.push({file_path:g.file_path,start_line:g.start_line,signature:`[Boundary] ${E}`,capabilities:g.capabilities||void 0,score:w})}}if(a.length<3&&!l){let h=u.map(m=>m.replace(/[^a-zA-Z0-9_]/g,"")).filter(m=>m.length>0).join(" AND ");if(h.length>0){let m=s.content.search(h);for(let f of m){let b=Iu(f.snippet);if(!Lu(b)||!Au(b,r))continue;let g=za(b);if(o&&g&&g!==o)continue;let y=0,E=f.file_path.toLowerCase(),k=b.toLowerCase();(E.includes("route")||E.includes("controller"))&&(y+=10),(E.includes("src/api")||E.includes("services/api"))&&(y+=5),(k.includes("addroute")||k.includes("@get"))&&(y+=15),(k.includes("axios.")||k.includes("fetch("))&&(y-=10),(E.includes(".spec.")||E.includes(".test."))&&(y-=20),o&&k.includes(o.toLowerCase())&&(y+=20),y>0&&a.push({file_path:f.file_path,start_line:0,signature:`[FTS Match] ${b.replace(/\n/g," ")}`,score:y})}}}let d=new Map;return a.sort((h,m)=>m.score-h.score).forEach(h=>{d.has(h.file_path)||d.set(h.file_path,h)}),Array.from(d.values()).slice(0,l?2:3)}var Js=7,Ct=80,Du=2,Ou=4,Fu=6,Ua=24,Wu=3,Hu=24,zu=new Set(["publish","publishmessage","publishtaskbynameandpayload"]),Bu=new Set(["Error","TypeError","RangeError","ReferenceError","SyntaxError","Promise","Map","Set","WeakMap","WeakSet","Date","Array","Object","String","Number","Boolean","RegExp","URL","URLSearchParams","FormData"]),Uu=new Set(["error","errors","request","response","result","results","value","values","item","data","payload","message","messages","text","description","name","id","type","status","code","count","test"]),Ga=new Set(["req","res","request","response","error","err","event","item","row","data","value","obj","window","document","console","json","math"]),ju=new Set(["length","size","value","values","name","id","type","status","count"]),qa=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","test"]);function Gu(s,e){return Se.resolve(s)===Se.resolve(e)}function Va(s){if(Bu.has(s))return!0;let e=s.trim().toLowerCase();if(!e||e.length<2||/\[|\]|\s/.test(s)||Uu.has(e))return!0;let t=s.split(/(?:\.|->|::)+/).filter(Boolean),n=(t.length>0?t[t.length-1]:e).replace(/^\$+/,"");if(ju.has(n.toLowerCase())||qa.has(n))return!0;if(t.length>1){let i=t[0].replace(/^\$+/,"").toLowerCase();if(Ga.has(i))return!0}return!1}function Ks(s,e){if(e.has(s))return e.get(s)??null;try{let t=Gt.readFileSync(s,"utf8");return e.set(s,t),t}catch{return null}}function Ys(s){let e=new Set,t=[];for(let n of s){let i=`${n.file_path}:${n.name}:${n.start_line??0}`;e.has(i)||(e.add(i),t.push(n))}return t}function qu(s,e,t){if(Va(s))return[];let n=s.trim();if(!n)return[];let i=t.exports.findByNameAndFile(n,e),r=n.split(/(?:\.|->|::)+/).filter(Boolean);if(r.length<=1)return Ys([...i,...t.exports.findTopLevelByNameGlobal(n)]);let o=r[0]?.replace(/^\$+/,"")||"",a=o.toLowerCase(),l=r[r.length-1];if(!l)return i;let c=t.exports.findByNameAndFile(l,e);if(qa.has(l)||Ga.has(a))return Ys([...i,...c]);let p=o?t.exports.findMemberCandidates(o,l,e):[],d=o&&!new Set(["this","self","static","parent"]).has(a)&&p.length===0?t.exports.findMemberCandidates(o,l):[];return Ys([...p,...c,...i,...d])}function Vu(s){return s<20?Js:s<45?Js-1:Math.max(4,Js-2)}function Ju(s,e){let t=s<=2?1:s<=4?.7:.4,n=e<25?1:e<55?.8:.55,i=Math.floor(Hu*t*n);return Math.max(Wu,i)}function Yu(s,e){let t=s.split(`
747
+ `),n=new Map,i=new Map,r=[],o=new Set;for(let a=0;a<t.length;a++){let l=t[a],c=e+a+1,p=l.match(/\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/),u=l.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*[^=]/),d=p?.[1]||u?.[1];if(d){n.set(d,c);continue}for(let[h,m]of n.entries()){if(c<=m||!new RegExp(`\\b${Ja(h)}\\b`).test(l))continue;let f=i.get(h)||0;if(f>=2)continue;let b=`${h}:${m}->${c}`;o.has(b)||(r.push({symbol:h,fromLine:m,toLine:c}),o.add(b),i.set(h,f+1))}}return r}function Ku(s){let e=new Map;for(let t of s){let n=`${t.symbol}:${t.fromLine}`,i=e.get(n);if(i){i.toLines.includes(t.toLine)||i.toLines.push(t.toLine);continue}e.set(n,{symbol:t.symbol,fromLine:t.fromLine,toLines:[t.toLine]})}return Array.from(e.values()).map(t=>({...t,toLines:[...t.toLines].sort((n,i)=>n-i)}))}function Qu(s){if(s.toLines.length<=1)return`assigned @L${s.fromLine} \u2192 used @L${s.toLines[0]}`;let e=s.toLines.slice(0,3).map(i=>`@L${i}`).join(", "),t=s.toLines.length-3,n=t>0?`, +${t} more`:"";return`assigned @L${s.fromLine} \u2192 used ${e}${n} (${s.toLines.length} uses)`}function Zu(s,e,t=Fu){let n=Math.max(0,Math.min(s.length,t,e));return{visibleEdges:s.slice(0,n),omittedCount:Math.max(0,s.length-n)}}function ja(s){let e=s.trim();if(!e)return"";let t=e.indexOf("/"),n=t>=0?e.slice(t):e;return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function Ja(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qs(s){let e=s.split(/(?:\.|::|->)+/).filter(Boolean);return e.length>0?e[e.length-1]:s.trim()}function Xu(s){return s&&(s.includes("Class")||s.includes("Interface")||s.includes("TypeAlias")||s.includes("Enum"))?"component":"function"}function ed(s,e){let t=0,n=!1;for(let i=e;i<s.length;i++){let r=s[i];for(let a of r)if(a==="{")t++,n=!0;else if(a==="}"&&(t--,n&&t<=0))return{start:e+1,end:i+1};let o=r.trim();if(!n&&/[;}]$/.test(o))return{start:e+1,end:i+1}}return{start:e+1,end:Math.min(s.length,e+40)}}function Fi(s,e,t){let n=Qs(e);if(!n)return null;try{let i=t?Ks(s,t):Gt.readFileSync(s,"utf8");if(!i)return null;let r=i.split(`
748
+ `),o=Ja(n),a=[new RegExp(`^\\s*(?:export\\s+)?(?:async\\s+)?function\\s+${o}\\b`),new RegExp(`^\\s*(?:(?:public|private|protected|static|readonly|async|abstract|get|set)\\s+)*${o}\\s*(?:<[^>]*>)?\\s*\\(`),new RegExp(`^\\s*(?:(?:public|private|protected|static|readonly|async|abstract)\\s+)*${o}\\s*[:=]\\s*(?:async\\s*)?(?:\\([^)]*\\)\\s*=>|function\\b)`),new RegExp(`^\\s*(?:export\\s+)?class\\s+${o}\\b`)];for(let l=0;l<r.length;l++){let c=r[l];if(c.includes(n)&&a.some(p=>p.test(c)))return ed(r,l)}}catch{return null}return null}function Ya(s,e,t,n){try{let i=n?Ks(s,n):Gt.readFileSync(s,"utf8");if(!i)return!0;let r=i.split(`
670
749
  `);if(e.start<1||e.end<e.start||e.start>r.length||e.end>r.length||!r.slice(e.start-1,e.end).join(`
671
- `).trim())return!0;if(e.start===e.end){let a=r[e.start-1]?.trim()||"",c=a.replace(/\s+/g,"");if(!c||/^[{}()[\];,]+$/.test(c))return!0;let l=As(t);if(l&&!a.includes(l))return!0}return!1}catch{return!0}}function wi(s,e,t,n){if(e){if(!t)return e;if(_a(s,e,t,n)){let i=Ls(s,t,n);if(i)return i}return e}}function Su(s,e,t){let n=s.exports.findByNameAndFile(t,e);if(n.length>0)return n[0];let i=s.exports.findByFile(e);if(i.length===0)return null;if(t.includes("/")){let a=fa(t),c=i.find(l=>!l?.name||typeof l.name!="string"?!1:fa(l.name)===a);if(c)return c}let r=t.split(/(?:\.|::|->)+/).filter(Boolean);if(r.length>1){let a=r[r.length-1],c=s.exports.findByNameAndFile(a,e);if(c.length===1)return c[0]}return i.find(a=>typeof a?.name=="string"&&(a.name===t||a.name.includes(t)))||null}async function Ea(s){let{repoPath:e,filePath:t,symbolName:n}=Ve(s);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let i=t;await X(e);let r=O.getInstance(e);if(!$t.existsSync(i))return{isError:!0,content:[{type:"text",text:`File not found: ${i}`}]};let o=new Map,a,c=fe.basename(i),l;if(n){let h=As(n),m=Su(r,i,n);if(m){let f=m;a={start:f.start_line,end:f.end_line},c=f.name,l=f.start_line}else{let f=Ls(i,n,o);if(f)a=f,l=f.start,c=h||n;else{let _=r.exports.findByFile(i).map(g=>g.name).filter(g=>!!g).slice(0,10);return{isError:!0,content:[{type:"text",text:`Symbol not found in file: "${n}"
672
- File: ${fe.relative(e,i)}
673
- `+(_.length>0?`Top symbols in file: ${_.join(", ")}`:"No indexed symbols found for this file.")}]}}}if(a&&_a(i,a,n,o)){let f=Ls(i,n,o);f&&(S.warn({filePath:i,symbolName:n,start:a.start,end:a.end},"Indexed symbol range appears degenerate; using source-inferred range for flow"),a=f,l=f.start,c===fe.basename(i)&&(c=h||n))}}let p={type:a?"function":"file",name:c,path:fe.relative(e,i),line:l,children:[]},u=new Set;u.add(i+(n?`:${n}`:""));let d={count:0,truncated:!1,pruned:!1};return await Bt(i,p,e,r,u,1,d,o,a),(d.truncated||d.pruned)&&p.children.push({type:"function",name:"\u26A0\uFE0F Trace Pruned",details:`Adaptive trace limits applied (depth/node budget). Current cap: ${Lt} nodes.`,children:[]}),{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}async function Bt(s,e,t,n,i,r,o,a,c){let l=yu(o.count);if(r>l){o.pruned=!0;return}if(o.count>=Lt){o.truncated=!0;return}try{let p=$s(s,a);if(!p)throw new Error(`Unable to read source: ${s}`);let u=p,d=fe.extname(s).toLowerCase(),m=(u.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
674
- `);c&&(u=u.split(`
675
- `).slice(c.start-1,c.end).join(`
676
- `));let f;if(d===".ts"||d===".tsx"||d===".js"||d===".jsx"){f=new Si;let P={syntax:"typescript",tsx:s.endsWith(".tsx"),target:"es2020"};try{let E=c?`${m}
677
- ${u}`:u,T=await ms(E,P);f.visitModule(T)}catch{if(c)try{let T=`${m}
750
+ `).trim())return!0;if(e.start===e.end){let a=r[e.start-1]?.trim()||"",l=a.replace(/\s+/g,"");if(!l||/^[{}()[\];,]+$/.test(l))return!0;let c=Qs(t);if(c&&!a.includes(c))return!0}return!1}catch{return!0}}function Oi(s,e,t,n){if(e){if(!t)return e;if(Ya(s,e,t,n)){let i=Fi(s,t,n);if(i)return i}return e}}function td(s,e){let t=Math.max(0,s.end-s.start),n=Math.max(0,e.end-e.start);return!(e.start>=s.start&&e.end<=s.end)||t===0?!1:n+5<t&&n<=Math.max(12,Math.floor(t*.6))}function nd(s,e,t){let n=s.exports.findByNameAndFile(t,e);if(n.length>0)return n[0];let i=s.exports.findByFile(e);if(i.length===0)return null;if(t.includes("/")){let a=ja(t),l=i.find(c=>!c?.name||typeof c.name!="string"?!1:ja(c.name)===a);if(l)return l}let r=t.split(/(?:\.|::|->)+/).filter(Boolean);if(r.length>1){let a=r[r.length-1],l=s.exports.findByNameAndFile(a,e);if(l.length===1)return l[0]}return i.find(a=>typeof a?.name=="string"&&(a.name===t||a.name.includes(t)))||null}async function Ka(s){let{repoPath:e,filePath:t,symbolName:n}=He(s);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let i=t;await se(e);let r=F.getInstance(e);if(!Gt.existsSync(i))return{isError:!0,content:[{type:"text",text:`File not found: ${i}`}]};let o=new Map,a,l=Se.basename(i),c,p=n?"function":"file";if(n){let m=Qs(n),f=nd(r,i,n);if(f){let b=f;a={start:b.start_line,end:b.end_line},l=b.name,c=b.start_line,p=Xu(b.kind)}else{let b=Fi(i,n,o);if(b)a=b,c=b.start,l=m||n;else{let g=r.exports.findByFile(i).map(y=>y.name).filter(y=>!!y).slice(0,10);return{isError:!0,content:[{type:"text",text:`Symbol not found in file: "${n}"
751
+ File: ${Se.relative(e,i)}
752
+ `+(g.length>0?`Top symbols in file: ${g.join(", ")}`:"No indexed symbols found for this file.")}]}}}if(a&&Ya(i,a,n,o)){let b=Fi(i,n,o);b&&(x.warn({filePath:i,symbolName:n,start:a.start,end:a.end},"Indexed symbol range appears degenerate; using source-inferred range for flow"),a=b,c=b.start,l===Se.basename(i)&&(l=m||n))}if(a){let b=Fi(i,n,o);b&&td(a,b)&&(x.warn({filePath:i,symbolName:n,start:a.start,end:a.end},"Indexed symbol range appears overwide; using source-inferred range for flow"),a=b,c=b.start)}}let u={type:a?p:"file",name:l,path:Se.relative(e,i),line:c,children:[]},d=new Set;d.add(i+(n?`:${n}`:""));let h={count:0,truncated:!1,pruned:!1,dataFlowCount:0};return await an(i,u,e,r,d,1,h,o,a),(h.truncated||h.pruned)&&u.children.push({type:"function",name:"\u26A0\uFE0F Trace Pruned",details:`Adaptive trace limits applied (depth/node budget). Current cap: ${Ct} nodes.`,children:[]}),{content:[{type:"text",text:JSON.stringify(u,null,2)}]}}async function an(s,e,t,n,i,r,o,a,l){let c=Vu(o.count);if(r>c){o.pruned=!0;return}if(o.count>=Ct){o.truncated=!0;return}try{let p=Ks(s,a);if(!p)throw new Error(`Unable to read source: ${s}`);let u=p,d=Se.extname(s).toLowerCase(),m=(u.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
753
+ `);l&&(u=u.split(`
754
+ `).slice(l.start-1,l.end).join(`
755
+ `));let f;if(d===".ts"||d===".tsx"||d===".js"||d===".jsx"){f=new Di;let D={syntax:"typescript",tsx:s.endsWith(".tsx"),target:"es2020"};try{let P=l?`${m}
756
+ ${u}`:u,B=await $s(P,D);f.visitModule(B)}catch{if(l)try{let B=`${m}
678
757
  class TraceContext {
679
758
  ${u}
680
- }`,I=await ms(T,P);f.visitModule(I)}catch{let I=new jt,M=d;I.visit(u,M),f.calls=I.calls,f.apiCalls=I.apiCalls,f.imports=I.imports}else{let T=new jt;T.visit(u,d),f.calls=T.calls,f.apiCalls=T.apiCalls,f.imports=T.imports}}}else f=new jt,f.visit(u,d);S.info({file:fe.basename(s),calls:f.calls.size,apiCalls:f.apiCalls.length,depth:r},"Analyzed file");let _=Math.max(0,Lt-o.count),g=Math.max(2,Math.min(10,Math.floor(_/(r<=2?3:5)))),b=f.apiCalls.slice(0,g);f.apiCalls.length>g&&(o.pruned=!0);for(let P of b){if(o.count>=Lt)break;if(o.count++,P.method==="PUBSUB"){let M={type:"event_trigger",name:`PubSub Event: ${P.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(M);let N=P.url.toLowerCase();if(uu.has(N)){M.children.push({type:"subscriber",name:"PubSub fan-out omitted",details:"Generic publish call without concrete event/action; skipping global subscriber expansion to avoid false links.",children:[]});continue}let $=n.exports.findByNameGlobal(P.url).concat(n.exports.findByMethodName(P.url));if(P.url.length>10){let L=P.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(L!==P.url){let A=n.exports.findByNameGlobal(L).concat(n.exports.findByMethodName(L));$.push(...A)}}let W=new Set;for(let L of $.slice(0,au)){if(W.has(L.file_path)||L.file_path===s)continue;if(W.add(L.file_path),o.count>=Lt)break;o.count++;let A={type:"subscriber",name:`${L.name} (${fe.basename(L.file_path)})`,path:fe.relative(t,L.file_path),line:L.start_line,details:"Potential Subscriber / Handler",children:[]};M.children.push(A),$t.existsSync(L.file_path)&&!i.has(L.file_path)&&(i.add(L.file_path),await Bt(L.file_path,A,t,n,i,r+1,o,a))}continue}let E={type:"api_call",name:`${P.method} ${P.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(E);let I=ha(n,P.url,P.method).slice(0,ou);for(let M of I){if(fu(M.file_path,s))continue;if(o.count>=Lt)break;o.count++;let N={type:"route",name:M.signature||"Route Handler",path:M.file_path,line:M.start_line,children:[]};if(E.children.push(N),$t.existsSync(M.file_path)&&!i.has(M.file_path)&&(i.add(M.file_path),await Bt(M.file_path,N,t,n,i,r+1,o,a)),M.capabilities)try{let $=JSON.parse(M.capabilities);if($.handler){let[W,L]=$.handler.split("@");if(W){let H=W.split("\\").pop();if(H){let F=n.exports.findClassByName(H);if(F){let v=n.exports.findByNameAndFile(L||"",F.file_path),C,B=F.start_line;v.length>0&&(C=wi(F.file_path,{start:v[0].start_line,end:v[0].end_line},L||"",a),C||(C={start:v[0].start_line,end:v[0].end_line}),B=C.start);let j={type:"component",name:`${H}${L?" :: "+L:""}`,path:fe.relative(t,F.file_path),line:B,details:"Controller Logic (Macro IR)",children:[]};N.children.push(j),i.has(F.file_path+(L?`:${L}`:""))||(i.add(F.file_path+(L?`:${L}`:"")),await Bt(F.file_path,j,t,n,i,r+1,o,a,C))}}}}}catch{}}}let w=c?c.start-1:0,x=_u(u,w).slice(0,cu);for(let P of x){if(o.count>=Lt)break;o.count++,e.children.push({type:"data_flow",name:`${P.symbol} handoff`,line:P.toLine,details:`assigned @L${P.fromLine} \u2192 used @L${P.toLine}`,children:[]})}let R=f.calls,k=Array.from(R).sort(),D=bu(r,o.count),U=k.slice(0,D);k.length>D&&(o.pruned=!0);for(let P of U)if(f.imports.has(P)){let E=f.imports.get(P);if(!E.startsWith(".")){if(["react","react-dom"].includes(E))continue;e.children.push({type:"function",name:P,details:`External: ${E}`,children:[]});continue}let T=Tt(E,s,t);if(T&&$t.existsSync(T)){let I=n.exports.findByNameAndFile(P,T),M=I.length>0?I[0]:null,N=M?`${T}:${M.name}`:T;if(i.has(N))e.children.push({type:"function",name:P,details:"Circular / Already Visited",path:fe.relative(t,T),line:M?.start_line,children:[]});else{i.add(N);let $={type:M?"component":"file",name:P,details:M?`Imported symbol from ${fe.basename(T)}`:`Imported from ${fe.basename(T)}`,path:fe.relative(t,T),line:M?.start_line,children:[]};e.children.push($);let W=M?wi(T,{start:M.start_line,end:M.end_line},P,a):void 0;await Bt(T,$,t,n,i,r+1,o,a,W)}}}else if(!["log","info","error","warn","print"].includes(P)&&!gu(P)){let E=n.exports.findByNameGlobal(P);if(E.length===0){let T=P.split(/(?:\.|->|::)+/);if(T.length>1){let I=T[0]?.replace(/^\$+/,"").toLowerCase(),M=T[T.length-1];!ya.has(M)&&!(I&&ga.has(I))&&(E=n.exports.findByMethodName(M))}}if(E.length>0){let T=E.find(M=>M.file_path===s),I=T||(E.length===1?E[0]:null);if(I){let M=`${I.file_path}:${I.name}`;if(!i.has(M)){i.add(M);let N={type:"component",name:P,details:`Resolved via global index${T?" (local)":""}`,path:fe.relative(t,I.file_path),line:wi(I.file_path,{start:I.start_line,end:I.end_line},P,a)?.start,children:[]};e.children.push(N);let $=wi(I.file_path,{start:I.start_line,end:I.end_line},P,a)||{start:I.start_line,end:I.end_line};await Bt(I.file_path,N,t,n,i,r+1,o,a,$)}}}}}catch(p){S.error({filePath:s,error:p.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:p.message,children:[]})}}async function Sa(s,e){let t=xi.resolve(e.dir),n=xi.isAbsolute(s)?s:xi.resolve(t,s);await Y(async()=>{pe("Execution Trace");let i=Re();i.start(`Tracing ${y.cyan(e.symbolName||xi.basename(n))}...`);try{let r=await Ea({repoPath:t,filePath:n,symbolName:e.symbolName});i.stop("Trace complete."),r.isError?console.error(y.red(r.content[0].text)):se("Flow Results",r.content[0].text,"magenta")}catch(r){throw i.stop(`Trace failed: ${r.message}`),r}finally{await Q(t)}})}import vu from"path";V();Gt();q();import{execSync as xa}from"child_process";import xu from"path";var vi=S.child({module:"shadow-trace"}),qt=class{intentLogs;exports;repoPath;hologramService;constructor(e){let{intentLogs:t,exports:n}=O.getInstance(e);this.intentLogs=t,this.exports=n,this.repoPath=e,this.hologramService=new Se(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=xa(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
681
- `).filter(o=>o.trim()!=="");if(r.length===0)return;vi.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let a=xu.join(this.repoPath,o),l=xa(`git diff -U0 ${t} -- ${o}`,{cwd:this.repoPath,encoding:"utf-8"}).matchAll(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/g);for(let p of l){let u=parseInt(p[2],10),d=this.exports.findAtLine(a,u);d&&(this.intentLogs.create({mission_id:0,file_path:a,symbol_id:d.id,type:"discovery",content:`Shadow Trace: Modified externally in ${t}`,confidence:.8,symbol_name:d.name,signature:d.signature,commit_sha:null}),vi.debug({symbol:d.name},"Logged ghost change"),n.push({from:"external",to:`${o}:${d.name}`,pattern:"git-delta",confidence:.8}))}}n.length>0&&this.hologramService.updateGhostBridges(n),vi.info("Shadow Trace complete.")}catch(i){vi.warn({err:i.message},"Shadow Trace failed: git diff error.")}}};V();import{execSync as Vt}from"child_process";var Ti=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{Vt(`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 Vt(`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=Vt(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
682
- `);for(let i of n){let[r,o]=i.split(" ");if(o){let a=this.getNote(o);a&&e.set(o,a)}}}catch{}return e}removeNote(e){try{Vt(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{Vt(`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{Vt(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};q();gn();var Jt=S.child({module:"persistence-service"}),Fe=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new Ti(e)}async syncMissionToGitNotes(e){let{missions:t,intentLogs:n}=O.getInstance(this.repoPath),i=t.findById(e);if(!i)throw new Error(`Mission ${e} not found`);if(!i.commit_sha){Jt.info({missionId:e},"Skipping Git Notes sync because mission has no commit_sha yet");return}Jt.info({missionId:e,commitSha:i.commit_sha},"Syncing mission to Git Notes");let r=t.getArtifacts(e),o=n.findByMission(e,1e3),a=o.find(p=>p.type==="adr"),c=o.filter(p=>p.type==="decision").map(p=>({content:p.content,symbol_name:p.symbol_name,created_at:p.created_at})),l={version:"1.0",mission:{name:i.name,goal:i.goal,status:i.status,strategy_graph:i.strategy_graph,git_branch:i.git_branch,commit_sha:i.commit_sha,parent_id:i.parent_id,verification_context:i.verification_context,outcome_contract:i.outcome_contract,created_at:i.created_at,updated_at:i.updated_at},artifacts:r,adr:a?a.content:null,decisions:c};this.gitNotes.addNote(i.commit_sha,JSON.stringify(l,null,2))}async syncAllToGitNotes(){let{missions:e}=O.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){Jt.error({missionId:r.id,...ye(o)},"Failed to sync mission")}}async recoverFromGitNotes(){let e=this.gitNotes.listNotes(),{missions:t,intentLogs:n}=O.getInstance(this.repoPath),i=0,r=0;for(let[o,a]of e.entries())try{let c=JSON.parse(a);if(c.version!=="1.0")continue;if(t.findByCommitShas([o]).some(d=>d.name===c.mission.name)){Jt.debug({commitSha:o,missionName:c.mission.name},"Mission already exists, skipping recovery");continue}let u=t.create({name:c.mission.name,goal:c.mission.goal,status:c.mission.status,strategy_graph:c.mission.strategy_graph,git_branch:c.mission.git_branch,commit_sha:o,parent_id:c.mission.parent_id,verification_context:c.mission.verification_context,outcome_contract:c.mission.outcome_contract});if(i++,c.adr&&(n.create({mission_id:Number(u),symbol_id:null,file_path:null,type:"adr",content:c.adr,confidence:1,symbol_name:null,signature:null,commit_sha:o}),r++),c.decisions&&c.decisions.length>0)for(let d of c.decisions)n.create({mission_id:Number(u),symbol_id:null,file_path:null,type:"decision",content:d.content,confidence:1,symbol_name:d.symbol_name,signature:null,commit_sha:o}),r++;Jt.info({commitSha:o,missionName:c.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(c){Jt.error({commitSha:o,...ye(c)},"Failed to parse Git Note for recovery")}return{missionsRecovered:i,logsRecovered:r}}};V();It();async function va(s){let{repoPath:e,enableContextPivot:t,enableMergeSentinel:n}=s;try{await X(e),new qt(e).analyzeGhostChanges();let r=new qe(e),o=r.detectAndRepairShifts(),a=r.syncLifecycle({enableContextPivot:t,enableMergeSentinel:n}),l=await new Fe(e).recoverFromGitNotes(),{HologramService:p}=await Promise.resolve().then(()=>(Gt(),wa)),u=new p(e),d=mt(O.getInstance(e),e);u.updateTopography(d);let h=u.computeGravityZones();u.updateGravityZones(h);let m="Shadow Sync complete. Code changes indexed and intent logs updated.";return m+=`
759
+ }`,L=await $s(B,D);f.visitModule(L)}catch{let L=new on,A=d;L.visit(u,A),f.calls=L.calls,f.apiCalls=L.apiCalls,f.imports=L.imports}else{let B=new on;B.visit(u,d),f.calls=B.calls,f.apiCalls=B.apiCalls,f.imports=B.imports}}}else f=new on,f.visit(u,d);x.info({file:Se.basename(s),calls:f.calls.size,apiCalls:f.apiCalls.length,depth:r},"Analyzed file");let b=Math.max(0,Ct-o.count),g=Math.max(2,Math.min(10,Math.floor(b/(r<=2?3:5)))),y=f.apiCalls.slice(0,g);f.apiCalls.length>g&&(o.pruned=!0);for(let D of y){if(o.count>=Ct)break;if(o.count++,D.method==="PUBSUB"){let A={type:"event_trigger",name:`PubSub Event: ${D.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(A);let $=D.url.toLowerCase();if(zu.has($)){A.children.push({type:"subscriber",name:"PubSub fan-out omitted",details:"Generic publish call without concrete event/action; skipping global subscriber expansion to avoid false links.",children:[]});continue}let W=n.exports.findByNameGlobal(D.url).concat(n.exports.findByMethodName(D.url));if(D.url.length>10){let O=D.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(O!==D.url){let S=n.exports.findByNameGlobal(O).concat(n.exports.findByMethodName(O));W.push(...S)}}let J=new Set;for(let O of W.slice(0,Ou)){if(J.has(O.file_path)||O.file_path===s)continue;if(J.add(O.file_path),o.count>=Ct)break;o.count++;let S={type:"subscriber",name:`${O.name} (${Se.basename(O.file_path)})`,path:Se.relative(t,O.file_path),line:O.start_line,details:"Potential Subscriber / Handler",children:[]};A.children.push(S),Gt.existsSync(O.file_path)&&!i.has(O.file_path)&&(i.add(O.file_path),await an(O.file_path,S,t,n,i,r+1,o,a))}continue}let P={type:"api_call",name:`${D.method} ${D.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(P);let L=Ba(n,D.url,D.method).slice(0,Du);for(let A of L){if(Gu(A.file_path,s))continue;if(o.count>=Ct)break;o.count++;let $={type:"route",name:A.signature||"Route Handler",path:A.file_path,line:A.start_line,children:[]};if(P.children.push($),Gt.existsSync(A.file_path)&&!i.has(A.file_path)&&(i.add(A.file_path),await an(A.file_path,$,t,n,i,r+1,o,a)),A.capabilities)try{let W=JSON.parse(A.capabilities);if(W.handler){let[J,O]=W.handler.split("@");if(J){let v=J.split("\\").pop();if(v){let T=n.exports.findClassByName(v);if(T){let I=n.exports.findByNameAndFile(O||"",T.file_path),z,j=T.start_line;I.length>0&&(z=Oi(T.file_path,{start:I[0].start_line,end:I[0].end_line},O||"",a),z||(z={start:I[0].start_line,end:I[0].end_line}),j=z.start);let Q={type:"component",name:`${v}${O?" :: "+O:""}`,path:Se.relative(t,T.file_path),line:j,details:"Controller Logic (Macro IR)",children:[]};$.children.push(Q),i.has(T.file_path+(O?`:${O}`:""))||(i.add(T.file_path+(O?`:${O}`:"")),await an(T.file_path,Q,t,n,i,r+1,o,a,z))}}}}}catch{}}}let E=l?l.start-1:0,k=Ku(Yu(u,E)),R=Math.max(0,Ua-o.dataFlowCount),{visibleEdges:w,omittedCount:N}=Zu(k,R);N>0&&(o.pruned=!0);for(let D of w){if(o.count>=Ct)break;o.count++,o.dataFlowCount++,e.children.push({type:"data_flow",name:`${D.symbol} handoff`,line:D.toLines[0],details:Qu(D),children:[]})}N>0&&w.length>0&&o.count<Ct&&(o.count++,e.children.push({type:"data_flow",name:`${N} additional handoffs omitted`,details:R<=w.length?`Suppressed after trace hit the data-flow readability cap (${Ua} nodes per trace).`:"Suppressed to keep file-level trace readable.",children:[]}));let U=f.calls,H=Array.from(U).sort(),C=Ju(r,o.count),M=H.slice(0,C);H.length>C&&(o.pruned=!0);for(let D of M)if(f.imports.has(D)){let P=f.imports.get(D);if(!P.startsWith(".")){if(["react","react-dom"].includes(P))continue;e.children.push({type:"function",name:D,details:`External: ${P}`,children:[]});continue}let B=Ht(P,s,t);if(B&&Gt.existsSync(B)){let L=n.exports.findByNameAndFile(D,B),A=L.length>0?L[0]:null,$=A?`${B}:${A.name}`:B;if(i.has($))e.children.push({type:"function",name:D,details:"Circular / Already Visited",path:Se.relative(t,B),line:A?.start_line,children:[]});else{i.add($);let W={type:A?"component":"file",name:D,details:A?`Imported symbol from ${Se.basename(B)}`:`Imported from ${Se.basename(B)}`,path:Se.relative(t,B),line:A?.start_line,children:[]};e.children.push(W);let J=A?Oi(B,{start:A.start_line,end:A.end_line},D,a):void 0;await an(B,W,t,n,i,r+1,o,a,J)}}}else if(!["log","info","error","warn","print"].includes(D)&&!Va(D)){let P=qu(D,s,n);if(P.length>0){let B=P.find(A=>A.file_path===s),L=B||(P.length===1?P[0]:null);if(L){let A=`${L.file_path}:${L.name}`;if(!i.has(A)){i.add(A);let $={type:"component",name:D,details:`Resolved via global index${B?" (local)":""}`,path:Se.relative(t,L.file_path),line:Oi(L.file_path,{start:L.start_line,end:L.end_line},D,a)?.start,children:[]};e.children.push($);let W=Oi(L.file_path,{start:L.start_line,end:L.end_line},D,a)||{start:L.start_line,end:L.end_line};await an(L.file_path,$,t,n,i,r+1,o,a,W)}}}}}catch(p){x.error({filePath:s,error:p.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:p.message,children:[]})}}async function Qa(s,e){let t=Wi.resolve(e.dir),n=Wi.isAbsolute(s)?s:Wi.resolve(t,s);await Z(async()=>{ge("Execution Trace");let i=Fe();i.start(`Tracing ${_.cyan(e.symbolName||Wi.basename(n))}...`);try{let r=await Ka({repoPath:t,filePath:n,symbolName:e.symbolName});i.stop("Trace complete."),r.isError?console.error(_.red(r.content[0].text)):ue("Flow Results",r.content[0].text,"magenta")}catch(r){throw i.stop(`Trace failed: ${r.message}`),r}finally{await ne(t)}})}import rd from"path";Y();cn();G();import{execSync as Xa}from"child_process";import sd from"path";var Hi=x.child({module:"shadow-trace"}),ln=class{intentLogs;exports;repoPath;hologramService;constructor(e){let{intentLogs:t,exports:n}=F.getInstance(e);this.intentLogs=t,this.exports=n,this.repoPath=e,this.hologramService=new Ae(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=Xa(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
760
+ `).filter(o=>o.trim()!=="");if(r.length===0)return;Hi.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let a=sd.join(this.repoPath,o),c=Xa(`git diff -U0 ${t} -- ${o}`,{cwd:this.repoPath,encoding:"utf-8"}).matchAll(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/g);for(let p of c){let u=parseInt(p[2],10),d=this.exports.findAtLine(a,u);d&&(this.intentLogs.create({mission_id:0,file_path:a,symbol_id:d.id,type:"discovery",content:`Shadow Trace: Modified externally in ${t}`,confidence:.8,symbol_name:d.name,signature:d.signature,commit_sha:null}),Hi.debug({symbol:d.name},"Logged ghost change"),n.push({from:"external",to:`${o}:${d.name}`,pattern:"git-delta",confidence:.8}))}}n.length>0&&this.hologramService.updateGhostBridges(n),Hi.info("Shadow Trace complete.")}catch(i){Hi.warn({err:i.message},"Shadow Trace failed: git diff error.")}}};Y();import{execSync as pn}from"child_process";var zi=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{pn(`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 pn(`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=pn(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
761
+ `);for(let i of n){let[r,o]=i.split(" ");if(o){let a=this.getNote(o);a&&e.set(o,a)}}}catch{}return e}removeNote(e){try{pn(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{pn(`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{pn(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};G();In();var un=x.child({module:"persistence-service"}),et=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new zi(e)}async syncMissionToGitNotes(e){let{missions:t,intentLogs:n}=F.getInstance(this.repoPath),i=t.findById(e);if(!i)throw new Error(`Mission ${e} not found`);if(!i.commit_sha){un.info({missionId:e},"Skipping Git Notes sync because mission has no commit_sha yet");return}un.info({missionId:e,commitSha:i.commit_sha},"Syncing mission to Git Notes");let r=t.getArtifacts(e),o=n.findByMission(e,1e3),a=o.find(p=>p.type==="adr"),l=o.filter(p=>p.type==="decision").map(p=>({content:p.content,symbol_name:p.symbol_name,created_at:p.created_at})),c={version:"1.0",mission:{name:i.name,goal:i.goal,status:i.status,strategy_graph:i.strategy_graph,git_branch:i.git_branch,commit_sha:i.commit_sha,parent_id:i.parent_id,verification_context:i.verification_context,outcome_contract:i.outcome_contract,created_at:i.created_at,updated_at:i.updated_at},artifacts:r,adr:a?a.content:null,decisions:l};this.gitNotes.addNote(i.commit_sha,JSON.stringify(c,null,2))}async syncAllToGitNotes(){let{missions:e}=F.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){un.error({missionId:r.id,...Re(o)},"Failed to sync mission")}}async recoverFromGitNotes(){let e=this.gitNotes.listNotes(),{missions:t,intentLogs:n}=F.getInstance(this.repoPath),i=0,r=0,o=0;for(let[a,l]of e.entries())try{let c=JSON.parse(l);if(c.version!=="1.0")continue;if(t.findByCommitShas([a]).some(h=>h.name===c.mission.name)){un.debug({commitSha:a,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:a,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:a}),r++),c.decisions&&c.decisions.length>0)for(let h of c.decisions)n.create({mission_id:Number(d),symbol_id:null,file_path:null,type:"decision",content:h.content,confidence:1,symbol_name:h.symbol_name,signature:null,commit_sha:a}),r++;un.info({commitSha:a,missionName:c.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(c){o+=1,un.error({commitSha:a,...Re(c)},"Failed to parse Git Note for recovery")}return{missionsRecovered:i,logsRecovered:r,notesFailed:o}}};Y();jt();async function ec(s){let{repoPath:e}=He(s),{enableContextPivot:t,enableMergeSentinel:n}=s;try{await se(e),new ln(e).analyzeGhostChanges();let r=new rt(e),o=r.detectAndRepairShifts(),a=r.syncLifecycle({enableContextPivot:t,enableMergeSentinel:n}),c=await new et(e).recoverFromGitNotes(),{HologramService:p}=await Promise.resolve().then(()=>(cn(),Za)),u=new p(e),d=kt(F.getInstance(e),e);u.updateTopography(d);let h=u.computeGravityZones();u.updateGravityZones(h);let m="Shadow Sync complete. Code changes indexed and intent logs updated.";return m+=`
683
762
  \u269B\uFE0F Hologram: Refreshed architectural map (${h.length} hotspots).`,o.repaired>0&&(m+=`
684
763
  \u2728 Nano-Repair: Fixed ${o.repaired} links.`),m+=`
685
- \u{1F9ED} Lifecycle: contextPivot=${a.contextPivotEnabled?"on":"off"}, mergeSentinel=${a.mergeSentinelEnabled?"on":"off"}, suspended=${a.suspended}, resumed=${a.resumed}, completed=${a.completed}.`,l.missionsRecovered>0&&(m+=`
686
- \u{1F9EC} Re-hydration: Recovered ${l.missionsRecovered} missions.`),{content:[{type:"text",text:m}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}async function Ta(s,e){let t=vu.resolve(s);await Y(async()=>{pe("Shadow Sync");let n=Re();n.start("Synchronizing intelligence lifecycle...");try{let i=await va({repoPath:t,enableContextPivot:e.contextPivot===!0,enableMergeSentinel:e.mergeSentinel===!0});n.stop("Sync complete."),i.isError?console.error(y.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 Q(t)}})}It();V();q();Gt();import ka from"path";V();It();Gt();import et from"path";async function Ra(s){let{repoPath:e}=s;await X(e);let t=O.getInstance(e),n=mt(t,e),r=new Se(e).getSnapshot(),o=[],a=[],c=Object.values(n.layers.Entry.topFiles).map(d=>d.path),l=new Set(Object.values(n.layers.Data.topFiles).map(d=>d.path));for(let d of c){let h=et.isAbsolute(d)?d:et.join(e,d),m=t.imports.findByFile(h);for(let f of m)f.resolved_path&&l.has(et.relative(e,f.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${et.relative(e,d)}\` directly imports Data layer \`${et.relative(e,f.resolved_path)}\`. Should go through Logic.`)}let p=r.gravity?.hotspots||[];for(let d of p){let h=Ct(d.filePath,t);(h.layer==="Utility"||h.layer==="Unknown")&&d.gravity>50&&a.push(`\u{1F6A8} GRAVITY ANOMALY: \`${et.relative(e,d.filePath)}\` has high gravity (${d.gravity.toFixed(0)}) but is classified as ${h.layer}. Consider promoting to Core Logic.`)}for(let d of c){let h=et.isAbsolute(d)?d:et.join(e,d),m=t.exports.findByFile(h);m.length>10&&a.push(`\u{1F388} ENTRY BLOAT: \`${et.relative(e,d)}\` exports ${m.length} symbols. Entry handlers should be thin interfaces.`)}let u=`# \u{1F575}\uFE0F Architectural Scout Report
764
+ \u{1F9ED} Lifecycle: contextPivot=${a.contextPivotEnabled?"on":"off"}, mergeSentinel=${a.mergeSentinelEnabled?"on":"off"}, suspended=${a.suspended}, resumed=${a.resumed}, completed=${a.completed}.`,(c.missionsRecovered>0||c.logsRecovered>0)&&(m+=`
765
+ \u{1F9EC} Re-hydration: Recovered ${c.missionsRecovered} missions and ${c.logsRecovered} logs.`),c.notesFailed>0&&(m+=`
766
+ \u26A0\uFE0F Re-hydration: ${c.notesFailed} Git Note entries failed recovery (see logs).`),{content:[{type:"text",text:m}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}async function tc(s,e){let t=rd.resolve(s);await Z(async()=>{ge("Shadow Sync");let n=Fe();n.start("Synchronizing intelligence lifecycle...");try{let i=await ec({repoPath:t,enableContextPivot:e.contextPivot===!0,enableMergeSentinel:e.mergeSentinel===!0});n.stop("Sync complete."),i.isError?console.error(_.red(i.content[0].text)):(console.log(""),console.log(i.content[0].text),console.log(""))}catch(i){throw n.stop(`Sync failed: ${i.message}`),i}finally{await ne(t)}})}jt();Y();G();cn();import ic from"path";Y();jt();cn();import Vt from"path";function Bi(s,e){return(Vt.isAbsolute(e)?Vt.relative(s,e):e).replace(/^\.?[\\/]/,"")}async function nc(s){let{repoPath:e}=s;await se(e);let t=F.getInstance(e),n=kt(t,e),r=new Ae(e).getSnapshot(),o=[],a=[],l=Object.values(n.layers.Entry.topFiles).map(d=>d.path),c=new Set(Object.values(n.layers.Data.topFiles).map(d=>d.path));for(let d of l){let h=Vt.isAbsolute(d)?d:Vt.join(e,d),m=t.imports.findByFile(h);for(let f of m)f.resolved_path&&c.has(Vt.relative(e,f.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${Bi(e,d)}\` directly imports Data layer \`${Bi(e,f.resolved_path)}\`. Should go through Logic.`)}let p=r.gravity?.hotspots||[];for(let d of p){let h=Ut(d.filePath,t);(h.layer==="Utility"||h.layer==="Unknown")&&d.gravity>50&&a.push(`\u{1F6A8} GRAVITY ANOMALY: \`${Bi(e,d.filePath)}\` has high gravity (${d.gravity.toFixed(0)}) but is classified as ${h.layer}. Review for boundary drift and central coupling.`)}for(let d of l){let h=Vt.isAbsolute(d)?d:Vt.join(e,d),m=t.exports.findTopLevelByFile(h);m.length>10&&a.push(`\u{1F388} ENTRY BLOAT: \`${Bi(e,d)}\` exports ${m.length} symbols. Entry handlers should be thin interfaces.`)}let u=`# \u{1F575}\uFE0F Architectural Scout Report
687
767
 
688
768
  `;return o.length===0&&a.length===0?u+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
689
769
  `:(o.length>0&&(u+=`## \u274C Structural Violations
@@ -692,177 +772,184 @@ ${u}
692
772
  `),a.length>0&&(u+=`## \u26A0\uFE0F Architectural Warnings
693
773
  `,a.forEach(d=>u+=`- ${d}
694
774
  `),u+=`
695
- `)),{content:[{type:"text",text:u}]}}async function Ca(s,e,t){let n=e?ka.resolve(process.cwd(),e):process.cwd();if(s==="init"){S.info('Running full initialization (same as "index --force")...'),await X(n,void 0,!0,!0);return}if(s==="tree"){S.info('For tree view, please use the "tree" command.');return}if(s==="topography"){await X(n);let i=O.getInstance(n),r=mt(i,n);console.log(`
696
- \u{1F3D7}\uFE0F Architecture Summary for ${ka.basename(n)}
775
+ `)),{content:[{type:"text",text:u}]}}async function sc(s,e,t){let n=e?ic.resolve(process.cwd(),e):process.cwd();if(s==="init"){x.info('Running full initialization (same as "index --force")...'),await se(n,void 0,!0,!0);return}if(s==="tree"){x.info('For tree view, please use the "tree" command.');return}if(s==="topography"){await se(n);let i=F.getInstance(n),r=kt(i,n);console.log(`
776
+ \u{1F3D7}\uFE0F Architecture Summary for ${ic.basename(n)}
697
777
  `),console.log(`Detected Pattern: **${r.pattern}** (Confidence: ${r.patternConfidence.toFixed(0)}%)`),r.insights.length>0&&(console.log(`
698
- Insights:`),r.insights.forEach(l=>console.log(`- ${l}`))),console.log(`
699
- Layer Distribution:`);let o=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],a=Object.values(r.layers).reduce((l,p)=>l+p.count,0),c=l=>{switch(l){case"Entry":return"\u{1F6AA}";case"Logic":return"\u2699\uFE0F";case"Data":return"\u{1F4BE}";case"Utility":return"\u{1F527}";case"Infrastructure":return"\u{1F3D7}\uFE0F";case"Test":return"\u{1F9EA}";case"Types":return"\u{1F4DD}";default:return"\u2753"}};o.forEach(l=>{let p=r.layers[l],u=a>0?(p.count/a*100).toFixed(1):"0.0";console.log(`${c(l)} ${l.padEnd(14)} | ${p.count.toString().padStart(5)} files | ${u}%`)}),console.log(`
700
- Top Files by Layer:`),o.forEach(l=>{let p=r.layers[l];p.count!==0&&(console.log(`
701
- ${c(l)} ${l}`),p.topFiles.forEach(u=>{console.log(` - ${u.path} (${u.confidence}% conf)`),u.signals.length>0&&console.log(` \u2514\u2500 ${u.signals.slice(0,1).join(", ")}`)}))});return}if(s==="scout"){let i=await Ra({repoPath:n});console.log(i.content[0].text);return}if(s==="hologram"){let i=new Se(n);console.log(JSON.stringify(i.getSnapshot(),null,2));return}S.error(`Unknown recon mode: ${s}. Available: init, topography, scout, hologram`)}import _n from"path";V();var ht=class s{static extractKeywords(e){if(!e)return[];let t=new Set(["the","and","for","with","from","this","that","into","onto","http","https","www","com","org","net","api"]),i=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>2&&!t.has(r));return Array.from(new Set(i))}static calculateKeywordCoverageFromKeywords(e,t){if(!e||!t||t.length===0)return 0;let n=e.toLowerCase();return t.filter(r=>n.includes(r)).length/t.length}static calculateKeywordCoverage(e,t){return s.calculateKeywordCoverageFromKeywords(e,s.extractKeywords(t))}static extractSnippet(e,t,n=300){if(!e||!t)return"";let i=s.extractKeywords(t);if(i.length===0)return e.slice(0,n)+"...";let r=e.split(`
702
- `),o=new Array(r.length).fill(0);for(let d=0;d<r.length;d++){let h=r[d].toLowerCase(),m=0,f=0;for(let _ of i)h.includes(_)&&(m++,f++);(h.includes("export ")||h.includes("class ")||h.includes("function ")||h.includes("interface "))&&(m+=1),o[d]=f*10+m}let a=0,c=-1,l=5;for(let d=0;d<=r.length-l;d++){let h=0;for(let m=0;m<l;m++)h+=o[d+m];h>c&&(c=h,a=d)}if(c<=0)return e.slice(0,n).trim()+"...";let u=r.slice(a,a+l).join(`
778
+ Insights:`),r.insights.forEach(c=>console.log(`- ${c}`))),console.log(`
779
+ Layer Distribution:`);let o=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],a=Object.values(r.layers).reduce((c,p)=>c+p.count,0),l=c=>{switch(c){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(c=>{let p=r.layers[c],u=a>0?(p.count/a*100).toFixed(1):"0.0";console.log(`${l(c)} ${c.padEnd(14)} | ${p.count.toString().padStart(5)} files | ${u}%`)}),console.log(`
780
+ Top Files by Layer:`),o.forEach(c=>{let p=r.layers[c];p.count!==0&&(console.log(`
781
+ ${l(c)} ${c}`),p.topFiles.forEach(u=>{console.log(` - ${u.path} (${u.confidence}% conf)`),u.signals.length>0&&console.log(` \u2514\u2500 ${u.signals.slice(0,1).join(", ")}`)}))});return}if(s==="scout"){let i=await nc({repoPath:n});console.log(i.content[0].text);return}if(s==="hologram"){let i=new Ae(n);console.log(JSON.stringify(i.getSnapshot(),null,2));return}x.error(`Unknown recon mode: ${s}. Available: init, topography, scout, hologram`)}import An from"path";Y();var It=class s{static extractKeywords(e){if(!e)return[];let t=new Set(["the","and","for","with","from","this","that","into","onto","http","https","www","com","org","net","api"]),i=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>2&&!t.has(r));return Array.from(new Set(i))}static calculateKeywordCoverageFromKeywords(e,t){if(!e||!t||t.length===0)return 0;let n=e.toLowerCase();return t.filter(r=>n.includes(r)).length/t.length}static calculateKeywordCoverage(e,t){return s.calculateKeywordCoverageFromKeywords(e,s.extractKeywords(t))}static extractSnippet(e,t,n=300){if(!e||!t)return"";let i=s.extractKeywords(t);if(i.length===0)return e.slice(0,n)+"...";let r=e.split(`
782
+ `),o=new Array(r.length).fill(0);for(let d=0;d<r.length;d++){let h=r[d].toLowerCase(),m=0,f=0;for(let b of i)h.includes(b)&&(m++,f++);(h.includes("export ")||h.includes("class ")||h.includes("function ")||h.includes("interface "))&&(m+=1),o[d]=f*10+m}let a=0,l=-1,c=5;for(let d=0;d<=r.length-c;d++){let h=0;for(let m=0;m<c;m++)h+=o[d+m];h>l&&(l=h,a=d)}if(l<=0)return e.slice(0,n).trim()+"...";let u=r.slice(a,a+c).join(`
703
783
  `).trim();return a>0&&(u=`...
704
- `+u),a+l<r.length&&(u=u+`
705
- ...`),u.length>n?u.slice(0,n)+"...":u}static calculateLexicalScore(e,t){if(!e||!t)return 0;let n=s.extractKeywords(t);if(n.length===0)return 0;let i=0,r=e.toLowerCase();for(let o of n)if(r.includes(o)){i+=1;let a=new RegExp(`\\b${o}`,"gi"),c=r.match(a);c&&(i+=Math.min(c.length*.2,2)),new RegExp(`(class|function|export|interface|enum|type)\\s+${o}`,"i").test(e)&&(i+=1.5)}return i/n.length}};Ae();V();q();var ft=S.child({module:"clean-sweep"}),Ps=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=O.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){ft.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();ft.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++,ft.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,ft.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 ft.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},Ms=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)}))}},Ns=class{missions;constructor(e){let{missions:t}=O.getInstance(e);this.missions=t}findColdMissions(){let e=Math.floor(Date.now()/1e3)-604800,t=this.missions.findColdMissions(e,10);return ft.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},Ri=class{pruner;scorer;compactor;constructor(e){this.pruner=new Ps(e),this.scorer=new Ms,this.compactor=new Ns(e)}runMaintenance(){ft.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return ft.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};V();q();var Ia=S.child({module:"lineage-service"}),yn=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=So(this.repoPath,e);if(t.length===0)return[];let{missions:n}=O.getInstance(this.repoPath),r=n.findByCommitShas(t).map(o=>o.id);return r.length>0&&Ia.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return Ia.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var Tu={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},We=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 Tu[n]}};q();function Ru(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 ku(s,e){let t=Ru(s.toLowerCase(),e.toLowerCase()),n=Math.max(s.length,e.length);return Math.round((n-t)/n*100)}function La(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 Cu(s,e){let t=La(e),n=s.toLowerCase();if(t.map(o=>o[0].toLowerCase()).join("")===n)return!0;let r=0;for(let o of t){if(r>=s.length)break;let a=o.toLowerCase();if(a.startsWith(n.slice(r))){r=s.length;break}a[0]===n[r]&&r++}return r===s.length}function Iu(s,e){return La(e).map(i=>i[0].toLowerCase()).join("")===s.toLowerCase()}function Lu(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 Iu(s,e)?{matchType:"acronym",score:75}:Cu(s,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:ku(s,e)*.6}}function bn(s,e,t=50,n=5){let i=[];for(let r of e){let{matchType:o,score:a}=Lu(s,r);if(a>=t){let l={exact:1e3,"exact-case-insensitive":900,prefix:800,suffix:700,substring:600,acronym:550,"camel-case":500,levenshtein:100}[o]+a;i.push({match:r,score:a,matchType:o,rank:l})}}return i.sort((r,o)=>o.rank!==r.rank?o.rank-r.rank:o.score!==r.score?o.score-r.score:r.match.length-o.match.length),i.slice(0,n)}Gt();var gt=class s{constructor(e){this.repoPath=e}get filesRepo(){return O.getInstance(this.repoPath).files}get exportsRepo(){return O.getInstance(this.repoPath).exports}get intentLogsRepo(){return O.getInstance(this.repoPath).intentLogs}static normalizeFileType(e){if(e==null)return;let t=Array.isArray(e)?e:e.split(",").map(n=>n.trim().replace(/^\./,""));return t.filter(Boolean).length?t:void 0}static matchesFilters(e,t,n,i){if(t.fileType?.length){let r=e.replace(/^.*\./,"").toLowerCase();if(!t.fileType.some(o=>o.toLowerCase()===r))return!1}if(t.layer!=null||t.excludeLayers&&t.excludeLayers.length>0){let r=i!=null?We.mapClassificationToTier(i):We.classify(e);if(t.layer!=null&&r!==t.layer||t.excludeLayers?.includes(r))return!1}return!0}async searchByPath(e,t,n,i,r,o=!1){let a=this.extractPathKeywords(e),c=this.isLikelySymbolQuery(e),l=this.filesRepo.findByPathKeywords(a,Math.min((t??50)*(r?ge.FILTERED_QUERY_LIMIT_MULTIPLIER:1),ke.MAX_LIMIT)).map(b=>({...b,source:"path",keywordHits:this.countPathKeywordHits(b.path,a),relevance:this.scorePathResult(b.path,a,"path",c)}));r&&(l=l.filter(b=>s.matchesFilters(b.path,i,b.mtime,b.classification))),c&&a.length>=3&&(l=l.filter(b=>b.source==="symbol"||b.keywordHits>=2));let p=this.findSymbolBackedPaths(e,a,t*3),u=new Set(l.map(b=>b.path));for(let b of p){if(u.has(b))continue;let w=this.filesRepo.findByPath(b);w&&(r&&!s.matchesFilters(w.path,i,w.mtime,w.classification)||(l.push({...w,source:"symbol",keywordHits:this.countPathKeywordHits(w.path,a),relevance:this.scorePathResult(w.path,a,"symbol",c)}),u.add(b)))}l.sort((b,w)=>w.relevance-b.relevance),r||(l=l.slice(0,Math.min(t*4,ke.MAX_LIMIT)));let d=l.length;if(d===0)return{content:[{type:"text",text:`No indexed files match path/filename: "${e}".
784
+ `+u),a+c<r.length&&(u=u+`
785
+ ...`),u.length>n?u.slice(0,n)+"...":u}static calculateLexicalScore(e,t){if(!e||!t)return 0;let n=s.extractKeywords(t);if(n.length===0)return 0;let i=0,r=e.toLowerCase();for(let o of n)if(r.includes(o)){i+=1;let a=new RegExp(`\\b${o}`,"gi"),l=r.match(a);l&&(i+=Math.min(l.length*.2,2)),new RegExp(`(class|function|export|interface|enum|type)\\s+${o}`,"i").test(e)&&(i+=1.5)}return i/n.length}};Ve();Y();G();var Lt=x.child({module:"clean-sweep"}),Zs=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=F.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){Lt.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();Lt.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++,Lt.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,Lt.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 Lt.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},Xs=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)}))}},er=class{missions;constructor(e){let{missions:t}=F.getInstance(e);this.missions=t}findColdMissions(){let e=Math.floor(Date.now()/1e3)-604800,t=this.missions.findColdMissions(e,10);return Lt.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},Ui=class{pruner;scorer;compactor;constructor(e){this.pruner=new Zs(e),this.scorer=new Xs,this.compactor=new er(e)}runMaintenance(){Lt.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return Lt.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};Y();G();var rc=x.child({module:"lineage-service"}),Ln=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=Yo(this.repoPath,e);if(t.length===0)return[];let{missions:n}=F.getInstance(this.repoPath),r=n.findByCommitShas(t).map(o=>o.id);return r.length>0&&rc.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return rc.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var od={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},tt=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 od[n]}};G();function ad(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 cd(s,e){let t=ad(s.toLowerCase(),e.toLowerCase()),n=Math.max(s.length,e.length);return Math.round((n-t)/n*100)}function oc(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 ld(s,e){let t=oc(e),n=s.toLowerCase();if(t.map(o=>o[0].toLowerCase()).join("")===n)return!0;let r=0;for(let o of t){if(r>=s.length)break;let a=o.toLowerCase();if(a.startsWith(n.slice(r))){r=s.length;break}a[0]===n[r]&&r++}return r===s.length}function pd(s,e){return oc(e).map(i=>i[0].toLowerCase()).join("")===s.toLowerCase()}function ud(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 pd(s,e)?{matchType:"acronym",score:75}:ld(s,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:cd(s,e)*.6}}function Mn(s,e,t=50,n=5){let i=[];for(let r of e){let{matchType:o,score:a}=ud(s,r);if(a>=t){let c={exact:1e3,"exact-case-insensitive":900,prefix:800,suffix:700,substring:600,acronym:550,"camel-case":500,levenshtein:100}[o]+a;i.push({match:r,score:a,matchType:o,rank:c})}}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)}cn();var Mt=class s{constructor(e){this.repoPath=e}get filesRepo(){return F.getInstance(this.repoPath).files}get exportsRepo(){return F.getInstance(this.repoPath).exports}get intentLogsRepo(){return F.getInstance(this.repoPath).intentLogs}static normalizeFileType(e){if(e==null)return;let t=Array.isArray(e)?e:e.split(",").map(n=>n.trim().replace(/^\./,""));return t.filter(Boolean).length?t:void 0}static matchesFilters(e,t,n,i){if(t.fileType?.length){let r=e.replace(/^.*\./,"").toLowerCase();if(!t.fileType.some(o=>o.toLowerCase()===r))return!1}if(t.layer!=null||t.excludeLayers&&t.excludeLayers.length>0){let r=i!=null?tt.mapClassificationToTier(i):tt.classify(e);if(t.layer!=null&&r!==t.layer||t.excludeLayers?.includes(r))return!1}return!0}async searchByPath(e,t,n,i,r,o=!1){let a=this.extractPathKeywords(e),l=this.isLikelySymbolQuery(e),c=this.filesRepo.findByPathKeywords(a,Math.min((t??50)*(r?ve.FILTERED_QUERY_LIMIT_MULTIPLIER:1),We.MAX_LIMIT)).map(y=>({...y,source:"path",keywordHits:this.countPathKeywordHits(y.path,a),relevance:this.scorePathResult(y.path,a,"path",l)}));r&&(c=c.filter(y=>s.matchesFilters(y.path,i,y.mtime,y.classification))),l&&a.length>=3&&(c=c.filter(y=>y.source==="symbol"||y.keywordHits>=2));let p=this.findSymbolBackedPaths(e,a,t*3),u=new Set(c.map(y=>y.path));for(let y of p){if(u.has(y))continue;let E=this.filesRepo.findByPath(y);E&&(r&&!s.matchesFilters(E.path,i,E.mtime,E.classification)||(c.push({...E,source:"symbol",keywordHits:this.countPathKeywordHits(E.path,a),relevance:this.scorePathResult(E.path,a,"symbol",l)}),u.add(y)))}c.sort((y,E)=>E.relevance-y.relevance),r||(c=c.slice(0,Math.min(t*4,We.MAX_LIMIT)));let d=c.length;if(d===0)return{content:[{type:"text",text:`No indexed files match path/filename: "${e}".
706
786
 
707
- If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};let h=b=>b.replace(this.repoPath,"").replace(/^\//,"");if(o){let w=new Se(this.repoPath).getSection("gravity"),x=new Map;if(w?.hotspots)for(let E of w.hotspots){let T=x.get(E.filePath)||0;x.set(E.filePath,T+E.gravity)}let R=l.map(E=>{let T=x.get(E.path)||0,I=E.classification?We.mapClassificationToTier(E.classification):We.classify(E.path);return{...E,gravity:T,layer:I}});R.sort((E,T)=>T.gravity!==E.gravity?T.gravity-E.gravity:T.relevance!==E.relevance?T.relevance-E.relevance:E.path.localeCompare(T.path));let k=R.slice(n,n+t),D=n+t<d;if(k.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${d}.`}]};let U=D?`
787
+ If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};let h=y=>y.replace(this.repoPath,"").replace(/^\//,"");if(o){let E=new Ae(this.repoPath).getSection("gravity"),k=new Map;if(E?.hotspots)for(let C of E.hotspots){let M=k.get(C.filePath)||0;k.set(C.filePath,M+C.gravity)}let R=c.map(C=>{let M=k.get(C.path)||0,D=C.classification?tt.mapClassificationToTier(C.classification):tt.classify(C.path);return{...C,gravity:M,layer:D}});R.sort((C,M)=>M.gravity!==C.gravity?M.gravity-C.gravity:M.relevance!==C.relevance?M.relevance-C.relevance:C.path.localeCompare(M.path));let w=R.slice(n,n+t),N=n+t<d;if(w.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${d}.`}]};let U=N?`
708
788
  > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"";return{content:[{type:"text",text:`# Resolved paths: "${e}" (Ranked by Gravity)
709
789
 
710
- Showing ${k.length} of ${d} file(s) (offset: ${n}, limit: ${t})${U}
790
+ Showing ${w.length} of ${d} file(s) (offset: ${n}, limit: ${t})${U}
711
791
 
712
- `+k.map((E,T)=>{let I=E.gravity>50?" \u269B\uFE0F":E.gravity>0?" \u2022":"",M=E.gravity>0?` [G:${Math.round(E.gravity)}]`:"",N=E.source==="symbol"?" [via symbol]":"";return`${n+T+1}. \`${h(E.path)}\` (${E.layer})${I}${M}${N}`}).join(`
792
+ `+w.map((C,M)=>{let D=C.gravity>50?" \u269B\uFE0F":C.gravity>0?" \u2022":"",P=C.gravity>0?` [G:${Math.round(C.gravity)}]`:"",B=C.source==="symbol"?" [via symbol]":"";return`${n+M+1}. \`${h(C.path)}\` (${C.layer})${D}${P}${B}`}).join(`
713
793
  `)+`
714
794
 
715
- > **Legend**: \u269B\uFE0F = High-gravity hotspot (>50), \u2022 = Has gravity, G = Gravity score`}]}}let m=l.slice(n,n+t),f=n+t<d;if(m.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${d}.`}]};let _=f?`
795
+ > **Legend**: \u269B\uFE0F = High-gravity hotspot (>50), \u2022 = Has gravity, G = Gravity score`}]}}let m=c.slice(n,n+t),f=n+t<d;if(m.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${d}.`}]};let b=f?`
716
796
  > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"";return{content:[{type:"text",text:`# Resolved paths: "${e}"
717
797
 
718
- Showing ${m.length} of ${d} file(s) (offset: ${n}, limit: ${t})${_}
798
+ Showing ${m.length} of ${d} file(s) (offset: ${n}, limit: ${t})${b}
719
799
 
720
- `+m.map((b,w)=>{let x=b.source==="symbol"?" [via symbol]":"";return`${n+w+1}. \`${h(b.path)}\`${b.classification?` (${b.classification})`:""}${x}`}).join(`
721
- `)}]}}async searchByConcept(e,t,n,i,r,o=!1,a){S.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let c=await ts(e),l=x=>x.replace(this.repoPath,"").replace(/^\//,""),p=ht.extractKeywords(e),u=this.classifyConceptQuery(e,p),d=this.getConceptConfidenceFloor(u.profile),h=this.getIntentConfidenceFloor(u.profile),m=Math.min(Math.max((t+n)*2,t),ke.MAX_LIMIT),f=await this.findConceptMatches(e,c,i,r,m,0),_=c?await this.findIntentLogMatches(c,5):[],g=f.filter(x=>(x.score||0)>=d),b=f.filter(x=>(x.score||0)<d),w=_.filter(x=>(x.score||0)>=h);if(g.length>0){let x=g.length,R=g.slice(n,n+t),D=n+t<x?`
800
+ `+m.map((y,E)=>{let k=y.source==="symbol"?" [via symbol]":"";return`${n+E+1}. \`${h(y.path)}\`${y.classification?` (${y.classification})`:""}${k}`}).join(`
801
+ `)}]}}async searchByConcept(e,t,n,i,r,o=!1,a){x.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let l=await Es(e),c=k=>k.replace(this.repoPath,"").replace(/^\//,""),p=It.extractKeywords(e),u=this.classifyConceptQuery(e,p),d=this.getConceptConfidenceFloor(u.profile),h=this.getIntentConfidenceFloor(u.profile),m=Math.min(Math.max((t+n)*2,t),We.MAX_LIMIT),f=await this.findConceptMatches(e,l,i,r,m,0),b=l?await this.findIntentLogMatches(l,5):[],g=f.filter(k=>(k.score||0)>=d),y=f.filter(k=>(k.score||0)<d),E=b.filter(k=>(k.score||0)>=h);if(g.length>0){let k=g.length,R=g.slice(n,n+t),N=n+t<k?`
722
802
  > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",U=o?`
723
- > _Compact mode: snippets omitted_`:x>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",P=a&&a>0?`
724
- > _Adaptive compression enabled under token budget._`:"",E=b.length>0?`
725
- > _${b.length} lower-confidence candidate(s) were suppressed below the ${Math.round(d*100)}% evidence floor._`:"",T=`# Semantic Concept Search: "${e}"
803
+ > _Compact mode: snippets omitted_`:k>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",H=a&&a>0?`
804
+ > _Adaptive compression enabled under token budget._`:"",C=y.length>0?`
805
+ > _${y.length} lower-confidence candidate(s) were suppressed below the ${Math.round(d*100)}% evidence floor._`:"",M=`# Semantic Concept Search: "${e}"
726
806
 
727
- Showing ${R.length} of ${x} high-confidence file(s) (offset: ${n}, limit: ${t})${D}${U}${P}${E}
807
+ Showing ${R.length} of ${k} file(s) above the ${Math.round(d*100)}% evidence floor (offset: ${n}, limit: ${t})${N}${U}${H}${C}
728
808
 
729
- `,M=new Se(this.repoPath).getSection("gravity"),N=new Map;if(M?.hotspots)for(let A of M.hotspots)N.set(A.filePath,A.gravity);let $=R.map((A,H)=>{let F=l(A.path),v=Math.round((A.score||0)*100),B=N.get(A.path)?" \u269B\uFE0F":"";return`${n+H+1}. \`${F}\`${B} (${v}% evidence) - ${A.summary||"No summary"}`}),W=R.map((A,H)=>{let F=l(A.path),v=Math.round((A.score||0)*100),C=N.get(A.path),B=C?" \u269B\uFE0F **CORE**":"",j=C&&C>50?`
730
- > \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${C.toFixed(0)}). Modifications may have significant architectural impact.`:"",J=`## ${n+H+1}. ${F}${B} (${v}% Evidence Match)
731
- > **Rationale**: ${A.rationale}${j}
809
+ `,P=new Ae(this.repoPath).getSection("gravity"),B=new Map;if(P?.hotspots)for(let W of P.hotspots)B.set(W.filePath,W.gravity);let L=R.map((W,J)=>{let O=c(W.path),S=Math.round((W.score||0)*100),T=B.get(W.path)?" \u269B\uFE0F":"";return`${n+J+1}. \`${O}\`${T} (${S}% evidence) - ${W.summary||"No summary"}`}),A=R.map((W,J)=>{let O=c(W.path),S=Math.round((W.score||0)*100),v=B.get(W.path),T=v?" \u269B\uFE0F **CORE**":"",I=v&&v>50?`
810
+ > \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${v.toFixed(0)}). Modifications may have significant architectural impact.`:"",z=`## ${n+J+1}. ${O}${T} (${S}% Evidence Match)
811
+ > **Rationale**: ${W.rationale}${I}
732
812
 
733
- `+(A.snippet?`**Matched Snippet**:
813
+ `+(W.snippet?`**Matched Snippet**:
734
814
  \`\`\`typescript
735
- ${A.snippet}
815
+ ${W.snippet}
736
816
  \`\`\`
737
817
 
738
- `:"")+`**Summary**: ${A.summary||"No summary available"}
739
- `;return{index:n+H+1,relativePath:F,matchPct:v,gravity:C,text:J}}),L="";if(o)L=T+$.join(`
740
- `);else if(a&&a>0){let A=Math.max(80,Math.floor(a*.12)),H=this.estimateTokenCount(T),F=[],v=[];for(let C of W){let B=this.estimateTokenCount(C.text),j=H+B<=a-A;if(F.length<2||j)F.push(C.text),H+=B;else{let J=C.gravity?" \u269B\uFE0F":"";v.push(`${C.index}. \`${C.relativePath}\`${J} (${C.matchPct}% Evidence Match)`)}}L=T+F.join(`
741
- `),v.length>0&&(L+=`
818
+ `:"")+`**Summary**: ${W.summary||"No summary available"}
819
+ `;return{index:n+J+1,relativePath:O,matchPct:S,gravity:v,text:z}}),$="";if(o)$=M+L.join(`
820
+ `);else if(a&&a>0){let W=Math.max(80,Math.floor(a*.12)),J=this.estimateTokenCount(M),O=[],S=[];for(let v of A){let T=this.estimateTokenCount(v.text),I=J+T<=a-W;if(O.length<2||I)O.push(v.text),J+=T;else{let z=v.gravity?" \u269B\uFE0F":"";S.push(`${v.index}. \`${v.relativePath}\`${z} (${v.matchPct}% Evidence Match)`)}}$=M+O.join(`
821
+ `),S.length>0&&($+=`
742
822
 
743
- ### Folded Lower-Relevance Matches (${v.length})
823
+ ### Folded Lower-Relevance Matches (${S.length})
744
824
  _Expanded blocks omitted to stay within token budget._
745
- `+v.join(`
746
- `))}else L=T+W.map(A=>A.text).join(`
747
- `);if(w.length>0){let A=`
825
+ `+S.join(`
826
+ `))}else $=M+A.map(W=>W.text).join(`
827
+ `);if(E.length>0){let W=`
748
828
 
749
829
  ---
750
- ## Intent Vectors (${w.length} matching decision(s))
830
+ ## Intent Vectors (${E.length} matching decision(s))
751
831
 
752
- `+w.map((F,v)=>{let C=Math.round((F.score||0)*100),B=F.symbolName?` \`${F.symbolName}\``:"",j=F.missionId?` [Mission #${F.missionId}]`:"",J=F.content.length>200?F.content.slice(0,200)+"...":F.content;return o?`${v+1}. **[${F.type}]**${B}${j} (${C}%) - ${J}`:`### ${v+1}. [${F.type}]${B}${j} (${C}% Evidence Match)
753
- > ${J}
832
+ `+E.map((O,S)=>{let v=Math.round((O.score||0)*100),T=O.symbolName?` \`${O.symbolName}\``:"",I=O.missionId?` [Mission #${O.missionId}]`:"",z=O.content.length>200?O.content.slice(0,200)+"...":O.content;return o?`${S+1}. **[${O.type}]**${T}${I} (${v}%) - ${z}`:`### ${S+1}. [${O.type}]${T}${I} (${v}% Evidence Match)
833
+ > ${z}
754
834
  `}).join(`
755
- `),H=`
835
+ `),J=`
756
836
 
757
837
  ---
758
- ## Intent Vectors (${w.length} matching decision(s))
838
+ ## Intent Vectors (${E.length} matching decision(s))
759
839
 
760
- `+w.slice(0,2).map((F,v)=>{let C=Math.round((F.score||0)*100),B=F.symbolName?` \`${F.symbolName}\``:"",j=F.missionId?` [Mission #${F.missionId}]`:"";return`${v+1}. **[${F.type}]**${B}${j} (${C}%)`}).join(`
761
- `)+(w.length>2?`
762
- > Additional intent matches folded by token budget.`:"");a&&a>0&&this.estimateTokenCount(L+A)>a?L+=H:L+=A}return{content:[{type:"text",text:L}]}}if(n===0){let x=this.filesRepo.getStats(),R=e.toLowerCase().split(/\s+/),k=this.filesRepo.findByPathKeywords(R,t);if(r&&(k=k.filter(D=>s.matchesFilters(D.path,i,D.mtime,D.classification))),k.length>0)return{content:[{type:"text",text:`# Concept Search: "${e}"
840
+ `+E.slice(0,2).map((O,S)=>{let v=Math.round((O.score||0)*100),T=O.symbolName?` \`${O.symbolName}\``:"",I=O.missionId?` [Mission #${O.missionId}]`:"";return`${S+1}. **[${O.type}]**${T}${I} (${v}%)`}).join(`
841
+ `)+(E.length>2?`
842
+ > Additional intent matches folded by token budget.`:"");a&&a>0&&this.estimateTokenCount($+W)>a?$+=J:$+=W}return{content:[{type:"text",text:$}]}}if(n===0){let k=this.filesRepo.getStats(),R=e.toLowerCase().split(/\s+/),w=this.filesRepo.findByPathKeywords(R,t);if(r&&(w=w.filter(N=>s.matchesFilters(N.path,i,N.mtime,N.classification))),w.length>0)return{content:[{type:"text",text:`# Concept Search: "${e}"
763
843
 
764
- \u26A0\uFE0F No high-confidence semantic matches cleared the ${Math.round(d*100)}% evidence floor (${x.withSummary}/${x.total} summaries indexed).
844
+ \u26A0\uFE0F No semantic matches cleared the ${Math.round(d*100)}% evidence floor (${k.withSummary}/${k.total} summaries indexed).
765
845
 
766
- Found ${k.length} file(s) with matching paths:
846
+ Found ${w.length} file(s) with matching paths:
767
847
 
768
- `+k.map((U,P)=>`${P+1}. \`${l(U.path)}\` (${U.classification||"Unknown"})`).join(`
769
- `)}]};if(b.length>0){let D=b.slice(0,Math.min(3,t)).map((U,P)=>{let E=Math.round((U.score||0)*100);return`${P+1}. \`${l(U.path)}\` (${E}% evidence) - ${U.summary||"No summary"}`}).join(`
848
+ `+w.map((U,H)=>`${H+1}. \`${c(U.path)}\` (${U.classification||"Unknown"})`).join(`
849
+ `)}]};if(y.length>0){let N=y.slice(0,Math.min(3,t)).map((U,H)=>{let C=Math.round((U.score||0)*100);return`${H+1}. \`${c(U.path)}\` (${C}% evidence) - ${U.summary||"No summary"}`}).join(`
770
850
  `);return{content:[{type:"text",text:`# Semantic Concept Search: "${e}"
771
851
 
772
- No high-confidence semantic matches cleared the evidence floor (${Math.round(d*100)}% required for ${u.profile} queries).
852
+ No semantic matches cleared the evidence floor (${Math.round(d*100)}% required for ${u.profile} queries).
773
853
 
774
854
  Low-confidence candidates were suppressed instead of being presented as relevant matches:
775
- ${D?`
776
- ${D}
855
+ ${N?`
856
+ ${N}
777
857
 
778
858
  `:`
779
- `}Try adding distinctive identifiers, narrowing the concept, or using shadow_search_symbol({ query: "${e}", repoPath }).`}]}}}return{content:[{type:"text",text:`No high-confidence files found matching concept: "${e}"
859
+ `}Try adding distinctive identifiers, narrowing the concept, or using shadow_search_symbol({ query: "${e}", repoPath }).`}]}}}return{content:[{type:"text",text:`No files cleared the evidence floor for concept: "${e}"
780
860
 
781
- Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}async searchBySymbol(e,t,n,i,r,o="any"){let a=e.toLowerCase(),c=E=>E.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 E=this.exportsRepo.getAllNames(5e3),T=e.trim().split(/\s+/).filter(M=>M.length>0);if(T.length>1){let M=new Map;for(let $ of T){let W=bn($,E,40,20);for(let L of W){let A=M.get(L.match);A?(A.terms.push($),A.bestScore=Math.max(A.bestScore,L.score)):M.set(L.match,{terms:[$],bestScore:L.score})}}let N=Array.from(M.entries()).sort(($,W)=>W[1].terms.length!==$[1].terms.length?W[1].terms.length-$[1].terms.length:W[1].bestScore-$[1].bestScore).slice(0,10);if(N.length>0){let $=N.map(([W,L])=>{let A=L.terms.join(", ");return` \u2022 \`${W}\` (matches: ${A}, ${Math.round(L.bestScore)}%)`}).join(`
861
+ Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}async searchBySymbol(e,t,n,i,r,o="any"){let a=e.toLowerCase(),l=C=>C.replace(this.repoPath,"").replace(/^\//,""),c=this.buildFtsQuery(e,o),p;try{p=this.exportsRepo.findFts(c,t+50)}catch{p=this.exportsRepo.findByPartialName(e,t+50)}if(p.length===0){let C=this.exportsRepo.getAllNames(5e3),M=e.trim().split(/\s+/).filter(P=>P.length>0);if(M.length>1){let P=new Map;for(let L of M){let A=Mn(L,C,40,20);for(let $ of A){let W=P.get($.match);W?(W.terms.push(L),W.bestScore=Math.max(W.bestScore,$.score)):P.set($.match,{terms:[L],bestScore:$.score})}}let B=Array.from(P.entries()).sort((L,A)=>A[1].terms.length!==L[1].terms.length?A[1].terms.length-L[1].terms.length:A[1].bestScore-L[1].bestScore).slice(0,10);if(B.length>0){let L=B.map(([A,$])=>{let W=$.terms.join(", ");return` \u2022 \`${A}\` (matches: ${W}, ${Math.round($.bestScore)}%)`}).join(`
782
862
  `);return{content:[{type:"text",text:`No symbols found matching all terms: "${e}"
783
863
 
784
864
  **Partial matches:**
785
- ${$}
865
+ ${L}
786
866
 
787
- \u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let M=bn(e,E,50,5);if(M.length>0){let N=M.map($=>` \u2022 \`${$.match}\` (${Math.round($.score)}% ${$.matchType} match)`).join(`
867
+ \u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let P=Mn(e,C,50,5);if(P.length>0){let B=P.map(L=>` \u2022 \`${L.match}\` (${Math.round(L.score)}% ${L.matchType} match)`).join(`
788
868
  `);return{content:[{type:"text",text:`No symbols found matching: "${e}"
789
869
 
790
870
  **Did you mean?**
791
- ${N}
871
+ ${B}
792
872
 
793
873
  \u{1F4A1} Try shadow_search_symbol with fuzzy, or shadow_search_concept for semantic search.`}]}}}return{content:[{type:"text",text:`No symbols found matching: "${e}"
794
874
 
795
- \u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(E=>{let T=this.filesRepo.findByPath(E.file_path);return s.matchesFilters(E.file_path,i,T?.mtime,T?.classification)}));let u=new yn(this.repoPath),d=new Se(this.repoPath),h=u.getAncestorMissionIds(),m=me(this.repoPath)||void 0,f=this.exportsRepo.getGravityMap(h,m),_=d.getSection("gravity"),g=new Map;if(_?.hotspots)for(let E of _.hotspots)g.set(`${E.filePath}::${E.symbol}`,E.gravity);let b="\u{1F525}",w="\u26A1",x="\u269B\uFE0F",R=p.map((E,T)=>{let I=f[E.id],M=g.get(`${E.file_path}::${E.name}`),N=this.filesRepo.findByPath(E.file_path),$=We.getMultiplier(E.file_path,N?.classification),W=(ge.SCORE_BASE-T)*$;I&&(W+=I.score*ge.SCORE_BASE),M&&(W+=M*ge.SCORE_BASE*ge.GRAVITY_STRUCTURAL_WEIGHT),E.name.toLowerCase()===a&&(W+=ge.EXACT_MATCH_BONUS*$);let L=N?.mtime;if(L!=null){let H=L>1e10?L/1e3:L,F=(Date.now()/1e3-H)/ls.SECONDS_PER_DAY;F<ge.RECENT_FILE_THRESHOLD_DAYS?W+=ge.RECENT_FILE_BOOST:F<ge.OLDER_FILE_THRESHOLD_DAYS&&(W+=ge.OLDER_FILE_BOOST)}let A=[];return I&&A.push(...I.reasons),M&&A.push(`Structural Hotspot (Gravity: ${M.toFixed(1)})`),{...E,activeGravity:I,structuralGravity:M,sortScore:W,reasons:A}}).sort((E,T)=>T.sortScore-E.sortScore).slice(n,n+t),k=p.length,D=n+t<k,U=R.map((E,T)=>{let I=c(E.file_path),M=this.filesRepo.getContent(E.file_path),N="";if(M){let L=M.split(`
796
- `);N=L.slice(Math.max(0,E.start_line-2),Math.min(L.length,E.start_line+3)).join(`
797
- `).trim()}let $=[];E.activeGravity&&(E.activeGravity.reasons.some(L=>L.includes("Working Set"))?$.push(b):E.activeGravity.reasons.some(L=>L.includes("Recent Intent"))&&$.push(w)),E.structuralGravity&&$.push(x);let W=$.length>0?` ${$.join("")}`:"";return{relPath:I,name:E.name,kind:E.kind,signature:E.signature,line:E.start_line,snippet:N,badgeStr:W,gravityReasons:E.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
875
+ \u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(C=>{let M=this.filesRepo.findByPath(C.file_path);return s.matchesFilters(C.file_path,i,M?.mtime,M?.classification)}));let u=new Ln(this.repoPath),d=new Ae(this.repoPath),h=u.getAncestorMissionIds(),m=be(this.repoPath)||void 0,f=this.exportsRepo.getGravityMap(h,m),b=d.getSection("gravity"),g=new Map;if(b?.hotspots)for(let C of b.hotspots)g.set(`${C.filePath}::${C.symbol}`,C.gravity);let y="\u{1F525}",E="\u26A1",k="\u269B\uFE0F",R=p.map((C,M)=>{let D=f[C.id],P=g.get(`${C.file_path}::${C.name}`),B=this.filesRepo.findByPath(C.file_path),L=tt.getMultiplier(C.file_path,B?.classification),A=(ve.SCORE_BASE-M)*L;D&&(A+=D.score*ve.SCORE_BASE),P&&(A+=P*ve.SCORE_BASE*ve.GRAVITY_STRUCTURAL_WEIGHT),C.name.toLowerCase()===a&&(A+=ve.EXACT_MATCH_BONUS*L);let $=B?.mtime;if($!=null){let J=$>1e10?$/1e3:$,O=(Date.now()/1e3-J)/Cs.SECONDS_PER_DAY;O<ve.RECENT_FILE_THRESHOLD_DAYS?A+=ve.RECENT_FILE_BOOST:O<ve.OLDER_FILE_THRESHOLD_DAYS&&(A+=ve.OLDER_FILE_BOOST)}let W=[];return D&&W.push(...D.reasons),P&&W.push(`Structural Hotspot (Gravity: ${P.toFixed(1)})`),{...C,activeGravity:D,structuralGravity:P,sortScore:A,reasons:W}}).sort((C,M)=>M.sortScore-C.sortScore).slice(n,n+t),w=p.length,N=n+t<w,U=R.map((C,M)=>{let D=l(C.file_path),P=this.filesRepo.getContent(C.file_path),B="";if(P){let $=P.split(`
876
+ `);B=$.slice(Math.max(0,C.start_line-2),Math.min($.length,C.start_line+3)).join(`
877
+ `).trim()}let L=[];C.activeGravity&&(C.activeGravity.reasons.some($=>$.includes("Working Set"))?L.push(y):C.activeGravity.reasons.some($=>$.includes("Recent Intent"))&&L.push(E)),C.structuralGravity&&L.push(k);let A=L.length>0?` ${L.join("")}`:"";return{relPath:D,name:C.name,kind:C.kind,signature:C.signature,line:C.start_line,snippet:B,badgeStr:A,gravityReasons:C.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
798
878
 
799
- Showing ${U.length} matching symbol(s)${D?` (use offset=${n+t} for more)`:""}:
879
+ Showing ${U.length} matching symbol(s)${N?` (use offset=${n+t} for more)`:""}:
800
880
 
801
- `+U.map((E,T)=>{let I=`## ${n+T+1}. \`${E.name}\` (${E.kind})${E.badgeStr}
802
- **File**: \`${E.relPath}:${E.line}\`
803
- `;return E.gravityReasons&&(I+=`> *${E.gravityReasons.join(", ")}*
804
- `),E.signature&&(I+=`**Signature**: \`${E.signature}\`
805
- `),E.snippet&&(I+=`
881
+ `+U.map((C,M)=>{let D=`## ${n+M+1}. \`${C.name}\` (${C.kind})${C.badgeStr}
882
+ **File**: \`${C.relPath}:${C.line}\`
883
+ `;return C.gravityReasons.length>0&&(D+=`> *${C.gravityReasons.join(", ")}*
884
+ `),C.signature&&(D+=`**Signature**: \`${C.signature}\`
885
+ `),C.snippet&&(D+=`
806
886
  \`\`\`typescript
807
- ${E.snippet}
887
+ ${C.snippet}
808
888
  \`\`\`
809
- `),I}).join(`
810
- `)}]}}async findConceptMatches(e,t,n,i,r,o=0){let a=me(this.repoPath)||void 0,l=new Ri(this.repoPath).getScorer(),u=new yn(this.repoPath).getAncestorMissionIds(),d=this.filesRepo.getGravityMap(u,a),h=ht.extractKeywords(e),m=h.length>=3,f=this.extractOrderedConceptTerms(e),_=this.buildNgrams(f,2,3),g=this.classifyConceptQuery(e,h),b=m?this.collectConceptSymbolHintPaths(h,Math.max(r*10,100)):new Set,w=Math.min(Math.max((r+o)*g.channelMultiplier,ge.FILTERED_QUERY_LIMIT_MULTIPLIER*20),ke.MAX_LIMIT),x=Math.min(Math.max(w*4,200),4e3),[R,k,D]=await Promise.all([Promise.resolve(t?this.filesRepo.findWithEmbeddings():[]),Promise.resolve(this.filesRepo.findContentFts(e,w)),Promise.resolve(t?this.exportsRepo.findWithEmbeddings(x):[])]),U=[];if(t){for(let v of R)try{let C=JSON.parse(v.embedding),B=Mn(t,C);U.push({row:v,similarity:B,vectorRank:0})}catch{}U.sort((v,C)=>C.similarity-v.similarity);for(let v=0;v<U.length;v++)U[v].vectorRank=v+1}let P=[];if(t){for(let v of D)if(v.embedding)try{let C=JSON.parse(v.embedding),B=Mn(t,C);if(B<=0)continue;P.push({row:v,similarity:B,symbolVectorRank:0})}catch{}P.sort((v,C)=>C.similarity-v.similarity);for(let v=0;v<P.length;v++)P[v].symbolVectorRank=v+1}let E=new Map;for(let v of R)E.set(v.path,v);for(let v of k)E.has(v.path)||E.set(v.path,v);let T=new Map,I=[],M=new Set;for(let v of P.slice(0,x)){let C=v.row.file_path,B=T.get(C);if((!B||v.similarity>B.similarity)&&T.set(C,{similarity:v.similarity,symbolRank:v.symbolVectorRank,symbolName:v.row.name}),M.has(C))continue;let j=E.get(C);j||(j=this.filesRepo.findByPath(C),j&&E.set(C,j)),j&&(I.push({path:C,rank:v.symbolVectorRank,score:v.similarity,row:j,symbolName:v.row.name}),M.add(C))}let N=this.rrfMerge(U.slice(0,w).map(v=>({path:v.row.path,rank:v.vectorRank,score:v.similarity,row:v.row})),k.slice(0,w).map((v,C)=>({path:v.path,rank:C+1,bm25Rank:v.bm25_rank,row:v})),g.rrfK,{vectorWeight:g.vectorWeight,ftsWeight:g.ftsWeight,symbolWeight:g.symbolWeight,symbolResults:I.slice(0,w)});if(N.length===0)return[];let $=new Map;for(let v of U)$.set(v.row.path,v.similarity);let W=Math.min(N.length,Math.max(r*g.lexicalWindowMultiplier,40)),L=new Set(N.slice(0,W).map(v=>v.path)),A=[],H=new Map;for(let v of N){let C=v.row,B=$.get(C.path)||0,j=T.get(C.path),J=j?.similarity||0,z=Math.max(B,J),G=v.ftsRank!==null,we=v.symbolVectorRank!==null||!!j,xe=v.vectorRank!==null||we,he=b.has(C.path),le=L.has(C.path)||G||he||we;if(!le&&v.fusedScore<g.earlyRejectThreshold&&z<.18&&!i)continue;let re=le?this.filesRepo.getContent(C.path):null,He=ge.ENABLE_LEXICAL_SCORING&&re?ht.calculateLexicalScore(re,e):0,Mt=re?ht.calculateKeywordCoverageFromKeywords(re,h):0,_t=h.length>0?Math.round(Mt*h.length):0,ze=this.calculatePhraseCoverage(`${C.path}
811
- ${C.summary||""}
812
- ${re||""}`,_),Sn=1;if(re){let tn=/\b(class|function|const|let|var|enum)\s+\w+/.test(re);if(/export\s+/.test(re)&&!tn){let Dc=re.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");/\b(class|function|const|let|var|enum)\s+\w+/.test(Dc)||(Sn=.1)}}let Lc=he?.08:we?.1:He>0||ze>0||G?.14:m?.22:.18;if(xe&&z<=Lc&&!G)continue;if(h.length>0&&He===0&&!G){if(m){if(!he&&(_t===0&&ze===0&&z<.4||_t<=1&&ze===0&&z<.34||_t===1&&z<.3))continue}else if(_t===0&&z<.24)continue}if(m&&!he&&ze===0&&_t<=1&&z<.3&&!G||i&&!s.matchesFilters(C.path,n,C.mtime,C.classification))continue;let $c=C.mtime>2e9?Math.floor(C.mtime/1e3):C.mtime,Ac=Math.floor(Date.now()/1e3)-ls.SECONDS_PER_YEAR,Bi=We.getMultiplier(C.path,C.classification),Pc=xe?l.calculateScore(z,$c||Ac):0,Ye=(v.fusedScore*60+Pc*.2)*Bi,wn=d[C.path],Mc=C.classification?We.mapClassificationToTier(C.classification):We.classify(C.path,{content:re??void 0}),ve=`vector_rank: ${this.formatRank(v.vectorRank)} | symbol_vector_rank: ${this.formatRank(v.symbolVectorRank)} | fts_rank: ${this.formatRank(v.ftsRank)} | fused_score: ${v.fusedScore.toFixed(6)} | query_profile: ${g.profile} | Similarity: ${(z*100).toFixed(0)}%, Tier: ${Mc}${Bi!==1?` (${Bi}x)`:""}`;if(he&&(ve+=" | SymbolHint"),j&&(ve+=` | SymbolVec: ${j.symbolName}`),He>0&&(Ye+=He*ge.LEXICAL_WEIGHT,ve+=` | Lexical: +${He.toFixed(1)}`),h.length>0)if(Mt>0){let tn=m?Mt*.45:Mt*.35;Ye+=tn,ve+=` | Keywords: ${(Mt*100).toFixed(0)}%`}else ve+=" | Keywords: 0%",m&&!G&&(Ye*=.55,ve+=" (penalty)");if(_.length>0)if(ze>0){let tn=m?ze*.8:ze*.35;Ye+=tn,ve+=` | Phrases: ${(ze*100).toFixed(0)}%`}else m&&!G&&(Ye*=.72,ve+=" | Phrases: 0% (penalty)");wn&&(Ye+=wn.score,ve+=` | \u{1F525} Gravity: +${wn.score.toFixed(1)} (${wn.reasons.join(", ")})`),m&&this.isGenericConceptPath(C.path)&&_t<=1&&ze===0&&!G&&(Ye*=.75,ve+=" | Generic path penalty"),Sn<1&&(Ye*=Sn,ve+=` | \u{1F4C9} Barrel: x${Sn}`);let Nc=re?ht.extractSnippet(re,e):void 0;A.push({path:C.path,summary:C.summary||"",score:z,fusedScore:v.fusedScore,vectorRank:v.vectorRank,ftsRank:v.ftsRank,decayedScore:Ye,rationale:ve,snippet:Nc}),H.set(C.path,{lexicalScore:He,keywordCoverage:Mt,matchedKeywordCount:_t,phraseCoverage:ze,similarity:z,hasFtsSignal:G,hasSymbolHint:he,hasSymbolVectorSignal:we,lexicalConfirm:0,identifierOverlap:0,isGenericPath:this.isGenericConceptPath(C.path)})}if(A.length>0&&h.length>0){let v=this.exportsRepo.findByFiles(A.map(B=>B.path)),C=new Map;for(let B of v){let j=C.get(B.file_path)??[];j.push(B.name),C.set(B.file_path,j)}for(let B of A){let j=this.calculateIdentifierOverlap(h,C.get(B.path)??[]),J=H.get(B.path);if(J&&(J.identifierOverlap=j),j>0){let z=m?j*.8:j*.25;B.decayedScore=(B.decayedScore||0)+z,B.rationale+=` | Symbols: ${(j*100).toFixed(0)}%`}else m&&this.isGenericConceptPath(B.path)&&(B.decayedScore=(B.decayedScore||0)*.82,B.rationale+=" | Symbols: 0% (generic penalty)")}}let F=new Map;for(let v of A){let C=v.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();C&&C.length>3&&(F.has(C)||F.set(C,[]),F.get(C).push(v))}for(let[v,C]of F.entries())if(new Set(C.map(j=>j.path.split(".").pop())).size>1)for(let j of C)j.decayedScore=(j.decayedScore||0)+.15,j.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${v}')`;if(m&&A.length>1){let v=Math.min(Math.max(r*4,ge.FILTERED_QUERY_LIMIT_MULTIPLIER*20),A.length),C=[...A].sort((j,J)=>(J.decayedScore||0)-(j.decayedScore||0)).slice(0,v),B=this.computeBm25LikeConfirmation(C.map(j=>j.path),h);for(let j of C){let J=B.get(j.path)||0,z=H.get(j.path);if(z&&(z.lexicalConfirm=J),J>0){let G=Math.min(.95,J*.18);j.decayedScore=(j.decayedScore||0)+G,j.rationale+=` | LexConfirm: +${G.toFixed(2)}`}else z&&z.matchedKeywordCount<=1&&z.phraseCoverage===0&&z.lexicalScore===0&&(j.decayedScore=(j.decayedScore||0)*.85,j.rationale+=" | LexConfirm: 0 (penalty)")}}for(let v of A){let C=H.get(v.path);C&&(v.score=this.calculateConceptEvidenceScore({profile:g.profile,queryKeywordCount:h.length,...C}),v.rationale+=` | Evidence: ${(v.score*100).toFixed(0)}%`)}return A.sort((v,C)=>(C.decayedScore||0)-(v.decayedScore||0)),A.slice(o,o+Math.min(r,ke.MAX_LIMIT))}async findIntentLogMatches(e,t){return(await this.intentLogsRepo.findSemanticMatches(e,t)).map(i=>({id:i.id,missionId:i.mission_id,type:i.type,content:i.content,symbolName:i.symbol_name,filePath:i.file_path,score:i.similarity,decayedScore:i.similarity,rationale:`Similarity: ${(i.similarity*100).toFixed(0)}%`,createdAt:i.created_at}))}buildFtsQuery(e,t){let n=e.trim();if(!n.includes(" "))return`"${n}" OR ${n}*`;let i=n.split(/\s+/).filter(r=>r.length>0);switch(t){case"exact":return`"${n}"`;case"all":return i.map(r=>`${r}*`).join(" ");default:return i.map(r=>`${r}*`).join(" OR ")}}extractPathKeywords(e){let t=e.trim();if(!t)return[];let n=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_\/.-]+/).map(r=>r.trim()).filter(r=>r.length>=2),i=new Set;i.add(t.toLowerCase());for(let r of n)i.add(r);return Array.from(i)}isLikelySymbolQuery(e){let t=e.trim();return!t||/[\/\\]/.test(t)?!1:/^[a-z]+(?:[A-Z][a-z0-9]+)+$/.test(t)||!t.includes(" ")&&/[A-Z]/.test(t)}countPathKeywordHits(e,t){let n=e.toLowerCase(),i=t.filter(o=>o.length>=3),r=0;for(let o of i)n.includes(o.toLowerCase())&&(r+=1);return r}scorePathResult(e,t,n,i){let o=this.countPathKeywordHits(e,t)*10;n==="symbol"&&(o+=25);let a=e.toLowerCase(),c=a.includes("/.env")||a.endsWith(".env")||a.endsWith(".yml")||a.endsWith(".yaml")||a.endsWith(".json")||a.endsWith(".md");return i&&c&&(o-=20),i&&a.includes("/tests/")&&(o-=15),o}findSymbolBackedPaths(e,t,n){let i=e.trim().toLowerCase();if(!i)return[];if(/[\/\\]/.test(i))return[];let r=Array.from(new Set([i,...t])).filter(c=>c.length>=3).slice(0,6);if(r.length===0)return[];let o=r.flatMap(c=>{let l=c===i?Math.min(n,60):Math.min(n,30);return this.exportsRepo.findByPartialName(c,l)}),a=new Map;for(let c of o){let l=c.name.toLowerCase(),p=0;l===i&&(p+=6),l.startsWith(i)&&(p+=4),l.includes(i)&&(p+=3);for(let d of t)d.length>=3&&l.includes(d)&&(p+=1);if(p===0)continue;let u=a.get(c.file_path)||0;p>u&&a.set(c.file_path,p)}return Array.from(a.entries()).sort((c,l)=>l[1]-c[1]).slice(0,Math.min(n,ke.MAX_LIMIT)).map(([c])=>c)}rrfMerge(e,t,n,i){let r=new Map,o=i?.vectorWeight??1.2,a=i?.ftsWeight??.8,c=i?.symbolWeight??1.1,l=i?.symbolResults??[];for(let p of e){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.vectorRank=p.rank,u.fusedScore+=o/(n+p.rank),r.set(p.path,u)}for(let p of t){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.ftsRank=p.rank,u.fusedScore+=a/(n+p.rank),r.set(p.path,u)}for(let p of l){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.symbolVectorRank=p.rank,u.symbolName=p.symbolName,u.fusedScore+=c/(n+p.rank),r.set(p.path,u)}return Array.from(r.values()).sort((p,u)=>u.fusedScore-p.fusedScore)}formatRank(e){return e==null?"none":String(e)}getConceptConfidenceFloor(e){switch(e){case"identifier-heavy":return .33;case"lexical-heavy":return .38;case"semantic-exploratory":return .3;default:return .35}}getIntentConfidenceFloor(e){return Math.max(.28,this.getConceptConfidenceFloor(e)-.05)}calculateConceptEvidenceScore(e){let t=Math.min(1,e.lexicalConfirm/Math.max(1,e.queryKeywordCount*1.5)),n=e.profile==="semantic-exploratory"?.72:.58,i=e.profile==="lexical-heavy"?.16:.12,r=e.profile==="identifier-heavy"?.12:.08,o=e.similarity*n+Math.min(1,e.lexicalScore)*.08+e.keywordCoverage*.1+e.phraseCoverage*i+e.identifierOverlap*r+t*.08;return e.hasFtsSignal&&(o+=.04),e.hasSymbolHint?o+=.03:e.hasSymbolVectorSignal&&(o+=.02),e.matchedKeywordCount===0&&e.phraseCoverage===0&&e.lexicalScore===0?o*=e.hasFtsSignal||e.hasSymbolVectorSignal?.72:.6:e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.88),e.isGenericPath&&e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.85),e.queryKeywordCount===0&&(o*=.75),Math.max(0,Math.min(.97,o))}estimateTokenCount(e){return e?Math.ceil(e.length/4):0}classifyConceptQuery(e,t){let n=e.trim(),i=t.length,r=/\b[a-z]+[A-Z][A-Za-z0-9]*\b/.test(n),o=/\b[a-z0-9]+_[a-z0-9_]+\b/i.test(n),a=/[/.:#()]/.test(n),c=i<=1&&!n.includes(" "),l=n.includes('"')||i>=5&&n.split(/\s+/).length>=6;return r||o||a&&i>=2?{profile:"identifier-heavy",rrfK:45,vectorWeight:1,ftsWeight:.75,symbolWeight:1.45,channelMultiplier:5,lexicalWindowMultiplier:5,earlyRejectThreshold:.012}:l?{profile:"lexical-heavy",rrfK:55,vectorWeight:.95,ftsWeight:1.3,symbolWeight:1,channelMultiplier:7,lexicalWindowMultiplier:8,earlyRejectThreshold:.008}:c||i<=2?{profile:"semantic-exploratory",rrfK:70,vectorWeight:1.35,ftsWeight:.6,symbolWeight:.9,channelMultiplier:4,lexicalWindowMultiplier:4,earlyRejectThreshold:.018}:{profile:"balanced",rrfK:60,vectorWeight:1.15,ftsWeight:.9,symbolWeight:1.2,channelMultiplier:6,lexicalWindowMultiplier:6,earlyRejectThreshold:.01}}extractOrderedConceptTerms(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>=3):[]}buildNgrams(e,t,n){if(e.length<t)return[];let i=[];for(let r=t;r<=n&&!(e.length<r);r++)for(let o=0;o<=e.length-r;o++)i.push(e.slice(o,o+r).join(" "));return Array.from(new Set(i))}calculatePhraseCoverage(e,t){if(!e||t.length===0)return 0;let n=e.toLowerCase(),i=0;for(let r of t)n.includes(r)&&(i+=1);return i/t.length}calculateIdentifierOverlap(e,t){if(e.length===0||t.length===0)return 0;let n=new Set(e.map(o=>o.toLowerCase())),i=new Set;for(let o of t){let a=o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(c=>c.trim()).filter(c=>c.length>=3);for(let c of a)i.add(c)}let r=0;for(let o of n)i.has(o)&&(r+=1);return r/n.size}isGenericConceptPath(e){let t=e.toLowerCase();return/(?:^|\/)(index|utils?|helpers?|common|shared|types?|constants?|models?)(?:\/|\.|$)/.test(t)}computeBm25LikeConfirmation(e,t){let n=Array.from(new Set(t.map(u=>u.toLowerCase()).filter(u=>u.length>=3)));if(e.length===0||n.length===0)return new Map;let i=new Set(n),r=[],o=new Map;for(let u of e){let h=(this.filesRepo.getContent(u)??"").toLowerCase().split(/[^a-z0-9_]+/).map(f=>f.trim()).filter(Boolean),m=new Map;for(let f of h)i.has(f)&&m.set(f,(m.get(f)||0)+1);for(let f of n)(m.get(f)||0)>0&&o.set(f,(o.get(f)||0)+1);r.push({path:u,frequencies:m,length:Math.max(h.length,1)})}let a=r.reduce((u,d)=>u+d.length,0)/Math.max(r.length,1),c=1.2,l=.75,p=new Map;for(let u of r){let d=0;for(let h of n){let m=u.frequencies.get(h)||0;if(m===0)continue;let f=o.get(h)||0,_=Math.log(1+(r.length-f+.5)/(f+.5)),g=m*(c+1)/(m+c*(1-l+l*(u.length/Math.max(a,1))));d+=_*g}p.set(u.path,d)}return p}collectConceptSymbolHintPaths(e,t){let n=Array.from(new Set(e.filter(r=>r.length>=4&&!this.isLowSignalConceptKeyword(r)))).slice(0,6);if(n.length===0)return new Set;let i=new Map;for(let r of n){let o=this.exportsRepo.findByPartialName(r,Math.min(t,80));for(let a of o){let c=a.name.toLowerCase(),l=0;c===r&&(l+=3),c.startsWith(r)&&(l+=2),c.includes(r)&&(l+=1),l!==0&&i.set(a.file_path,(i.get(a.file_path)||0)+l)}}return new Set(Array.from(i.entries()).sort((r,o)=>o[1]-r[1]).slice(0,Math.min(t,ke.MAX_LIMIT)).map(([r])=>r))}isLowSignalConceptKeyword(e){return new Set(["type","types","data","update","create","list","item","value","model","helper"]).has(e.toLowerCase())}};q();V();function ki(s){let{fileType:e,layer:t}=s,n={fileType:gt.normalizeFileType(e),layer:t},i=!!(n.fileType?.length||n.layer!=null);return{filters:n,hasFilters:i}}async function $a(s){let e=Ei(s.query??""),t={...s,query:e},n=qn();try{let{repoPath:i}=Ve(t),{query:r,limit:o=ke.DEFAULT_LIMIT,offset:a=0,compact:c=!1,tokenBudget:l}=t;await X(i);let{filters:p,hasFilters:u}=ki(t),h=await new gt(i).searchByConcept(r,o,a,p,u,c,l);try{let m=yi(i);if(m.status==="running"){let[f,_]=m.progress.split("/").map(Number),g=_>0?Math.round(f/_*100):0,b=`\u26A0\uFE0F Symbol embeddings still warming (${m.progress}, ${g}%) \u2014 symbol-level results may be incomplete. File-level results are fully available.
889
+ `),D}).join(`
890
+ `)}]}}async findConceptMatches(e,t,n,i,r,o=0){let a=be(this.repoPath)||void 0,c=new Ui(this.repoPath).getScorer(),u=new Ln(this.repoPath).getAncestorMissionIds(),d=this.filesRepo.getGravityMap(u,a),h=It.extractKeywords(e),m=h.length>=3,f=this.extractOrderedConceptTerms(e),b=this.buildNgrams(f,2,3),g=this.classifyConceptQuery(e,h),y=m?this.collectConceptSymbolHintPaths(h,Math.max(r*10,100)):new Set,E=Math.min(Math.max((r+o)*g.channelMultiplier,ve.FILTERED_QUERY_LIMIT_MULTIPLIER*20),We.MAX_LIMIT),k=Math.min(Math.max(E*4,200),4e3),[R,w,N]=await Promise.all([Promise.resolve(t?this.filesRepo.findWithEmbeddings():[]),Promise.resolve(this.filesRepo.findContentFts(e,E)),Promise.resolve(t?this.exportsRepo.findWithEmbeddings(k):[])]),U=[];if(t){for(let S of R)try{let v=JSON.parse(S.embedding),T=Yn(t,v);U.push({row:S,similarity:T,vectorRank:0})}catch{}U.sort((S,v)=>v.similarity-S.similarity);for(let S=0;S<U.length;S++)U[S].vectorRank=S+1}let H=[];if(t){for(let S of N)if(S.embedding)try{let v=JSON.parse(S.embedding),T=Yn(t,v);if(T<=0)continue;H.push({row:S,similarity:T,symbolVectorRank:0})}catch{}H.sort((S,v)=>v.similarity-S.similarity);for(let S=0;S<H.length;S++)H[S].symbolVectorRank=S+1}let C=new Map;for(let S of R)C.set(S.path,S);for(let S of w)C.has(S.path)||C.set(S.path,S);let M=new Map,D=[],P=new Set;for(let S of H.slice(0,k)){let v=S.row.file_path,T=M.get(v);if((!T||S.similarity>T.similarity)&&M.set(v,{similarity:S.similarity,symbolRank:S.symbolVectorRank,symbolName:S.row.name}),P.has(v))continue;let I=C.get(v);I||(I=this.filesRepo.findByPath(v),I&&C.set(v,I)),I&&(D.push({path:v,rank:S.symbolVectorRank,score:S.similarity,row:I,symbolName:S.row.name}),P.add(v))}let B=this.rrfMerge(U.slice(0,E).map(S=>({path:S.row.path,rank:S.vectorRank,score:S.similarity,row:S.row})),w.slice(0,E).map((S,v)=>({path:S.path,rank:v+1,bm25Rank:S.bm25_rank,row:S})),g.rrfK,{vectorWeight:g.vectorWeight,ftsWeight:g.ftsWeight,symbolWeight:g.symbolWeight,symbolResults:D.slice(0,E)});if(B.length===0)return[];let L=new Map;for(let S of U)L.set(S.row.path,S.similarity);let A=Math.min(B.length,Math.max(r*g.lexicalWindowMultiplier,40)),$=new Set(B.slice(0,A).map(S=>S.path)),W=[],J=new Map;for(let S of B){let v=S.row,T=L.get(v.path)||0,I=M.get(v.path),z=I?.similarity||0,j=Math.max(T,z),Q=S.ftsRank!==null,fe=S.symbolVectorRank!==null||!!I,Ce=S.vectorRank!==null||fe,Ie=y.has(v.path),gt=$.has(v.path)||Q||Ie||fe;if(!gt&&S.fusedScore<g.earlyRejectThreshold&&j<.18&&!i)continue;let he=gt?this.filesRepo.getContent(v.path):null,Ne=ve.ENABLE_LEXICAL_SCORING&&he?It.calculateLexicalScore(he,e):0,Pe=he?It.calculateKeywordCoverageFromKeywords(he,h):0,Ee=h.length>0?Math.round(Pe*h.length):0,K=this.calculatePhraseCoverage(`${v.path}
891
+ ${v.summary||""}
892
+ ${he||""}`,b),ae=1;if(he){let ce=/\b(class|function|const|let|var|enum)\s+\w+/.test(he);if(/export\s+/.test(he)&&!ce){let ct=he.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");/\b(class|function|const|let|var|enum)\s+\w+/.test(ct)||(ae=.1)}}let at=Ie?.08:fe?.1:Ne>0||K>0||Q?.14:m?.22:.18;if(Ce&&j<=at&&!Q)continue;if(h.length>0&&Ne===0&&!Q){if(m){if(!Ie&&(Ee===0&&K===0&&j<.4||Ee<=1&&K===0&&j<.34||Ee===1&&j<.3))continue}else if(Ee===0&&j<.24)continue}if(m&&!Ie&&K===0&&Ee<=1&&j<.3&&!Q||i&&!s.matchesFilters(v.path,n,v.mtime,v.classification))continue;let yt=v.mtime>2e9?Math.floor(v.mtime/1e3):v.mtime,Ue=Math.floor(Date.now()/1e3)-Cs.SECONDS_PER_YEAR,je=tt.getMultiplier(v.path,v.classification),Nt=Ce?c.calculateScore(j,yt||Ue):0,xe=(S.fusedScore*60+Nt*.2)*je,V=d[v.path],q=v.classification?tt.mapClassificationToTier(v.classification):tt.classify(v.path,{content:he??void 0}),X=`vector_rank: ${this.formatRank(S.vectorRank)} | symbol_vector_rank: ${this.formatRank(S.symbolVectorRank)} | fts_rank: ${this.formatRank(S.ftsRank)} | fused_score: ${S.fusedScore.toFixed(6)} | query_profile: ${g.profile} | Similarity: ${(j*100).toFixed(0)}%, Tier: ${q}${je!==1?` (${je}x)`:""}`;if(Ie&&(X+=" | SymbolHint"),I&&(X+=` | SymbolVec: ${I.symbolName}`),Ne>0&&(xe+=Ne*ve.LEXICAL_WEIGHT,X+=` | Lexical: +${Ne.toFixed(1)}`),h.length>0)if(Pe>0){let ce=m?Pe*.45:Pe*.35;xe+=ce,X+=` | Keywords: ${(Pe*100).toFixed(0)}%`}else X+=" | Keywords: 0%",m&&!Q&&(xe*=.55,X+=" (penalty)");if(b.length>0)if(K>0){let ce=m?K*.8:K*.35;xe+=ce,X+=` | Phrases: ${(K*100).toFixed(0)}%`}else m&&!Q&&(xe*=.72,X+=" | Phrases: 0% (penalty)");V&&(xe+=V.score,X+=` | \u{1F525} Gravity: +${V.score.toFixed(1)} (${V.reasons.join(", ")})`),m&&this.isGenericConceptPath(v.path)&&Ee<=1&&K===0&&!Q&&(xe*=.75,X+=" | Generic path penalty"),ae<1&&(xe*=ae,X+=` | \u{1F4C9} Barrel: x${ae}`);let we=he?It.extractSnippet(he,e):void 0;W.push({path:v.path,summary:v.summary||"",score:j,fusedScore:S.fusedScore,vectorRank:S.vectorRank,ftsRank:S.ftsRank,decayedScore:xe,rationale:X,snippet:we}),J.set(v.path,{lexicalScore:Ne,keywordCoverage:Pe,matchedKeywordCount:Ee,phraseCoverage:K,similarity:j,hasFtsSignal:Q,hasSymbolHint:Ie,hasSymbolVectorSignal:fe,lexicalConfirm:0,identifierOverlap:0,isGenericPath:this.isGenericConceptPath(v.path)})}if(W.length>0&&h.length>0){let S=this.exportsRepo.findByFiles(W.map(T=>T.path)),v=new Map;for(let T of S){let I=v.get(T.file_path)??[];I.push(T.name),v.set(T.file_path,I)}for(let T of W){let I=this.calculateIdentifierOverlap(h,v.get(T.path)??[]),z=J.get(T.path);if(z&&(z.identifierOverlap=I),I>0){let j=m?I*.8:I*.25;T.decayedScore=(T.decayedScore||0)+j,T.rationale+=` | Symbols: ${(I*100).toFixed(0)}%`}else m&&this.isGenericConceptPath(T.path)&&(T.decayedScore=(T.decayedScore||0)*.82,T.rationale+=" | Symbols: 0% (generic penalty)")}}let O=new Map;for(let S of W){let v=S.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();v&&v.length>3&&(O.has(v)||O.set(v,[]),O.get(v).push(S))}for(let[S,v]of O.entries())if(new Set(v.map(I=>I.path.split(".").pop())).size>1)for(let I of v)I.decayedScore=(I.decayedScore||0)+.15,I.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${S}')`;if(m&&W.length>1){let S=Math.min(Math.max(r*4,ve.FILTERED_QUERY_LIMIT_MULTIPLIER*20),W.length),v=[...W].sort((I,z)=>(z.decayedScore||0)-(I.decayedScore||0)).slice(0,S),T=this.computeBm25LikeConfirmation(v.map(I=>I.path),h);for(let I of v){let z=T.get(I.path)||0,j=J.get(I.path);if(j&&(j.lexicalConfirm=z),z>0){let Q=Math.min(.95,z*.18);I.decayedScore=(I.decayedScore||0)+Q,I.rationale+=` | LexConfirm: +${Q.toFixed(2)}`}else j&&j.matchedKeywordCount<=1&&j.phraseCoverage===0&&j.lexicalScore===0&&(I.decayedScore=(I.decayedScore||0)*.85,I.rationale+=" | LexConfirm: 0 (penalty)")}}for(let S of W){let v=J.get(S.path);v&&(S.score=this.calculateConceptEvidenceScore({profile:g.profile,queryKeywordCount:h.length,...v}),S.rationale+=` | Evidence: ${(S.score*100).toFixed(0)}%`)}return W.sort((S,v)=>(v.decayedScore||0)-(S.decayedScore||0)),W.slice(o,o+Math.min(r,We.MAX_LIMIT))}async findIntentLogMatches(e,t){return(await this.intentLogsRepo.findSemanticMatches(e,t)).map(i=>({id:i.id,missionId:i.mission_id,type:i.type,content:i.content,symbolName:i.symbol_name,filePath:i.file_path,score:i.similarity,decayedScore:i.similarity,rationale:`Similarity: ${(i.similarity*100).toFixed(0)}%`,createdAt:i.created_at}))}buildFtsQuery(e,t){let n=e.trim();if(!n.includes(" "))return`"${n}" OR ${n}*`;let i=n.split(/\s+/).filter(r=>r.length>0);switch(t){case"exact":return`"${n}"`;case"all":return i.map(r=>`${r}*`).join(" ");default:return i.map(r=>`${r}*`).join(" OR ")}}extractPathKeywords(e){let t=e.trim();if(!t)return[];let n=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_\/.-]+/).map(r=>r.trim()).filter(r=>r.length>=2),i=new Set;i.add(t.toLowerCase());for(let r of n)i.add(r);return Array.from(i)}isLikelySymbolQuery(e){let t=e.trim();return!t||/[\/\\]/.test(t)?!1:/^[a-z]+(?:[A-Z][a-z0-9]+)+$/.test(t)||!t.includes(" ")&&/[A-Z]/.test(t)}countPathKeywordHits(e,t){let n=e.toLowerCase(),i=t.filter(o=>o.length>=3),r=0;for(let o of i)n.includes(o.toLowerCase())&&(r+=1);return r}scorePathResult(e,t,n,i){let o=this.countPathKeywordHits(e,t)*10;n==="symbol"&&(o+=25);let a=e.toLowerCase(),l=a.includes("/.env")||a.endsWith(".env")||a.endsWith(".yml")||a.endsWith(".yaml")||a.endsWith(".json")||a.endsWith(".md");return i&&l&&(o-=20),i&&a.includes("/tests/")&&(o-=15),o}findSymbolBackedPaths(e,t,n){let i=e.trim().toLowerCase();if(!i)return[];if(/[\/\\]/.test(i))return[];let r=Array.from(new Set([i,...t])).filter(l=>l.length>=3).slice(0,6);if(r.length===0)return[];let o=r.flatMap(l=>{let c=l===i?Math.min(n,60):Math.min(n,30);return this.exportsRepo.findByPartialName(l,c)}),a=new Map;for(let l of o){let c=l.name.toLowerCase(),p=0;c===i&&(p+=6),c.startsWith(i)&&(p+=4),c.includes(i)&&(p+=3);for(let d of t)d.length>=3&&c.includes(d)&&(p+=1);if(p===0)continue;let u=a.get(l.file_path)||0;p>u&&a.set(l.file_path,p)}return Array.from(a.entries()).sort((l,c)=>c[1]-l[1]).slice(0,Math.min(n,We.MAX_LIMIT)).map(([l])=>l)}rrfMerge(e,t,n,i){let r=new Map,o=i?.vectorWeight??1.2,a=i?.ftsWeight??.8,l=i?.symbolWeight??1.1,c=i?.symbolResults??[];for(let p of e){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.vectorRank=p.rank,u.fusedScore+=o/(n+p.rank),r.set(p.path,u)}for(let p of t){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.ftsRank=p.rank,u.fusedScore+=a/(n+p.rank),r.set(p.path,u)}for(let p of c){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.symbolVectorRank=p.rank,u.symbolName=p.symbolName,u.fusedScore+=l/(n+p.rank),r.set(p.path,u)}return Array.from(r.values()).sort((p,u)=>u.fusedScore-p.fusedScore)}formatRank(e){return e==null?"none":String(e)}getConceptConfidenceFloor(e){switch(e){case"identifier-heavy":return .33;case"lexical-heavy":return .38;case"semantic-exploratory":return .3;default:return .35}}getIntentConfidenceFloor(e){return Math.max(.28,this.getConceptConfidenceFloor(e)-.05)}calculateConceptEvidenceScore(e){let t=Math.min(1,e.lexicalConfirm/Math.max(1,e.queryKeywordCount*1.5)),n=e.profile==="semantic-exploratory"?.72:.58,i=e.profile==="lexical-heavy"?.16:.12,r=e.profile==="identifier-heavy"?.12:.08,o=e.similarity*n+Math.min(1,e.lexicalScore)*.08+e.keywordCoverage*.1+e.phraseCoverage*i+e.identifierOverlap*r+t*.08;return e.hasFtsSignal&&(o+=.04),e.hasSymbolHint?o+=.03:e.hasSymbolVectorSignal&&(o+=.02),e.matchedKeywordCount===0&&e.phraseCoverage===0&&e.lexicalScore===0?o*=e.hasFtsSignal||e.hasSymbolVectorSignal?.72:.6:e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.88),e.isGenericPath&&e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.85),e.queryKeywordCount===0&&(o*=.75),Math.max(0,Math.min(.97,o))}estimateTokenCount(e){return e?Math.ceil(e.length/4):0}classifyConceptQuery(e,t){let n=e.trim(),i=t.length,r=/\b[a-z]+[A-Z][A-Za-z0-9]*\b/.test(n),o=/\b[a-z0-9]+_[a-z0-9_]+\b/i.test(n),a=/[/.:#()]/.test(n),l=i<=1&&!n.includes(" "),c=n.includes('"')||i>=5&&n.split(/\s+/).length>=6;return r||o||a&&i>=2?{profile:"identifier-heavy",rrfK:45,vectorWeight:1,ftsWeight:.75,symbolWeight:1.45,channelMultiplier:5,lexicalWindowMultiplier:5,earlyRejectThreshold:.012}:c?{profile:"lexical-heavy",rrfK:55,vectorWeight:.95,ftsWeight:1.3,symbolWeight:1,channelMultiplier:7,lexicalWindowMultiplier:8,earlyRejectThreshold:.008}:l||i<=2?{profile:"semantic-exploratory",rrfK:70,vectorWeight:1.35,ftsWeight:.6,symbolWeight:.9,channelMultiplier:4,lexicalWindowMultiplier:4,earlyRejectThreshold:.018}:{profile:"balanced",rrfK:60,vectorWeight:1.15,ftsWeight:.9,symbolWeight:1.2,channelMultiplier:6,lexicalWindowMultiplier:6,earlyRejectThreshold:.01}}extractOrderedConceptTerms(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>=3):[]}buildNgrams(e,t,n){if(e.length<t)return[];let i=[];for(let r=t;r<=n&&!(e.length<r);r++)for(let o=0;o<=e.length-r;o++)i.push(e.slice(o,o+r).join(" "));return Array.from(new Set(i))}calculatePhraseCoverage(e,t){if(!e||t.length===0)return 0;let n=e.toLowerCase(),i=0;for(let r of t)n.includes(r)&&(i+=1);return i/t.length}calculateIdentifierOverlap(e,t){if(e.length===0||t.length===0)return 0;let n=new Set(e.map(o=>o.toLowerCase())),i=new Set;for(let o of t){let a=o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(l=>l.trim()).filter(l=>l.length>=3);for(let l of a)i.add(l)}let r=0;for(let o of n)i.has(o)&&(r+=1);return r/n.size}isGenericConceptPath(e){let t=e.toLowerCase();return/(?:^|\/)(index|utils?|helpers?|common|shared|types?|constants?|models?)(?:\/|\.|$)/.test(t)}computeBm25LikeConfirmation(e,t){let n=Array.from(new Set(t.map(u=>u.toLowerCase()).filter(u=>u.length>=3)));if(e.length===0||n.length===0)return new Map;let i=new Set(n),r=[],o=new Map;for(let u of e){let h=(this.filesRepo.getContent(u)??"").toLowerCase().split(/[^a-z0-9_]+/).map(f=>f.trim()).filter(Boolean),m=new Map;for(let f of h)i.has(f)&&m.set(f,(m.get(f)||0)+1);for(let f of n)(m.get(f)||0)>0&&o.set(f,(o.get(f)||0)+1);r.push({path:u,frequencies:m,length:Math.max(h.length,1)})}let a=r.reduce((u,d)=>u+d.length,0)/Math.max(r.length,1),l=1.2,c=.75,p=new Map;for(let u of r){let d=0;for(let h of n){let m=u.frequencies.get(h)||0;if(m===0)continue;let f=o.get(h)||0,b=Math.log(1+(r.length-f+.5)/(f+.5)),g=m*(l+1)/(m+l*(1-c+c*(u.length/Math.max(a,1))));d+=b*g}p.set(u.path,d)}return p}collectConceptSymbolHintPaths(e,t){let n=Array.from(new Set(e.filter(r=>r.length>=4&&!this.isLowSignalConceptKeyword(r)))).slice(0,6);if(n.length===0)return new Set;let i=new Map;for(let r of n){let o=this.exportsRepo.findByPartialName(r,Math.min(t,80));for(let a of o){let l=a.name.toLowerCase(),c=0;l===r&&(c+=3),l.startsWith(r)&&(c+=2),l.includes(r)&&(c+=1),c!==0&&i.set(a.file_path,(i.get(a.file_path)||0)+c)}}return new Set(Array.from(i.entries()).sort((r,o)=>o[1]-r[1]).slice(0,Math.min(t,We.MAX_LIMIT)).map(([r])=>r))}isLowSignalConceptKeyword(e){return new Set(["type","types","data","update","create","list","item","value","model","helper"]).has(e.toLowerCase())}};G();Y();function ji(s){let{fileType:e,layer:t}=s,n={fileType:Mt.normalizeFileType(e),layer:t},i=!!(n.fileType?.length||n.layer!=null);return{filters:n,hasFilters:i}}async function ac(s){let e=Pi(s.query??""),t={...s,query:e},n=ci();try{let{repoPath:i}=He(t),{query:r,limit:o=We.DEFAULT_LIMIT,offset:a=0,compact:l=!1,tokenBudget:c}=t;await se(i);let{filters:p,hasFilters:u}=ji(t),h=await new Mt(i).searchByConcept(r,o,a,p,u,l,c);try{let m=$i(i);if(m.status==="running"){let[f,b]=m.progress.split("/").map(Number),g=b>0?Math.round(f/b*100):0,y=`\u26A0\uFE0F Symbol embeddings still warming (${m.progress}, ${g}%) \u2014 symbol-level results may be incomplete. File-level results are fully available.
813
893
 
814
- `;h.content?.[0]?.type==="text"&&(h.content[0].text=b+h.content[0].text)}}catch{}return $u(i,r,"concept"),n(),h}catch(i){return S.error({error:i,args:s},"Concept Search failed"),n(),await Ft(),{content:[{type:"text",text:`Concept Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function $u(s,e,t){try{let n=O.getInstance(s),i=me(s);n.searchHistory.record(e,t,i)}catch(n){let i=me(s);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"),Ft()}}q();V();async function Ds(s){let e=Ei(s.query??""),t={...s,query:e},n=qn();try{let{repoPath:i}=Ve(t),{query:r,limit:o=ke.DEFAULT_LIMIT,offset:a=0,matchMode:c="any"}=t;await X(i);let{filters:l,hasFilters:p}=ki(t),d=await new gt(i).searchBySymbol(r,o,a,l,p,c);return Au(i,r,"symbol"),n(),d}catch(i){return S.error({error:i,args:s},"Symbol Search failed"),n(),await Ft(),{content:[{type:"text",text:`Symbol Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Au(s,e,t){try{let n=O.getInstance(s),i=me(s);n.searchHistory.record(e,t,i)}catch(n){let i=me(s);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"),Ft()}}V();q();import Yt from"path";function Aa(s,e){let t=s.findContentByToken(e,100);return{count:t.length,files:t}}async function Pa(s){let{repoPath:e,query:t,key:n="",kind:i,limit:r=50,showUsage:o=!1}=s,a=n||t;if(!a&&!i)return{content:[{type:"text",text:'Error: Either "key" or "kind" parameter is required.'}]};await X(e);let c=O.getInstance(e),{configs:l,files:p}=c;if(a){S.info({repoPath:e,key:a},"Searching for config key in DB...");let m=l.findByKey(a,r);if(m.length===0)return{content:[{type:"text",text:`No configuration found for key: ${a}`}]};if(o){let g=m.map(R=>{let k=Aa(p,R.key),D=k.count===0?"\u26A0\uFE0F ORPHANED":`\u2713 ${k.count} usage(s)`;return{file:Yt.relative(e,R.file_path),key:R.key,value:R.value,kind:R.kind,usageCount:k.count,usageFiles:k.files.slice(0,5).map(U=>Yt.relative(e,U)),status:D}});g.sort((R,k)=>R.usageCount===0&&k.usageCount>0?-1:k.usageCount===0&&R.usageCount>0?1:R.usageCount-k.usageCount);let b=g.filter(R=>R.usageCount===0).length;return{content:[{type:"text",text:(b>0?`# Configuration Search: "${a}" (with Usage Analysis)
894
+ `;h.content?.[0]?.type==="text"&&(h.content[0].text=y+h.content[0].text)}}catch{}return dd(i,r,"concept"),n(),h}catch(i){return x.error({error:i,args:s},"Concept Search failed"),n(),await Xt(),{content:[{type:"text",text:`Concept Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function dd(s,e,t){try{let n=F.getInstance(s),i=be(s);n.searchHistory.record(e,t,i)}catch(n){let i=be(s);x.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),Xt()}}G();Y();async function tr(s){let e=Pi(s.query??""),t={...s,query:e},n=ci();try{let{repoPath:i}=He(t),{query:r,limit:o=We.DEFAULT_LIMIT,offset:a=0,matchMode:l="any"}=t;await se(i);let{filters:c,hasFilters:p}=ji(t),d=await new Mt(i).searchBySymbol(r,o,a,c,p,l);return md(i,r,"symbol"),n(),d}catch(i){return x.error({error:i,args:s},"Symbol Search failed"),n(),await Xt(),{content:[{type:"text",text:`Symbol Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function md(s,e,t){try{let n=F.getInstance(s),i=be(s);n.searchHistory.record(e,t,i)}catch(n){let i=be(s);x.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),Xt()}}Y();G();import dn from"path";function cc(s,e){let t=s.findContentByToken(e,100);return{count:t.length,files:t}}function lc(s){let e=s.file_path.toLowerCase().replace(/\\/g,"/");return e.includes("/storage/runtime/")||e.includes("/compiled_templates/")||e.includes("/compiled_classes/")||e.includes("/.cache/")||e.includes("docker-compose")||e.includes("/dockerfile")||e.includes("/gitlab/")||e.includes("/.github/workflows/")||e.includes("/k8s/")||e.includes("/helm/")||e.includes("/charts/")||e.includes("/terraform/")||e.endsWith(".yml")||e.endsWith(".yaml")?"external-wiring":"orphaned"}async function pc(s){let{repoPath:e,query:t,key:n="",kind:i,limit:r=50,showUsage:o=!1}=s,a=n||t;if(!a&&!i)return{content:[{type:"text",text:'Error: Either "key" or "kind" parameter is required.'}]};await se(e);let l=F.getInstance(e),{configs:c,files:p}=l;if(a){x.info({repoPath:e,key:a},"Searching for config key in DB...");let m=c.findByKey(a,r);if(m.length===0)return{content:[{type:"text",text:`No configuration found for key: ${a}`}]};if(o){let g=m.map(w=>{let N=cc(p,w.key),U=N.count>0?"in-use":lc({file_path:w.file_path,kind:w.kind}),H=U==="in-use"?`\u2713 ${N.count} usage(s)`:U==="external-wiring"?"\u2699\uFE0F NO IN-REPO CODE REFERENCES":"\u26A0\uFE0F ORPHANED";return{file:dn.relative(e,w.file_path),key:w.key,value:w.value,kind:w.kind,usageCount:N.count,usageFiles:N.files.slice(0,5).map(C=>dn.relative(e,C)),status:H,disposition:U}});g.sort((w,N)=>{let U=H=>H==="orphaned"?0:H==="external-wiring"?1:2;return U(w.disposition)!==U(N.disposition)?U(w.disposition)-U(N.disposition):w.usageCount-N.usageCount});let y=g.filter(w=>w.disposition==="orphaned").length,E=g.filter(w=>w.disposition==="external-wiring").length;return{content:[{type:"text",text:(y>0?`# Configuration Search: "${a}" (with Usage Analysis)
815
895
 
816
- \u26A0\uFE0F **${b} orphaned var(s)** (defined but never used in code)
896
+ \u26A0\uFE0F **${y} likely orphaned setting(s)** (no in-repo code references detected in code-backed config)
817
897
 
818
898
  Found ${m.length} match(es):
819
899
 
820
900
  `:`# Configuration Search: "${a}" (with Usage Analysis)
821
901
 
822
- Found ${m.length} match(es), all in use:
823
-
824
- `)+g.map(R=>{let k=`## ${R.file} (${R.kind}) ${R.status}
825
- **${R.key}**: \`${R.value}\``;return R.usageCount>0&&R.usageFiles.length>0&&(k+=`
826
- > Used in: ${R.usageFiles.map(D=>`\`${D}\``).join(", ")}${R.usageCount>5?` (+${R.usageCount-5} more)`:""}`),k}).join(`
902
+ Found ${m.length} match(es).
903
+ ${E>0?`
904
+ ${E} item(s) have no in-repo code references but appear to be infrastructure/runtime wiring.
905
+ `:`
906
+ `}`)+g.map(w=>{let N=`## ${w.file} (${w.kind}) ${w.status}
907
+ **${w.key}**: \`${w.value}\``;return w.usageCount>0&&w.usageFiles.length>0?N+=`
908
+ > Used in: ${w.usageFiles.map(U=>`\`${U}\``).join(", ")}${w.usageCount>5?` (+${w.usageCount-5} more)`:""}`:w.disposition==="external-wiring"&&(N+=`
909
+ > No in-repo code references detected. This entry likely belongs to deployment, CI, or runtime wiring.`),N}).join(`
827
910
 
828
- `)}]}}let f=m.map(g=>({file:Yt.relative(e,g.file_path),key:g.key,value:g.value,kind:g.kind}));return{content:[{type:"text",text:`# Configuration Search: "${a}"
911
+ `)}]}}let f=m.map(g=>({file:dn.relative(e,g.file_path),key:g.key,value:g.value,kind:g.kind}));return{content:[{type:"text",text:`# Configuration Search: "${a}"
829
912
 
830
913
  Found ${m.length} match(es):
831
914
 
832
915
  `+f.map(g=>`## ${g.file} (${g.kind})
833
916
  **${g.key}**: \`${g.value}\``).join(`
834
917
 
835
- `)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let u=l.findByKind(i||null,r);if(o){let m=u.map(b=>{let w=Aa(p,b.key);return{file:Yt.relative(e,b.file_path),key:b.key,value:b.value,kind:b.kind,usageCount:w.count,usageFiles:w.files.slice(0,3).map(x=>Yt.relative(e,x)),status:w.count===0?"ORPHANED":"in-use"}});m.sort((b,w)=>b.usageCount===0&&w.usageCount>0?-1:w.usageCount===0&&b.usageCount>0?1:b.usageCount-w.usageCount);let f=m.filter(b=>b.usageCount===0).length,_=m.length,g=`# Config Discovery (${i||"all"}) with Usage Analysis
918
+ `)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let u=c.findByKind(i||null,r);if(o){let m=u.map(E=>{let k=cc(p,E.key),R=k.count>0?"in-use":lc({file_path:E.file_path,kind:E.kind});return{file:dn.relative(e,E.file_path),key:E.key,value:E.value,kind:E.kind,usageCount:k.count,usageFiles:k.files.slice(0,3).map(w=>dn.relative(e,w)),disposition:R}});m.sort((E,k)=>{let R=w=>w==="orphaned"?0:w==="external-wiring"?1:2;return R(E.disposition)!==R(k.disposition)?R(E.disposition)-R(k.disposition):E.usageCount-k.usageCount});let f=m.filter(E=>E.disposition==="orphaned").length,b=m.filter(E=>E.disposition==="external-wiring").length,g=m.length,y=`# Config Discovery (${i||"all"}) with Usage Analysis
836
919
 
837
- `;return g+=`**Summary**: ${_} config(s) found, ${f} orphaned
920
+ `;return y+=`**Summary**: ${g} config(s) found, ${f} likely orphaned, ${b} external/runtime-only
838
921
 
839
- `,f>0&&(g+=`## \u26A0\uFE0F Orphaned (${f})
840
- `,g+=m.filter(b=>b.usageCount===0).map(b=>`- \`${b.key}\` in ${b.file}`).join(`
841
- `),g+=`
922
+ `,f>0&&(y+=`## \u26A0\uFE0F Orphaned (${f})
923
+ `,y+=m.filter(E=>E.disposition==="orphaned").map(E=>`- \`${E.key}\` in ${E.file}`).join(`
924
+ `),y+=`
842
925
 
843
- `),g+=`## \u2713 In Use (${_-f})
844
- `,g+=m.filter(b=>b.usageCount>0).map(b=>{let w=b.usageFiles.length>0?`, used in ${b.usageFiles.map(x=>`\`${x}\``).join(", ")}${b.usageCount>3?` (+${b.usageCount-3} more)`:""}`:"";return`- \`${b.key}\`=\`${b.value}\` in \`${b.file}\` (${b.usageCount} usages${w})`}).join(`
845
- `),u.length===r&&(g+=`
926
+ `),b>0&&(y+=`## \u2699\uFE0F No In-Repo Code References (${b})
927
+ `,y+=m.filter(E=>E.disposition==="external-wiring").map(E=>`- \`${E.key}\` in \`${E.file}\` (likely deployment, CI, or runtime wiring rather than application code)`).join(`
928
+ `),y+=`
846
929
 
847
- > Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:g}]}}let d=u.map(m=>({...m,file:Yt.relative(e,m.file_path)})),h=JSON.stringify(d,null,2);return u.length===r&&(h=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
930
+ `),y+=`## \u2713 In Use (${m.filter(E=>E.disposition==="in-use").length})
931
+ `,y+=m.filter(E=>E.disposition==="in-use").map(E=>{let k=E.usageFiles.length>0?`, used in ${E.usageFiles.map(R=>`\`${R}\``).join(", ")}${E.usageCount>3?` (+${E.usageCount-3} more)`:""}`:"";return`- \`${E.key}\`=\`${E.value}\` in \`${E.file}\` (${E.usageCount} usages${k})`}).join(`
932
+ `),u.length===r&&(y+=`
848
933
 
849
- `+h),h+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:h}]}}V();It();import Pu from"fs";import Ma from"path";var Mu=new Set(["ClassDeclaration","FunctionDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","VariableDeclaration"]);function Na(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Os(s,e,t){let n=t.trim();return!!(!n||n.length>8e3||/^\w{1,4}\s+['"].*['"];?$/.test(n)&&!n.startsWith("export ")||n.includes(`
850
- import `)&&!n.startsWith("import ")||e&&Mu.has(e)&&s&&!new RegExp(`\\b${Na(s)}\\b`).test(n))}function Nu(s,e){let t=Math.max(0,(s.start_line||1)-1),n=Math.min(e.length,Math.max(t+1,(s.end_line||s.start_line||1)+1,t+120)),i=e.slice(t,n).join(`
851
- `),r=Ce(i,s.kind);return r?r.length>800?`${r.slice(0,797)}...`:r:s.signature||""}function Du(s,e,t){if(!s)return null;let n=Na(s),i=[];e==="TsTypeAliasDeclaration"&&i.push(new RegExp(`^\\s*export\\s+type\\s+${n}\\b`)),e==="TsInterfaceDeclaration"&&i.push(new RegExp(`^\\s*export\\s+interface\\s+${n}\\b`)),e==="FunctionDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:async\\s+)?function\\s+${n}\\b`)),e==="ClassDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:abstract\\s+)?class\\s+${n}\\b`)),e==="VariableDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`)),i.push(new RegExp(`\\b${n}\\b`));for(let r of i)for(let o=0;o<t.length;o++)if(r.test(t[o]))return o+1;return null}function Ou(s,e,t){let n=Math.max(0,s-1);if(e==="TsTypeAliasDeclaration"||e==="VariableDeclaration"||e==="TsEnumDeclaration"){for(let i=n;i<t.length;i++){if(t[i].includes(";"))return i+1;if(/^\s*export\s+(type|interface|class|function|const|let|var)\b/.test(t[i])&&i>n)return i}return Math.min(t.length,s+20)}if(e==="TsInterfaceDeclaration"||e==="ClassDeclaration"||e==="FunctionDeclaration"){let i=0,r=!1;for(let o=n;o<t.length;o++){let a=t[o];for(let c of a)c==="{"?(i+=1,r=!0):c==="}"&&(i-=1);if(r&&i<=0)return o+1}return Math.min(t.length,s+120)}return Math.min(t.length,s+40)}function Fu(s){return Array.isArray(s)?s.filter(e=>e.module!=="__type_reference__"):s}function Wu(s,e){return s?e==="TsTypeAliasDeclaration"?`type ${s}`:e==="TsInterfaceDeclaration"?`interface ${s}`:e==="FunctionDeclaration"?`function ${s}()`:e==="ClassDeclaration"?`class ${s}`:e==="VariableDeclaration"?`const ${s}`:`${e||"symbol"} ${s}`:e||"symbol"}function Hu(s,e){if(!s||e!=="TsTypeAliasDeclaration"&&e!=="TsInterfaceDeclaration")return s;let t=s.indexOf(`
852
- export `);return t<=0?s:s.slice(0,t).trim()}async function Ci(s){let{repoPath:e,filePath:t}=Ve(s);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=s.detailLevel||"signatures";await X(e);let{files:i,exports:r}=O.getInstance(e),o=i.findByPath(t),a=Ma.basename(t),c=/\.(ts|tsx|php|py|go)$/.test(a),l;c?l=await pn(t):l={exports:r.findByFile(t),imports:[]};let p=null;if(c)try{p=Pu.readFileSync(t,"utf8").split(`
853
- `)}catch{p=null}Array.isArray(l.exports)&&p&&(l.exports=l.exports.map(m=>{let f=typeof m.signature=="string"?m.signature:"",_=m.start_line??m.line??1,g=m.end_line??m.endLine??_;if(Os(m.name||"",m.kind,f)){let w=Du(m.name||"",m.kind,p),x=w??_,R=w?Ou(x,m.kind,p):g,k=Nu({name:m.name||"",kind:m.kind,signature:f,start_line:x,end_line:R},p),D=Hu(k,m.kind),U=Os(m.name||"",m.kind,D)?Wu(m.name||"",m.kind):D;return{...m,signature:U,start_line:x,end_line:R,line:x,endLine:R,members:Array.isArray(m.members)?m.members.filter(P=>{let E=typeof P.signature=="string"?P.signature:"";return!Os(P.name||"",P.kind,E)}):m.members}}return m})),l.imports=Fu(l.imports),n==="structure"?(l.exports=l.exports.map(m=>{let f={name:m.name,kind:m.kind,line:m.start_line,classification:m.classification};return m.members&&m.members.length>0?{...f,members:m.members.map(_=>({name:`${m.name}.${_.name}`,kind:_.kind,line:_.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(_=>({name:`${m.name}.${_.name}`,kind:_.kind,signature:_.signature,line:_.start_line}))}:f}),delete l.imports);let u=Ma.relative(e,t),d=l.exports?.length||0,h="";return n==="structure"&&d>0?h=`
934
+ > Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:y}]}}let d=u.map(m=>({...m,file:dn.relative(e,m.file_path)})),h=JSON.stringify(d,null,2);return u.length===r&&(h=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
854
935
 
855
- \u{1F4A1} Showing ${d} symbol names. For full signatures: shadow_inspect_file({ filePath: "${u}", detailLevel: "signatures" })`:n==="signatures"&&d>0&&(h=`
936
+ `+h),h+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:h}]}}Y();jt();import fd from"fs";import uc from"path";var hd=new Set(["ClassDeclaration","FunctionDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","VariableDeclaration"]),dc=new Set(["ClassDeclaration","ClassExpression"]);function fc(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nr(s,e,t){let n=t.trim();return!!(!n||n.length>8e3||/^\w{1,4}\s+['"].*['"];?$/.test(n)&&!n.startsWith("export ")||n.includes(`
937
+ import `)&&!n.startsWith("import ")||e&&hd.has(e)&&s&&!new RegExp(`\\b${fc(s)}\\b`).test(n))}function gd(s,e){let t=Math.max(0,(s.start_line||1)-1),n=Math.min(e.length,Math.max(t+1,(s.end_line||s.start_line||1)+1,t+120)),i=e.slice(t,n).join(`
938
+ `),r=Me(i,s.kind);return r?r.length>800?`${r.slice(0,797)}...`:r:s.signature||""}function yd(s,e,t){if(!s)return null;let n=fc(s),i=[];e==="TsTypeAliasDeclaration"&&i.push(new RegExp(`^\\s*export\\s+type\\s+${n}\\b`)),e==="TsInterfaceDeclaration"&&i.push(new RegExp(`^\\s*export\\s+interface\\s+${n}\\b`)),e==="FunctionDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:async\\s+)?function\\s+${n}\\b`)),e==="ClassDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:abstract\\s+)?class\\s+${n}\\b`)),e==="VariableDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`)),i.push(new RegExp(`\\b${n}\\b`));for(let r of i)for(let o=0;o<t.length;o++)if(r.test(t[o]))return o+1;return null}function bd(s,e,t){let n=Math.max(0,s-1);if(e==="TsTypeAliasDeclaration"||e==="VariableDeclaration"||e==="TsEnumDeclaration"){for(let i=n;i<t.length;i++){if(t[i].includes(";"))return i+1;if(/^\s*export\s+(type|interface|class|function|const|let|var)\b/.test(t[i])&&i>n)return i}return Math.min(t.length,s+20)}if(e==="TsInterfaceDeclaration"||e==="ClassDeclaration"||e==="FunctionDeclaration"){let i=0,r=!1;for(let o=n;o<t.length;o++){let a=t[o];for(let l of a)l==="{"?(i+=1,r=!0):l==="}"&&(i-=1);if(r&&i<=0)return o+1}return Math.min(t.length,s+120)}return Math.min(t.length,s+40)}function _d(s){return Array.isArray(s)?s.filter(e=>e.module!=="__type_reference__"):s}function Ed(s,e){return s?e==="TsTypeAliasDeclaration"?`type ${s}`:e==="TsInterfaceDeclaration"?`interface ${s}`:e==="FunctionDeclaration"?`function ${s}()`:e==="ClassDeclaration"?`class ${s}`:e==="VariableDeclaration"?`const ${s}`:`${e||"symbol"} ${s}`:e||"symbol"}function Sd(s,e){if(!s||e!=="TsTypeAliasDeclaration"&&e!=="TsInterfaceDeclaration")return s;let t=s.indexOf(`
939
+ export `);return t<=0?s:s.slice(0,t).trim()}function $n(s){return s.kind!=="DefaultExport"?void 0:typeof s.defaultTarget=="string"&&s.defaultTarget.trim()?s.defaultTarget.trim():(typeof s.signature=="string"?s.signature.trim():"").match(/^export\s+default\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*;?$/)?.[1]}function xd(s){let e=new Map;for(let t of s||[]){let n=typeof t.name=="string"?t.name.trim():"";n&&e.set(n,(e.get(n)||0)+1)}return new Set(Array.from(e.entries()).filter(([,t])=>t>1).map(([t])=>t))}function wd(s){switch(s.kind){case"TsInterfaceDeclaration":return"interface";case"TsTypeAliasDeclaration":return"type";case"TsEnumDeclaration":return"enum";case"ClassDeclaration":case"ClassExpression":return"class";case"FunctionDeclaration":return"function"}let e=typeof s.classification=="string"?s.classification.trim():"";if(!e)return s.kind==="VariableDeclaration"?"value":void 0;let t=e.toLowerCase();return t==="component"?"component":t==="hook"?"hook":t==="type definition"?"type":t==="default export"?"default":e}function mc(s,e){let t=$n(s);if(s.kind==="DefaultExport")return t?`default -> ${t}`:"default export";let n=typeof s.name=="string"?s.name.trim():"";if(!n||!e.has(n))return;let i=wd(s);return i?`${n} [${i}]`:void 0}async function Gi(s){let{repoPath:e,filePath:t}=He(s);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=s.detailLevel||"signatures";await se(e);let{files:i,exports:r}=F.getInstance(e),o=i.findByPath(t),a=uc.basename(t),l=/\.(ts|tsx|php|py|go)$/.test(a),c;l?c=await wn(t):c={exports:r.findByFile(t),imports:[]};let p=null;if(l)try{p=fd.readFileSync(t,"utf8").split(`
940
+ `)}catch{p=null}Array.isArray(c.exports)&&p&&(c.exports=c.exports.map(f=>{let b=typeof f.signature=="string"?f.signature:"",g=f.start_line??f.line??1,y=f.end_line??f.endLine??g;if(nr(f.name||"",f.kind,b)){let k=yd(f.name||"",f.kind,p),R=k??g,w=k?bd(R,f.kind,p):y,N=gd({name:f.name||"",kind:f.kind,signature:b,start_line:R,end_line:w},p),U=Sd(N,f.kind),H=nr(f.name||"",f.kind,U)?Ed(f.name||"",f.kind):U;return{...f,signature:H,start_line:R,end_line:w,line:R,endLine:w,members:Array.isArray(f.members)?f.members.filter(C=>{let M=typeof C.signature=="string"?C.signature:"";return!nr(C.name||"",C.kind,M)}):f.members}}return f}));let u=xd(c.exports);c.imports=_d(c.imports),n==="structure"?(delete c.content,c.exports=c.exports.map(f=>{let b=mc(f,u),g={name:f.name,kind:f.kind,line:f.start_line,classification:f.classification,...b?{displayName:b}:{},...$n(f)?{defaultTarget:$n(f)}:{}};return dc.has(f.kind)&&Array.isArray(f.members)&&f.members.length>0?{...g,members:f.members.map(y=>({name:`${f.name}.${y.name}`,kind:y.kind,line:y.start_line}))}:g}),delete c.imports):n==="signatures"&&(delete c.content,c.exports=c.exports.map(f=>{let b=mc(f,u),g={name:f.name,kind:f.kind,signature:f.signature,line:f.start_line,classification:f.classification,capabilities:JSON.parse(f.capabilities||"[]"),...b?{displayName:b}:{},...$n(f)?{defaultTarget:$n(f)}:{}};return dc.has(f.kind)&&Array.isArray(f.members)&&f.members.length>0?{...g,members:f.members.map(y=>({name:`${f.name}.${y.name}`,kind:y.kind,signature:y.signature,line:y.start_line}))}:g}),delete c.imports);let d=uc.relative(e,t),h=c.exports?.length||0,m="";return n==="structure"&&h>0?m=`
856
941
 
857
- \u{1F4A1} Showing ${d} complete signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...l,fileDescription:o?.summary||"",classification:o?.classification&&o.classification!=="Unknown"?o.classification:Ct(t,O.getInstance(e)).layer},null,2)+h}]}}V();import Da from"path";import zu from"fs";function Uu(s,e,t){let n=s.split(`
858
- `),i=[],r=0;for(let u=0;u<Math.min(n.length,50);u++){let d=n[u].trim();if(d.startsWith("import ")||d.startsWith("from ")||d.startsWith("export ")&&d.includes(" from "))r=u+1;else if(d&&!d.startsWith("//")&&!d.startsWith("/*")&&!d.startsWith("*")&&d!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((u,d)=>u.startLine-d.startLine),a=0,c=0;for(let u of o)if(u.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${u.name} \u2501\u2501\u2501`);let d=n.slice(u.startLine-1,u.endLine);i.push(...d),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),c++}else{let d=u.signature||ju(n,u.startLine-1,u.kind);d&&(i.push(`${d}`),i.push(` /* implementation: ${u.lineCount} lines */`),i.push(""),a++)}let l=o[o.length-1];if(l)for(let u=l.endLine;u<n.length;u++){let d=n[u].trim();if(d==="}"||d==="};"){i.push(n[u]);break}else if(d&&!d.startsWith("//"))break}return{foldedSource:i.join(`
859
- `),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:c,siblingsFolded:a}}function ju(s,e,t){let n=s[e];if(t.includes("Function")||t.includes("Method")||t.includes("Arrow")){let i="";for(let r=e;r<Math.min(e+5,s.length);r++)if(i+=s[r],i.includes("{")||i.includes("=>")){let o=i.indexOf("{");o>0&&(i=i.substring(0,o).trim());break}return i.trim()}return n}function Bu(s,e=","){let t=[],n="",i=0,r=0,o=0,a=0,c=null,l=!1;for(let u of s){if(c){if(n+=u,l){l=!1;continue}if(u==="\\"){l=!0;continue}u===c&&(c=null);continue}if(u==='"'||u==="'"||u==="`"){c=u,n+=u;continue}if(u==="("?i++:u===")"?i=Math.max(0,i-1):u==="{"?r++:u==="}"?r=Math.max(0,r-1):u==="["?o++:u==="]"?o=Math.max(0,o-1):u==="<"?a++:u===">"&&(a=Math.max(0,a-1)),u===e&&i===0&&r===0&&o===0&&a===0){let d=n.trim();d&&t.push(d),n="";continue}n+=u}let p=n.trim();return p&&t.push(p),t}function Gu(s){let e=s.indexOf("(");if(e<0)return null;let t=0;for(let n=e;n<s.length;n++){let i=s[n];if(i==="("&&t++,i===")"&&(t--,t===0))return{start:e,end:n}}return null}function Ii(s,e){let t=0,n=0,i=0,r=0,o=null,a=!1;for(let c=0;c<s.length;c++){let l=s[c];if(o){a?a=!1:l==="\\"?a=!0:l===o&&(o=null);continue}if(l==='"'||l==="'"||l==="`"){o=l;continue}if(l==="("?t++:l===")"?t=Math.max(0,t-1):l==="{"?n++:l==="}"?n=Math.max(0,n-1):l==="["?i++:l==="]"?i=Math.max(0,i-1):l==="<"?r++:l===">"&&(r=Math.max(0,r-1)),l===e&&t===0&&n===0&&i===0&&r===0)return c}return-1}function qu(s){let t=s.trim(),n=!1;t.startsWith("...")&&(n=!0,t=t.slice(3).trim());let i=Ii(t,"="),r=i>=0,o=r?t.slice(0,i).trim():t,a=r?t.slice(i+1).trim():void 0,c=Ii(o,":"),l=(c>=0?o.slice(0,c):o).replace(/^(?:readonly\s+)?(?:public|private|protected)\s+/,"").trim(),p=l.includes("?"),u=l.replace(/\?/g,"").trim(),d=c>=0&&o.slice(c+1).trim()||null;return{name:u||"(anonymous)",type:d,optional:p,rest:n,hasDefault:r,...a?{defaultValue:a}:{}}}function Vu(s,e){let t=s.slice(e+1).trim();if(!t)return null;let n=t.indexOf("=>");if(n>=0){let r=t.slice(0,n).trim(),o=Ii(r,":");if(o>=0){let c=r.slice(o+1).trim();if(c)return c}return t.slice(n+2).replace(/\{.*$/,"").trim()||null}let i=Ii(t,":");return i>=0&&t.slice(i+1).replace(/\{.*$/,"").trim()||null}function Ju(s){let e=s.trim();if(!e)return[];if(e==="*")return["*"];if(e.startsWith("[")&&e.endsWith("]"))try{let n=JSON.parse(e);if(Array.isArray(n))return n.map(i=>String(i).trim()).filter(Boolean).map(i=>i.replace(/^['"`]|['"`]$/g,""))}catch{}return e.replace(/^\{|\}$/g,"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.replace(/^type\s+/,"")).map(n=>n.split(/\s+as\s+/i)[0]?.trim()||n).map(n=>n.replace(/^['"`]|['"`]$/g,""))}function Yu(s,e,t){let n=s?.replace(/\s+/g," ").trim()||null,r=n?.match(/\b(public|private|protected)\b/)?.[1]||null,a=(n?.match(/\bfunction\s*\*?\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/^(?:export\s+)?(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\(/))?.[1]||e,c=n?Gu(n):null,l=n&&c?n.slice(c.start+1,c.end):"",p=l?Bu(l).map(qu):[],u=n&&c?Vu(n,c.end):null,d=n?.match(/(?:function\s+[A-Za-z_$][A-Za-z0-9_$]*|[A-Za-z_$][A-Za-z0-9_$]*)\s*(<[^>]+>)\s*\(/);return{raw:s,normalized:n,symbol:a,kind:t,visibility:r,isStatic:/\bstatic\b/.test(n||""),isAsync:/\basync\b/.test(n||""),isGenerator:/function\s*\*/.test(n||"")||/\*\s*[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(n||""),isArrowFunction:/=>/.test(n||""),typeParameters:d?.[1]||null,parameters:p,parameterCount:p.length,returnType:u}}function Ku(s,e,t=5){let n=new Map;for(let o of s){let a=n.get(o.file_path)||{classification:o.classification||null,importedSymbols:new Set,wildcard:!1},c=Ju(o.imported_symbols);(c.length===0||c.includes("*"))&&(a.wildcard=!0);for(let l of c)a.importedSymbols.add(l);!a.classification&&o.classification&&(a.classification=o.classification),n.set(o.file_path,a)}let i=Array.from(n.entries()).map(([o,a])=>({file:Da.relative(e,o),classification:a.classification,importedSymbols:a.importedSymbols.size>0?Array.from(a.importedSymbols).sort():["*"],wildcard:a.wildcard})),r=i.slice(0,Math.max(1,t));return{totalVerifiedCallers:i.length,showing:r.length,wildcardCallers:i.filter(o=>o.wildcard).length,topCallers:r.map(({wildcard:o,...a})=>a)}}async function Kt(s){let{repoPath:e,filePath:t,resolver:n}=Ve(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 X(e);let o=O.getInstance(e),a=[];if(i.includes(".")){let[E,T]=i.split(".");a=o.exports.findMemberCandidates(E,T,t)}else a=o.exports.findDefinitionCandidates(i,t);if(a.length===0){let E=o.exports.findPotentialParents(i);if(E.length>0){let N=E.map($=>`\`${$.name}\` (in ${n.getRelative($.file_path)})`).join(", ");return{content:[{type:"text",text:`Symbol "${i}" not found as a top-level export.
860
- However, it likely exists inside: ${N}.
861
- Try: shadow_inspect_symbol({ symbolName: "${E[0].name}", context: "full" }) to see the class body.`}]}}let I=o.exports.findFuzzyCandidates(i).map(N=>N.name),M=bn(i,I,50,3);if(M.length>0){let N=M.map($=>` \u2022 \`${$.match}\` (${$.score}% match)`).join(`
942
+ \u{1F4A1} Showing ${h} top-level symbol names. For full signatures: shadow_inspect_file({ filePath: "${d}", detailLevel: "signatures" })`:n==="signatures"&&h>0&&(m=`
943
+
944
+ \u{1F4A1} Showing ${h} top-level signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...c,fileDescription:o?.summary||"",classification:o?.classification&&o.classification!=="Unknown"?o.classification:Ut(t,F.getInstance(e)).layer},null,2)+m}]}}Y();import hc from"path";import vd from"fs";function Rd(s,e,t){let n=s.split(`
945
+ `),i=[],r=0;for(let u=0;u<Math.min(n.length,50);u++){let d=n[u].trim();if(d.startsWith("import ")||d.startsWith("from ")||d.startsWith("export ")&&d.includes(" from "))r=u+1;else if(d&&!d.startsWith("//")&&!d.startsWith("/*")&&!d.startsWith("*")&&d!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((u,d)=>u.startLine-d.startLine),a=0,l=0;for(let u of o)if(u.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${u.name} \u2501\u2501\u2501`);let d=n.slice(u.startLine-1,u.endLine);i.push(...d),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),l++}else{let d=u.signature||Td(n,u.startLine-1,u.kind);d&&(i.push(`${d}`),i.push(` /* implementation: ${u.lineCount} lines */`),i.push(""),a++)}let c=o[o.length-1];if(c)for(let u=c.endLine;u<n.length;u++){let d=n[u].trim();if(d==="}"||d==="};"){i.push(n[u]);break}else if(d&&!d.startsWith("//"))break}return{foldedSource:i.join(`
946
+ `),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:l,siblingsFolded:a}}function Td(s,e,t){let n=s[e];if(t.includes("Function")||t.includes("Method")||t.includes("Arrow")){let i="";for(let r=e;r<Math.min(e+5,s.length);r++)if(i+=s[r],i.includes("{")||i.includes("=>")){let o=i.indexOf("{");o>0&&(i=i.substring(0,o).trim());break}return i.trim()}return n}function kd(s,e=","){let t=[],n="",i=0,r=0,o=0,a=0,l=null,c=!1;for(let u of s){if(l){if(n+=u,c){c=!1;continue}if(u==="\\"){c=!0;continue}u===l&&(l=null);continue}if(u==='"'||u==="'"||u==="`"){l=u,n+=u;continue}if(u==="("?i++:u===")"?i=Math.max(0,i-1):u==="{"?r++:u==="}"?r=Math.max(0,r-1):u==="["?o++:u==="]"?o=Math.max(0,o-1):u==="<"?a++:u===">"&&(a=Math.max(0,a-1)),u===e&&i===0&&r===0&&o===0&&a===0){let d=n.trim();d&&t.push(d),n="";continue}n+=u}let p=n.trim();return p&&t.push(p),t}function Cd(s){let e=s.indexOf("(");if(e<0)return null;let t=0;for(let n=e;n<s.length;n++){let i=s[n];if(i==="("&&t++,i===")"&&(t--,t===0))return{start:e,end:n}}return null}function qi(s,e){let t=0,n=0,i=0,r=0,o=null,a=!1;for(let l=0;l<s.length;l++){let c=s[l];if(o){a?a=!1:c==="\\"?a=!0:c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="("?t++:c===")"?t=Math.max(0,t-1):c==="{"?n++:c==="}"?n=Math.max(0,n-1):c==="["?i++:c==="]"?i=Math.max(0,i-1):c==="<"?r++:c===">"&&(r=Math.max(0,r-1)),c===e&&t===0&&n===0&&i===0&&r===0)return l}return-1}function Id(s){let t=s.trim(),n=!1;t.startsWith("...")&&(n=!0,t=t.slice(3).trim());let i=qi(t,"="),r=i>=0,o=r?t.slice(0,i).trim():t,a=r?t.slice(i+1).trim():void 0,l=qi(o,":"),c=(l>=0?o.slice(0,l):o).replace(/^(?:readonly\s+)?(?:public|private|protected)\s+/,"").trim(),p=c.includes("?"),u=c.replace(/\?/g,"").trim(),d=l>=0&&o.slice(l+1).trim()||null;return{name:u||"(anonymous)",type:d,optional:p,rest:n,hasDefault:r,...a?{defaultValue:a}:{}}}function Ld(s,e){let t=s.slice(e+1).trim();if(!t)return null;let n=t.indexOf("=>");if(n>=0){let r=t.slice(0,n).trim(),o=qi(r,":");if(o>=0){let l=r.slice(o+1).trim();if(l)return l}return t.slice(n+2).replace(/\{.*$/,"").trim()||null}let i=qi(t,":");return i>=0&&t.slice(i+1).replace(/\{.*$/,"").trim()||null}function Md(s){let e=s.trim();if(!e)return[];if(e==="*")return["*"];if(e.startsWith("[")&&e.endsWith("]"))try{let n=JSON.parse(e);if(Array.isArray(n))return n.map(i=>String(i).trim()).filter(Boolean).map(i=>i.replace(/^['"`]|['"`]$/g,""))}catch{}return e.replace(/^\{|\}$/g,"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.replace(/^type\s+/,"")).map(n=>n.split(/\s+as\s+/i)[0]?.trim()||n).map(n=>n.replace(/^['"`]|['"`]$/g,""))}function $d(s,e,t){let n=s?.replace(/\s+/g," ").trim()||null,r=n?.match(/\b(public|private|protected)\b/)?.[1]||null,a=(n?.match(/\bfunction\s*\*?\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/^(?:export\s+)?(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\(/))?.[1]||e,l=n?Cd(n):null,c=n&&l?n.slice(l.start+1,l.end):"",p=c?kd(c).map(Id):[],u=n&&l?Ld(n,l.end):null,d=n?.match(/(?:function\s+[A-Za-z_$][A-Za-z0-9_$]*|[A-Za-z_$][A-Za-z0-9_$]*)\s*(<[^>]+>)\s*\(/);return{raw:s,normalized:n,symbol:a,kind:t,visibility:r,isStatic:/\bstatic\b/.test(n||""),isAsync:/\basync\b/.test(n||""),isGenerator:/function\s*\*/.test(n||"")||/\*\s*[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(n||""),isArrowFunction:/=>/.test(n||""),typeParameters:d?.[1]||null,parameters:p,parameterCount:p.length,returnType:u}}function Ad(s,e,t=5){let n=new Map;for(let o of s){let a=n.get(o.file_path)||{classification:o.classification||null,importedSymbols:new Set,wildcard:!1},l=Md(o.imported_symbols);(l.length===0||l.includes("*"))&&(a.wildcard=!0);for(let c of l)a.importedSymbols.add(c);!a.classification&&o.classification&&(a.classification=o.classification),n.set(o.file_path,a)}let i=Array.from(n.entries()).map(([o,a])=>({file:hc.relative(e,o),classification:a.classification,importedSymbols:a.importedSymbols.size>0?Array.from(a.importedSymbols).sort():["*"],wildcard:a.wildcard})),r=i.slice(0,Math.max(1,t));return{totalVerifiedCallers:i.length,showing:r.length,wildcardCallers:i.filter(o=>o.wildcard).length,topCallers:r.map(({wildcard:o,...a})=>a)}}async function mn(s){let{repoPath:e,filePath:t,resolver:n}=He(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 se(e);let o=F.getInstance(e),a=[];if(i.includes(".")){let[M,D]=i.split(".");a=o.exports.findMemberCandidates(M,D,t)}else a=o.exports.findDefinitionCandidates(i,t);if(a.length===0){let M=o.exports.findPotentialParents(i);if(M.length>0){let L=M.map(A=>`\`${A.name}\` (in ${n.getRelative(A.file_path)})`).join(", ");return{content:[{type:"text",text:`Symbol "${i}" not found as a top-level export.
947
+ However, it likely exists inside: ${L}.
948
+ Try: shadow_inspect_symbol({ symbolName: "${M[0].name}", context: "full" }) to see the class body.`}]}}let P=o.exports.findFuzzyCandidates(i).map(L=>L.name),B=Mn(i,P,50,3);if(B.length>0){let L=B.map(A=>` \u2022 \`${A.match}\` (${A.score}% match)`).join(`
862
949
  `);return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
863
950
 
864
951
  Suggestions:
865
- ${N}
952
+ ${L}
866
953
 
867
954
  Next steps:
868
955
  \u2022 Search semantically: shadow_search_concept({ query: "${i}" })
@@ -871,40 +958,40 @@ Next steps:
871
958
  Next steps:
872
959
  \u2022 Search for it: shadow_search_concept({ query: "${i}" })
873
960
  \u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${i}", filePath: "..." })
874
- `}]}}let c=a[0];if(c.kind==="ExportSpecifier"||c.kind==="ExportAllDeclaration"){let E=o.imports.findImportSource(c.file_path,i);if(E&&E.resolved_path)return Kt({...s,filePath:E.resolved_path})}let l=zu.readFileSync(c.file_path,"utf8"),p=l.split(`
875
- `),u=c.end_line-c.start_line+1,d=150,h,m=!1,f=null;if(r==="definition"&&u>d){let T=o.exports.findSiblings(c.file_path).map(I=>({name:I.name,kind:I.kind,signature:I.signature||"",startLine:I.start_line,endLine:I.end_line,lineCount:I.end_line-I.start_line+1,isTarget:I.name===c.name&&I.start_line===c.start_line,parentName:I.parent_name}));if(T.length>1){f=Uu(l,{name:c.name,startLine:c.start_line,endLine:c.end_line},T);let I=n.getRelative(c.file_path);h=f.foldedSource+`
961
+ `}]}}let l=a[0];if(l.kind==="ExportSpecifier"||l.kind==="ExportAllDeclaration"){let M=o.imports.findImportSource(l.file_path,i);if(M&&M.resolved_path)return mn({...s,filePath:M.resolved_path})}let c=vd.readFileSync(l.file_path,"utf8"),p=c.split(`
962
+ `),u=l.end_line-l.start_line+1,d=150,h,m=!1,f=null,b=null;if(r==="definition"&&u>d){let D=o.exports.findSiblings(l.file_path).map(P=>({name:P.name,kind:P.kind,signature:P.signature||"",startLine:P.start_line,endLine:P.end_line,lineCount:P.end_line-P.start_line+1,isTarget:P.name===l.name&&P.start_line===l.start_line,parentName:P.parent_name}));if(D.length>1){f=Rd(c,{name:l.name,startLine:l.start_line,endLine:l.end_line},D);let P=n.getRelative(l.file_path);h=f.foldedSource+`
876
963
 
877
964
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
878
965
  \u{1F4CA} Semantic Fold Applied (context: "definition")
879
966
 
880
967
  Original file: ${f.totalOriginalLines} lines
881
968
  Folded view: ${f.foldedToLines} lines
882
- Target Symbol: ${c.name}
969
+ Target Symbol: ${l.name}
883
970
  \u{1F4A1} Need more context?
884
- \u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${c.name}", context: "full" })
885
- \u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${I}", detailLevel: "signatures" })
886
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,m=!0}else h=p.slice(c.start_line-1,c.start_line-1+d).join(`
971
+ \u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${l.name}", context: "full" })
972
+ \u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${P}", detailLevel: "signatures" })
973
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,m=!0,b=f.foldedToLines}else{let P=p.slice(l.start_line-1,l.start_line-1+d);h=P.join(`
887
974
  `)+`
888
975
 
889
- ... (truncated ${u-d} lines)`,m=!0}else h=p.slice(c.start_line-1,c.end_line).join(`
890
- `);let _=c.parent_name?`${c.parent_name}.${c.name}`:c.name,g=o.exports.findHydratedById(c.id),b=c.parent_name||c.name,w=o.imports.findProxies(c.file_path).map(E=>E.file_path),x=Array.from(new Set([c.file_path,...w])),R=o.imports.findVerifiedDependents(x,b),k=Ku(R,e),D=Yu(c.signature,_,c.kind),U={name:_,kind:c.kind,signature:D,file:n.getRelative(c.file_path),startLine:c.start_line,endLine:c.end_line,totalLines:u,...m&&{truncated:!0,previewLines:d},classification:c.classification,callerSummary:k,source:h};if(g&&g.recent_intents&&g.recent_intents.length>0){let E={},T=Date.now();for(let I of g.recent_intents){if(I.is_crystallized&&I.type!=="crystal")continue;let M=I.created_at;M<1e10&&(M*=1e3);let N=new Date(M).getTime(),$=T-N,W="just now";if($>0){let L=Math.floor($/1e3),A=Math.floor(L/60),H=Math.floor(A/60),F=Math.floor(H/24);F>0?W=`${F}d ago`:H>0?W=`${H}h ago`:A>0?W=`${A}m ago`:W=`${L}s ago`}E[I.type]||(E[I.type]=[]),E[I.type].push(`[${W}] ${I.content}`)}U.intelligence={working_set_of:g.active_missions.map(I=>`Mission #${I.id}: ${I.name}`),total_intents:g.intent_log_count,recent_activity:E}}else g&&(U.intelligence={working_set_of:g.active_missions.map(E=>`Mission #${E.id}: ${E.name}`),total_intents:g.intent_log_count,recent_activity:null});try{let{generateEmbedding:E}=await Promise.resolve().then(()=>(Ae(),ot)),T=`Symbol: ${U.name}
891
- Signature: ${c.signature||""}
892
- File: ${U.file}`,I=await E(T);if(I){let M=o.intentLogs.findSemanticMatches(I,3,c.id),N=new Promise(W=>setTimeout(()=>W([]),100)),$=await Promise.race([M,N]);$&&$.length>0&&(U.intelligence||(U.intelligence={}),U.intelligence.related_knowledge=$.map(W=>({type:W.type,content:W.content,from_symbol:W.symbol_name,similarity:`${(W.similarity*100).toFixed(0)}%`})))}}catch{}if(r==="definition")return{content:[{type:"text",text:JSON.stringify(U,null,2)}]};let P={definition:U,dependencies:o.imports.getImportsForFile(c.file_path).map(E=>({module:E.module_specifier,symbols:E.imported_symbols,relativePath:E.resolved_path?Da.relative(e,E.resolved_path):null})),callerSummary:k};return P.verifiedUsages=k.topCallers,{content:[{type:"text",text:JSON.stringify(P,null,2)}]}}async function Oa(s,e){let t=_n.resolve(e.dir);await Y(async()=>{pe("Semantic Concept Search");let n=Re();n.start(`Analyzing intent: "${y.bold(s)}"...`);try{let i=await $a({repoPath:t,query:s});n.stop("Analysis complete.");let r=i.content[0].text;if(r.includes("Found")){let a=r.split("## ").slice(1).map(c=>{let[l,...p]=c.split(`
976
+ ... (truncated ${u-d} lines)`,m=!0,b=P.length}}else h=p.slice(l.start_line-1,l.end_line).join(`
977
+ `);let g=l.parent_name?`${l.parent_name}.${l.name}`:l.name,y=o.exports.findHydratedById(l.id),E=l.parent_name||l.name,k=o.imports.findProxies(l.file_path).map(M=>M.file_path),R=Array.from(new Set([l.file_path,...k])),w=o.imports.findVerifiedDependents(R,E),N=Ad(w,e),U=$d(l.signature,g,l.kind),H={name:g,kind:l.kind,signature:U,file:n.getRelative(l.file_path),startLine:l.start_line,endLine:l.end_line,totalLines:u,...m&&b!==null&&{truncated:!0,previewLines:b},...f&&{semanticFold:{totalOriginalLines:f.totalOriginalLines,foldedToLines:f.foldedToLines,siblingsShown:f.siblingsShown,siblingsFolded:f.siblingsFolded}},classification:l.classification,callerSummary:N,source:h};if(y&&y.recent_intents&&y.recent_intents.length>0){let M={},D=Date.now();for(let P of y.recent_intents){if(P.is_crystallized&&P.type!=="crystal")continue;let B=P.created_at;B<1e10&&(B*=1e3);let L=new Date(B).getTime(),A=D-L,$="just now";if(A>0){let W=Math.floor(A/1e3),J=Math.floor(W/60),O=Math.floor(J/60),S=Math.floor(O/24);S>0?$=`${S}d ago`:O>0?$=`${O}h ago`:J>0?$=`${J}m ago`:$=`${W}s ago`}M[P.type]||(M[P.type]=[]),M[P.type].push(`[${$}] ${P.content}`)}H.intelligence={working_set_of:y.active_missions.map(P=>`Mission #${P.id}: ${P.name}`),total_intents:y.intent_log_count,recent_activity:M}}else y&&(H.intelligence={working_set_of:y.active_missions.map(M=>`Mission #${M.id}: ${M.name}`),total_intents:y.intent_log_count,recent_activity:null});try{let{generateEmbedding:M}=await Promise.resolve().then(()=>(Ve(),Et)),D=`Symbol: ${H.name}
978
+ Signature: ${l.signature||""}
979
+ File: ${H.file}`,P=await M(D);if(P){let B=o.intentLogs.findSemanticMatches(P,3,l.id),L=new Promise($=>setTimeout(()=>$([]),100)),A=await Promise.race([B,L]);A&&A.length>0&&(H.intelligence||(H.intelligence={}),H.intelligence.related_knowledge=A.map($=>({type:$.type,content:$.content,from_symbol:$.symbol_name,similarity:`${($.similarity*100).toFixed(0)}%`})))}}catch{}if(r==="definition")return{content:[{type:"text",text:JSON.stringify(H,null,2)}]};let C={definition:H,dependencies:o.imports.getImportsForFile(l.file_path).map(M=>({module:M.module_specifier,symbols:M.imported_symbols,relativePath:M.resolved_path?hc.relative(e,M.resolved_path):null})),callerSummary:N};return C.verifiedUsages=N.topCallers,{content:[{type:"text",text:JSON.stringify(C,null,2)}]}}async function gc(s,e){let t=An.resolve(e.dir);await Z(async()=>{ge("Semantic Concept Search");let n=Fe();n.start(`Analyzing intent: "${_.bold(s)}"...`);try{let i=await ac({repoPath:t,query:s});n.stop("Analysis complete.");let r=i.content[0].text;if(r.includes("Found")){let a=r.split("## ").slice(1).map(l=>{let[c,...p]=l.split(`
893
980
 
894
- `),[u,d]=l.split(" ( "),h=(u??"").replace(/^\d+\.\s*/,"").trim(),m=p.find(f=>f.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:h,matchPct:d??"",summaryLine:m}});if(a.forEach(({name:c,matchPct:l,summaryLine:p})=>{se(`${y.green(c)} ${y.dim("("+(l||""))}`,p,"blue"),console.log("")}),e.interactive&&a.length>1){let c=await Gn("Inspect a file",a.map(l=>({value:{name:l.name},label:l.name,hint:l.summaryLine.slice(0,50)})),{limit:15});if(c){let l=c.name.startsWith(t)?c.name:_n.join(t,c.name),p=await Ci({repoPath:t,filePath:l});p.content?.[0]&&(console.log(""),se(y.bold("File summary"),p.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await Q(t)}})}async function Fa(s,e){let t=_n.resolve(e.dir);await Y(async()=>{pe("Symbol Search");let n=Re();n.start(`Searching symbols: "${y.bold(s)}"...`);try{let i=await Ds({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(""),jn(["Symbol","Kind","File","Line"],o.map(a=>[y.bold(y.green(a.name)),y.dim(a.kind??""),y.cyan(a.file??""),y.yellow(String(a.line??""))])),e.interactive&&o.length>1){let a=o.map(l=>({value:l,label:l.name,hint:`${l.file??""}:${l.line??""}`})),c=await Gn("Inspect symbol",a,{limit:15});if(c){let l=await Kt({repoPath:t,symbolName:c.name});l.content?.[0]&&(console.log(""),se(y.bold(c.name),l.content[0].text,"cyan"))}}}else console.log(r)}catch{console.log(r)}}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await Q(t)}})}async function Wa(s,e){let t=_n.resolve(e.dir);await Y(async()=>{pe("Fuzzy Symbol Search");let n=Re();n.start(`Fuzzy matching: "${y.bold(s)}"...`);try{let i=await Ds({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;if(r.includes("## ")){let a=r.split("## ").slice(1).map(c=>{let l=c.split(`
895
- `),p=l[0],u=l.find(g=>g.startsWith("**Match**:"))||"",d=l.find(g=>g.startsWith("**File**:"))||"",h=p.match(/`([^`]+)`/),m=h?h[1]:"",f=u.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),_=d.match(/`([^:]+):(\d+)`/);return{symbolName:m,file:_?_[1]:"",line:_?_[2]:"",matchType:f?f[1]:"",confidence:f?f[2]:""}});if(console.log(""),console.log(y.dim(`Found ${a.length} fuzzy match(es):`)),console.log(""),a.forEach((c,l)=>{console.log(`${y.dim(`${l+1}.`)} ${y.bold(y.green(c.symbolName))} ${y.dim(`(${c.matchType}, ${c.confidence}% match)`)}`),console.log(` ${y.cyan(c.file)}:${y.yellow(c.line)}`),console.log("")}),e.interactive&&a.length>1){let c=await Gn("Inspect symbol",a.map(l=>({value:l,label:l.symbolName,hint:`${l.file}:${l.line}`})),{limit:15});if(c){let l=await Kt({repoPath:t,symbolName:c.symbolName});l.content?.[0]&&(console.log(""),se(y.bold(c.symbolName),l.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await Q(t)}})}async function Ha(s,e){let t=_n.resolve(e.dir);await Y(async()=>{pe("Config Search");let n=Re();n.start(`Searching config: ${y.bold(s||"all")}...`);try{let i=await Pa({repoPath:t,key:s,kind:e.kind});n.stop("Search complete."),se("\u2699\uFE0F Results",i.content[0].text,"yellow")}finally{await Q(t)}})}q();var Fs=S.child({module:"mcp:tools:env:hooks"});async function Li(s){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:i}=s;if(t==="install"){Fs.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:i},"Installing git hooks");let r=zr({repoPath:e,enableAutoRefresh:n??!0,enableSymbolHealing:i??!0}),o=["# Git Hooks Installation","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(a=>`- \`${a}\``).join(`
981
+ `),[u,d]=c.split(" ( "),h=(u??"").replace(/^\d+\.\s*/,"").trim(),m=p.find(f=>f.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:h,matchPct:d??"",summaryLine:m}});if(a.forEach(({name:l,matchPct:c,summaryLine:p})=>{ue(`${_.green(l)} ${_.dim("("+(c||""))}`,p,"blue"),console.log("")}),e.interactive&&a.length>1){let l=await ai("Inspect a file",a.map(c=>({value:{name:c.name},label:c.name,hint:c.summaryLine.slice(0,50)})),{limit:15});if(l){let c=l.name.startsWith(t)?l.name:An.join(t,l.name),p=await Gi({repoPath:t,filePath:c});p.content?.[0]&&(console.log(""),ue(_.bold("File summary"),p.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function yc(s,e){let t=An.resolve(e.dir);await Z(async()=>{ge("Symbol Search");let n=Fe();n.start(`Searching symbols: "${_.bold(s)}"...`);try{let i=await tr({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(""),ri(["Symbol","Kind","File","Line"],o.map(a=>[_.bold(_.green(a.name)),_.dim(a.kind??""),_.cyan(a.file??""),_.yellow(String(a.line??""))])),e.interactive&&o.length>1){let a=o.map(c=>({value:c,label:c.name,hint:`${c.file??""}:${c.line??""}`})),l=await ai("Inspect symbol",a,{limit:15});if(l){let c=await mn({repoPath:t,symbolName:l.name});c.content?.[0]&&(console.log(""),ue(_.bold(l.name),c.content[0].text,"cyan"))}}}else console.log(r)}catch{console.log(r)}}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function bc(s,e){let t=An.resolve(e.dir);await Z(async()=>{ge("Fuzzy Symbol Search");let n=Fe();n.start(`Fuzzy matching: "${_.bold(s)}"...`);try{let i=await tr({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;if(r.includes("## ")){let a=r.split("## ").slice(1).map(l=>{let c=l.split(`
982
+ `),p=c[0],u=c.find(g=>g.startsWith("**Match**:"))||"",d=c.find(g=>g.startsWith("**File**:"))||"",h=p.match(/`([^`]+)`/),m=h?h[1]:"",f=u.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),b=d.match(/`([^:]+):(\d+)`/);return{symbolName:m,file:b?b[1]:"",line:b?b[2]:"",matchType:f?f[1]:"",confidence:f?f[2]:""}});if(console.log(""),console.log(_.dim(`Found ${a.length} fuzzy match(es):`)),console.log(""),a.forEach((l,c)=>{console.log(`${_.dim(`${c+1}.`)} ${_.bold(_.green(l.symbolName))} ${_.dim(`(${l.matchType}, ${l.confidence}% match)`)}`),console.log(` ${_.cyan(l.file)}:${_.yellow(l.line)}`),console.log("")}),e.interactive&&a.length>1){let l=await ai("Inspect symbol",a.map(c=>({value:c,label:c.symbolName,hint:`${c.file}:${c.line}`})),{limit:15});if(l){let c=await mn({repoPath:t,symbolName:l.symbolName});c.content?.[0]&&(console.log(""),ue(_.bold(l.symbolName),c.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function _c(s,e){let t=An.resolve(e.dir);await Z(async()=>{ge("Config Search");let n=Fe();n.start(`Searching config: ${_.bold(s||"all")}...`);try{let i=await pc({repoPath:t,key:s,kind:e.kind});n.stop("Search complete."),ue("\u2699\uFE0F Results",i.content[0].text,"yellow")}finally{await ne(t)}})}G();var ir=x.child({module:"mcp:tools:env:hooks"});async function Vi(s){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:i}=s;if(t==="install"){ir.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:i},"Installing git hooks");let r=go({repoPath:e,enableAutoRefresh:n??!0,enableSymbolHealing:i??!0}),o=["# Git Hooks Installation","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(a=>`- \`${a}\``).join(`
896
983
  `):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(a=>`- \`${a}\` (already installed)`).join(`
897
984
  `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
898
985
  `)),o.push("")),o.push("---"),o.push("**What happens now?**"),(n??!0)&&o.push("- After `git pull` or `git checkout`: Index auto-refreshes in background"),(i??!0)&&o.push("- After `git commit`: Symbol shift detection runs automatically"),{content:[{type:"text",text:o.join(`
899
- `)}]}}if(t==="remove"){Fs.info({repoPath:e},"Uninstalling git hooks");let r=Ur(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(a=>`- \`${a}\``).join(`
986
+ `)}]}}if(t==="remove"){ir.info({repoPath:e},"Uninstalling git hooks");let r=yo(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(a=>`- \`${a}\``).join(`
900
987
  `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
901
988
  `))),{content:[{type:"text",text:o.join(`
902
- `)}]}}if(t==="status"){Fs.info({repoPath:e},"Checking git hooks status");let r=Wt(e),o=r.statuses["post-checkout"];return{content:[{type:"text",text:["# Git Hooks Status","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(c=>`- \`${c}\``).join(`
903
- `):"- None","",`## Missing (${r.missing.length})`,r.missing.length>0?r.missing.map(c=>`- \`${c}\``).join(`
904
- `):"- None","",`## Foreign (${r.foreign.length})`,r.foreign.length>0?r.foreign.map(c=>`- \`${c}\` (non-Liquid hook content)`).join(`
905
- `):"- None","",`## Disabled (${r.disabled.length})`,r.disabled.length>0?r.disabled.map(c=>`- \`${c}\` (not executable)`).join(`
989
+ `)}]}}if(t==="status"){ir.info({repoPath:e},"Checking git hooks status");let r=en(e),o=r.statuses["post-checkout"];return{content:[{type:"text",text:["# Git Hooks Status","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(l=>`- \`${l}\``).join(`
990
+ `):"- None","",`## Missing (${r.missing.length})`,r.missing.length>0?r.missing.map(l=>`- \`${l}\``).join(`
991
+ `):"- None","",`## Foreign (${r.foreign.length})`,r.foreign.length>0?r.foreign.map(l=>`- \`${l}\` (non-Liquid hook content)`).join(`
992
+ `):"- None","",`## Disabled (${r.disabled.length})`,r.disabled.length>0?r.disabled.map(l=>`- \`${l}\` (not executable)`).join(`
906
993
  `):"- None","","---",`**Post-checkout status**: \`${o}\``,o==="installed"?"**Branch-switch delta reindex**: active":"**Branch-switch delta reindex**: inactive",'**To install hooks**: Use `shadow_env_hooks({ action: "install" })`'].join(`
907
- `)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function za(s){let[e,t="."]=s;if(!e||!["install","uninstall","status"].includes(e)){console.log(""),console.log(` ${y.bold("Usage: ")} liquid-shadow hooks <install|uninstall|status> [path]`),console.log(""),console.log(` ${y.bold("Commands: ")}`),console.log(` ${y.cyan("install")} Install git hooks for automatic index refresh and symbol healing`),console.log(` ${y.cyan("uninstall")} Remove installed git hooks`),console.log(` ${y.cyan("status")} Check git hooks installation status`),console.log(""),console.log(` ${y.bold("Examples: ")}`),console.log(" liquid-shadow hooks install ."),console.log(" liquid-shadow hooks status /path/to/repo"),console.log("");return}await Y(async()=>{let n=Uc("path").resolve(t);switch(e){case"install":{let i=await Li({repoPath:n,action:"install",enableAutoRefresh:!0,enableSymbolHealing:!0});if(console.log(""),console.log(` ${y.green("\u2714")} ${y.bold("Git hooks installed successfully")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);console.log(` ${y.bold("Installed hooks: ")}`),r.hooks.forEach(o=>{console.log(` ${y.cyan("\u2022")} ${o}`)}),console.log("")}catch{console.log(i.content[0].text)}break}case"uninstall":{await Li({repoPath:n,action:"remove"}),console.log(""),console.log(` ${y.green("\u2714")} ${y.bold("Git hooks uninstalled successfully")}`),console.log("");break}case"status":{let i=await Li({repoPath:n,action:"status"});if(console.log(""),console.log(` ${y.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(` ${y.green("\u2714")} Installed hooks:`),r.installed.forEach(o=>{console.log(` ${y.cyan("\u2022")} ${o}`)})):console.log(` ${y.yellow("\u26A0")} No hooks installed`),r.missing&&r.missing.length>0&&(console.log(""),console.log(` ${y.dim("Missing hooks: ")}`),r.missing.forEach(o=>{console.log(` ${y.dim("\u2022")} ${o}`)}))}catch{console.log(i.content[0].text)}console.log("");break}}})}V();q();import Qu from"path";import Xu from"fs";var Ua=S.child({module:"mcp:tools:workspace:list"});async function ja(s){let{repoPaths:e,status:t,limit:n,summarize:i=!1}=s;Ua.info({repoCount:e.length,status:t,summarize:i},"Getting workspace missions");let r=[];for(let a of e)if(Xu.existsSync(a))try{let{missions:c}=O.getInstance(a),l=c.findAll(t);for(let p of l){let u=c.getLinks(p.id);r.push({...p,repo_path:a,repo_name:Qu.basename(a),cross_repo_links:u})}}catch(c){Ua.error({error:c,repoPath:a},"Failed to query repo missions")}if(r.sort((a,c)=>{let l=d=>d==="in-progress"?0:d==="verifying"?1:2,p=l(a.status),u=l(c.status);return p!==u?p-u:(a.created_at||0)-(c.created_at||0)}),i||r.length>50&&!n){let a=n||20,c=r.slice(0,a),l=r.reduce((u,d)=>(u[d.status]=(u[d.status]||0)+1,u),{}),p=r.reduce((u,d)=>(u[d.repo_name]=(u[d.repo_name]||0)+1,u),{});return{content:[{type:"text",text:JSON.stringify({summary:{total_missions:r.length,by_status:l,by_repo:p,showing_top:a},top_missions:c,hint:`Showing top ${a} of ${r.length} missions. Use limit to adjust or summarize:false for full list.`},null,2)}]}}let o=n?r.slice(0,n):r;return{content:[{type:"text",text:JSON.stringify({total_missions:r.length,showing:o.length,missions:o},null,2)}]}}V();q();var Zu=S.child({module:"mcp:tools:workspace:link"});async function Ba(s){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:i,relationship:r="related"}=s;Zu.info({parentRepoPath:e,childRepoPath:n},"Linking cross-repo missions");let{missions:o}=O.getInstance(e),{missions:a}=O.getInstance(n);try{let c=o.findById(t),l=a.findById(i);if(!c)throw new Error(`Parent mission ${t} not found`);if(!l)throw new Error(`Child mission ${i} not found`);return o.createLink(t,n,i,r,"parent"),a.createLink(i,e,t,r,"child"),{content:[{type:"text",text:JSON.stringify({status:"linked",relationship:r},null,2)}]}}catch(c){throw new Error(`Failed to link: ${c.message}`)}}q();import cd from"path";q();Ze();import ed from"better-sqlite3";import Qt from"path";import Ga from"fs";import td from"os";import nd from"crypto";var qa=S.child({module:"fusion-connection"}),$i=5,id=1,Va=["files","exports","imports","configs","schema_migrations"],Ws=3,Ai=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),qa.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=Qt.dirname(this.fusionDbPath);Ga.existsSync(t)||Ga.mkdirSync(t,{recursive:!0}),this.fusionDb=new ed(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=td.homedir(),n=Qt.join(t,".mcp-liquid-shadow","fused"),i=e.replace(/[^a-zA-Z0-9-_]/g,"_");return Qt.join(n,`${i}.db`)}initFusionSchema(){this.fusionDb.exec(`
994
+ `)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function Ec(s){let[e,t="."]=s;if(!e||!["install","uninstall","status"].includes(e)){console.log(""),console.log(` ${_.bold("Usage: ")} liquid-shadow hooks <install|uninstall|status> [path]`),console.log(""),console.log(` ${_.bold("Commands: ")}`),console.log(` ${_.cyan("install")} Install git hooks for automatic index refresh and symbol healing`),console.log(` ${_.cyan("uninstall")} Remove installed git hooks`),console.log(` ${_.cyan("status")} Check git hooks installation status`),console.log(""),console.log(` ${_.bold("Examples: ")}`),console.log(" liquid-shadow hooks install ."),console.log(" liquid-shadow hooks status /path/to/repo"),console.log("");return}await Z(async()=>{let n=bl("path").resolve(t);switch(e){case"install":{let i=await Vi({repoPath:n,action:"install",enableAutoRefresh:!0,enableSymbolHealing:!0});if(console.log(""),console.log(` ${_.green("\u2714")} ${_.bold("Git hooks installed successfully")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);console.log(` ${_.bold("Installed hooks: ")}`),r.hooks.forEach(o=>{console.log(` ${_.cyan("\u2022")} ${o}`)}),console.log("")}catch{console.log(i.content[0].text)}break}case"uninstall":{await Vi({repoPath:n,action:"remove"}),console.log(""),console.log(` ${_.green("\u2714")} ${_.bold("Git hooks uninstalled successfully")}`),console.log("");break}case"status":{let i=await Vi({repoPath:n,action:"status"});if(console.log(""),console.log(` ${_.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(` ${_.green("\u2714")} Installed hooks:`),r.installed.forEach(o=>{console.log(` ${_.cyan("\u2022")} ${o}`)})):console.log(` ${_.yellow("\u26A0")} No hooks installed`),r.missing&&r.missing.length>0&&(console.log(""),console.log(` ${_.dim("Missing hooks: ")}`),r.missing.forEach(o=>{console.log(` ${_.dim("\u2022")} ${o}`)}))}catch{console.log(i.content[0].text)}console.log("");break}}})}Y();G();import Nd from"path";import Pd from"fs";var Sc=x.child({module:"mcp:tools:workspace:list"});async function xc(s){let{repoPaths:e,status:t,limit:n,summarize:i=!1}=s;Sc.info({repoCount:e.length,status:t,summarize:i},"Getting workspace missions");let r=[];for(let a of e)if(Pd.existsSync(a))try{let{missions:l}=F.getInstance(a),c=l.findAll(t);for(let p of c){let u=l.getLinks(p.id);r.push({...p,repo_path:a,repo_name:Nd.basename(a),cross_repo_links:u})}}catch(l){Sc.error({error:l,repoPath:a},"Failed to query repo missions")}if(r.sort((a,l)=>{let c=m=>m==="in-progress"?0:m==="verifying"?1:m==="planned"?2:m==="suspended"?3:m==="completed"?4:5,p=c(a.status),u=c(l.status);if(p!==u)return p-u;let d=a.updated_at||a.created_at||0;return(l.updated_at||l.created_at||0)-d}),i||r.length>50&&!n){let a=n||20,l=r.slice(0,a),c=r.reduce((u,d)=>(u[d.status]=(u[d.status]||0)+1,u),{}),p=r.reduce((u,d)=>(u[d.repo_name]=(u[d.repo_name]||0)+1,u),{});return{content:[{type:"text",text:JSON.stringify({summary:{total_missions:r.length,by_status:c,by_repo:p,showing_top:a},top_missions:l,hint:`Showing top ${a} of ${r.length} missions. Use limit to adjust or summarize:false for full list.`},null,2)}]}}let o=n?r.slice(0,n):r;return{content:[{type:"text",text:JSON.stringify({total_missions:r.length,showing:o.length,missions:o},null,2)}]}}Y();G();var Dd=x.child({module:"mcp:tools:workspace:link"});async function wc(s){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:i,relationship:r="related"}=s;Dd.info({parentRepoPath:e,childRepoPath:n},"Linking cross-repo missions");let{missions:o}=F.getInstance(e),{missions:a}=F.getInstance(n);try{let l=o.findById(t),c=a.findById(i);if(!l)throw new Error(`Parent mission ${t} not found`);if(!c)throw new Error(`Child mission ${i} not found`);return o.createLink(t,n,i,r,"parent"),a.createLink(i,e,t,r,"child"),{content:[{type:"text",text:JSON.stringify({status:"linked",relationship:r},null,2)}]}}catch(l){return{content:[{type:"text",text:`Error: Failed to link: ${l.message}`}],isError:!0}}}G();import Gd from"path";G();dt();import Od from"better-sqlite3";import fn from"path";import vc from"fs";import Fd from"os";import Wd from"crypto";var Rc=x.child({module:"fusion-connection"}),Ji=5,Hd=1,Tc=["files","exports","imports","configs","schema_migrations"],sr=3,Yi=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),Rc.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=fn.dirname(this.fusionDbPath);vc.existsSync(t)||vc.mkdirSync(t,{recursive:!0}),this.fusionDb=new Od(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=Fd.homedir(),n=fn.join(t,".mcp-liquid-shadow","fused"),i=e.replace(/[^a-zA-Z0-9-_]/g,"_");return fn.join(n,`${i}.db`)}initFusionSchema(){this.fusionDb.exec(`
908
995
  CREATE TABLE IF NOT EXISTS fused_repos (
909
996
  alias TEXT PRIMARY KEY,
910
997
  repo_path TEXT NOT NULL UNIQUE,
@@ -938,20 +1025,20 @@ File: ${U.file}`,I=await E(T);if(I){let M=o.intentLogs.findSemanticMatches(I,3,c
938
1025
 
939
1026
  CREATE INDEX IF NOT EXISTS idx_virtual_edges_source ON virtual_edges(source_repo, source_file_path);
940
1027
  CREATE INDEX IF NOT EXISTS idx_virtual_edges_target ON virtual_edges(target_repo, target_file_path);
941
- `),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(id.toString())}attachRepo(e){let t=Qt.resolve(e);if(this.attachedRepos.has(t))return;if(!Xe(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=Te(t),i=n.name;this.validateSchemaCompatibility(n,t);let r=this.getSchemaVersion(n),o=this.generateAlias(t);for(let a=1;a<=Ws;a++)try{this.fusionDb.exec(`ATTACH DATABASE '${i}' AS ${o}`);let c={alias:o,repoPath:t,dbPath:i,schemaVersion:r,attached:!0};this.attachedRepos.set(t,c),this.fusionDb.prepare(`INSERT OR REPLACE INTO fused_repos (alias, repo_path, db_path, schema_version, attached_at, last_validated_at)
942
- VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(c){if(this.isLockContentionError(c)&&a<Ws){qa.warn({repoPath:t,attempt:a,maxAttempts:Ws},"Attach failed due to lock contention; retrying");continue}throw c}}checkHealth(){let e=[];for(let t of this.attachedRepos.values())try{this.fusionDb.prepare(`SELECT 1 FROM ${t.alias}.files LIMIT 1`).get(),e.push({alias:t.alias,repoPath:t.repoPath,accessible:!0})}catch(n){e.push({alias:t.alias,repoPath:t.repoPath,accessible:!1,error:n instanceof Error?n.message:String(n)})}return{healthy:e.every(t=>t.accessible),repos:e}}detachRepo(e){let t=Qt.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=Te(t.repoPath),i=Va.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=$i&&i.length===0,missingTables:i}});return{valid:e.every(t=>t.compatible),minVersion:$i,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=Qt.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=nd.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<$i)throw new Error(`Schema version mismatch for ${t}. Expected >= ${$i}, got ${n}.`);let i=Va.filter(r=>!this.checkTableExists(e,r));if(i.length>0)throw new Error(`Missing tables in ${t}: ${i.join(", ")}`)}checkTableExists(e,t){try{return!!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)}catch{return!1}}isLockContentionError(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("locked")||t.includes("busy")}get nameValue(){return this.name}get dbPath(){return this.fusionDbPath}};q();var yt=S.child({module:"edge-scanner"});function Hs(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function sd(s){if(!s)return null;try{let e=JSON.parse(s);return e.path||e.name||null}catch{return null}}function rd(s,e){let t=Hs(s),n=Hs(e);if(t===n)return!0;let i=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function od(s){yt.info("Starting HTTP gap detection scan");let e=s.getAttachedRepos();if(e.length<2)return yt.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
1028
+ `),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(Hd.toString())}attachRepo(e){let t=fn.resolve(e);if(this.attachedRepos.has(t))return;if(!ut(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=Oe(t),i=n.name;this.validateSchemaCompatibility(n,t);let r=this.getSchemaVersion(n),o=this.generateAlias(t);for(let a=1;a<=sr;a++)try{this.fusionDb.exec(`ATTACH DATABASE '${i}' AS ${o}`);let l={alias:o,repoPath:t,dbPath:i,schemaVersion:r,attached:!0};this.attachedRepos.set(t,l),this.fusionDb.prepare(`INSERT OR REPLACE INTO fused_repos (alias, repo_path, db_path, schema_version, attached_at, last_validated_at)
1029
+ VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(l){if(this.isLockContentionError(l)&&a<sr){Rc.warn({repoPath:t,attempt:a,maxAttempts:sr},"Attach failed due to lock contention; retrying");continue}throw l}}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=fn.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=Oe(t.repoPath),i=Tc.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=Ji&&i.length===0,missingTables:i}});return{valid:e.every(t=>t.compatible),minVersion:Ji,repos:e}}getAttachedRepos(){return Array.from(this.attachedRepos.values())}prepare(e){return this.fusionDb.prepare(e)}exec(e){this.fusionDb.exec(e)}close(){for(let e of this.attachedRepos.values())try{this.fusionDb.exec(`DETACH DATABASE ${e.alias}`)}catch{}this.attachedRepos.clear(),this.fusionDb.open&&this.fusionDb.close()}generateAlias(e){let t=fn.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=Wd.createHash("sha256").update(e).digest("hex").substring(0,6);return`repo_${t}_${n}`}getSchemaVersion(e){try{return e.prepare("SELECT MAX(version) as version FROM schema_migrations").get()?.version||0}catch{return 0}}validateSchemaCompatibility(e,t){let n=this.getSchemaVersion(e);if(n<Ji)throw new Error(`Schema version mismatch for ${t}. Expected >= ${Ji}, got ${n}.`);let i=Tc.filter(r=>!this.checkTableExists(e,r));if(i.length>0)throw new Error(`Missing tables in ${t}: ${i.join(", ")}`)}checkTableExists(e,t){try{return!!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)}catch{return!1}}isLockContentionError(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("locked")||t.includes("busy")}get nameValue(){return this.name}get dbPath(){return this.fusionDbPath}};G();var $t=x.child({module:"edge-scanner"});function rr(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function zd(s){if(!s)return null;try{let e=JSON.parse(s);return e.path||e.name||null}catch{return null}}function Bd(s,e){let t=rr(s),n=rr(e);if(t===n)return!0;let i=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function Ud(s){$t.info("Starting HTTP gap detection scan");let e=s.getAttachedRepos();if(e.length<2)return $t.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
943
1030
  SELECT id, name, file_path, capabilities
944
1031
  FROM ${r.alias}.exports
945
1032
  WHERE kind = 'HTTP Route'
946
- `,a=s.executeRawQuery(o);for(let c of a){let l=sd(c.capabilities)||c.name;l&&l.startsWith("/")&&t.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,symbolId:c.id,routePath:l})}}catch(o){yt.warn({repo:r.alias,error:o},"Failed to query backend routes")}yt.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
1033
+ `,a=s.executeRawQuery(o);for(let l of a){let c=zd(l.capabilities)||l.name;c&&c.startsWith("/")&&t.push({repo:r.alias,repoPath:r.repoPath,filePath:l.file_path,symbolId:l.id,routePath:c})}}catch(o){$t.warn({repo:r.alias,error:o},"Failed to query backend routes")}$t.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
947
1034
  SELECT file_path, name
948
1035
  FROM ${r.alias}.event_synapses
949
1036
  WHERE type = 'api_route' AND direction = 'produce'
950
- `,a=s.executeRawQuery(o);for(let c of a){let l=Hs(c.name);l&&l.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,routePath:l})}}catch(o){yt.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}yt.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&&rd(r.routePath,o.routePath))try{s.addVirtualEdge({sourceRepo:r.repoPath,sourceFilePath:r.filePath,targetRepo:o.repoPath,targetFilePath:o.filePath,targetSymbolId:o.symbolId,relationship:"api_call",metadata:{frontendPath:r.routePath,backendPath:o.routePath,method:o.method},confidence:1}),i++}catch(a){yt.debug({source:r.filePath,target:o.filePath,error:a},"Skipped duplicate edge")}return yt.info({edgesCreated:i,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),i}function Ja(s){let e=od(s);return{httpGaps:e,totalEdges:e}}q();var ad=S.child({module:"fusion-index-service"}),Pi=class{constructor(e){this.connection=e}executeFederatedQuery(e,...t){return this.connection.prepare(e).all(...t).map(r=>{let{_repo_alias:o,_repo_path:a,...c}=r;return{repo:o,repoPath:a,data:c}})}executeRawQuery(e,...t){return this.connection.prepare(e).all(...t)}buildAdvancedQuery(e){let t=this.connection.getAttachedRepos();if(t.length===0)throw new Error("No repositories attached");let{table:n,tableAlias:i,columns:r,joins:o,where:a,groupBy:c,having:l,orderBy:p,limit:u,offset:d}=e,h=i||n.charAt(0),m=r.join(", "),_=t.map(g=>{let b=`${g.alias}.${n} ${h}`,w="";o&&o.length>0&&(w=o.map(D=>{let U=D.alias||D.table.charAt(0);return`${D.type} JOIN ${g.alias}.${D.table} ${U} ON ${D.on}`}).join(`
951
- `));let x=a?`WHERE ${a}`:"",R=c&&c.length>0?`GROUP BY ${c.join(", ")}`:"",k=l?`HAVING ${l}`:"";return`SELECT '${g.alias}' as _repo_alias, '${g.repoPath}' as _repo_path, ${m} FROM ${b} ${w} ${x} ${R} ${k}`.trim()}).join(`
1037
+ `,a=s.executeRawQuery(o);for(let l of a){let c=rr(l.name);c&&c.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:l.file_path,routePath:c})}}catch(o){$t.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}$t.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&&Bd(r.routePath,o.routePath))try{s.addVirtualEdge({sourceRepo:r.repoPath,sourceFilePath:r.filePath,targetRepo:o.repoPath,targetFilePath:o.filePath,targetSymbolId:o.symbolId,relationship:"api_call",metadata:{frontendPath:r.routePath,backendPath:o.routePath,method:o.method},confidence:1}),i++}catch(a){$t.debug({source:r.filePath,target:o.filePath,error:a},"Skipped duplicate edge")}return $t.info({edgesCreated:i,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),i}function kc(s){let e=Ud(s);return{httpGaps:e,totalEdges:e}}G();var jd=x.child({module:"fusion-index-service"}),Ki=class{constructor(e){this.connection=e}executeFederatedQuery(e,...t){return this.connection.prepare(e).all(...t).map(r=>{let{_repo_alias:o,_repo_path:a,...l}=r;return{repo:o,repoPath:a,data:l}})}executeRawQuery(e,...t){return this.connection.prepare(e).all(...t)}buildAdvancedQuery(e){let t=this.connection.getAttachedRepos();if(t.length===0)throw new Error("No repositories attached");let{table:n,tableAlias:i,columns:r,joins:o,where:a,groupBy:l,having:c,orderBy:p,limit:u,offset:d}=e,h=i||n.charAt(0),m=r.join(", "),b=t.map(g=>{let y=`${g.alias}.${n} ${h}`,E="";o&&o.length>0&&(E=o.map(N=>{let U=N.alias||N.table.charAt(0);return`${N.type} JOIN ${g.alias}.${N.table} ${U} ON ${N.on}`}).join(`
1038
+ `));let k=a?`WHERE ${a}`:"",R=l&&l.length>0?`GROUP BY ${l.join(", ")}`:"",w=c?`HAVING ${c}`:"";return`SELECT '${g.alias}' as _repo_alias, '${g.repoPath}' as _repo_path, ${m} FROM ${y} ${E} ${k} ${R} ${w}`.trim()}).join(`
952
1039
  UNION ALL
953
- `);return p&&(_=`SELECT * FROM (${_}) AS federated_results ORDER BY ${p}`),u!==void 0&&(_+=` LIMIT ${u}`),d!==void 0&&(_+=` OFFSET ${d}`),_}buildFtsQuery(e,t,n,i,r=50){let o=this.connection.getAttachedRepos();if(o.length===0)throw new Error("No repositories attached");let a=n.replace(/"/g,'""'),c=i.map(p=>`c.${p}`).join(", ");return`${o.map(p=>`
954
- SELECT '${p.alias}' as _repo_alias, '${p.repoPath}' as _repo_path, ${c}, bm25(${p.alias}.${e}) as _fts_rank
1040
+ `);return p&&(b=`SELECT * FROM (${b}) AS federated_results ORDER BY ${p}`),u!==void 0&&(b+=` LIMIT ${u}`),d!==void 0&&(b+=` OFFSET ${d}`),b}buildFtsQuery(e,t,n,i,r=50){let o=this.connection.getAttachedRepos();if(o.length===0)throw new Error("No repositories attached");let a=n.replace(/"/g,'""'),l=i.map(p=>`c.${p}`).join(", ");return`${o.map(p=>`
1041
+ SELECT '${p.alias}' as _repo_alias, '${p.repoPath}' as _repo_path, ${l}, bm25(${p.alias}.${e}) as _fts_rank
955
1042
  FROM ${p.alias}.${e} fts
956
1043
  JOIN ${p.alias}.${t} c ON fts.rowid = c.id
957
1044
  WHERE ${p.alias}.${e} MATCH '"${a}"'`).join(`
@@ -972,30 +1059,30 @@ WHERE i.resolved_path IS NOT NULL`);return t.join(`
972
1059
  INSERT INTO virtual_edges
973
1060
  (source_repo, source_file_path, source_symbol_id, target_repo, target_file_path, target_symbol_id, relationship, metadata, confidence, updated_at)
974
1061
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
975
- `).run(e.sourceRepo,e.sourceFilePath,e.sourceSymbolId||null,e.targetRepo,e.targetFilePath,e.targetSymbolId||null,e.relationship,e.metadata?JSON.stringify(e.metadata):null,e.confidence??1).lastInsertRowid}scanEdges(){return ad.info({name:this.connection.nameValue},"Starting edge scan"),Ja(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var Ya=S.child({module:"fused-index"}),Us=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Ai(e),this.service=new Pi(this.connection)}attachRepo(e){this.connection.attachRepo(e)}detachRepo(e){this.connection.detachRepo(e)}refreshRepo(e){this.connection.refreshRepo(e)}getAttachedRepos(){return this.connection.getAttachedRepos()}checkHealth(){return this.connection.checkHealth()}close(){this.connection.close(),Ya.info({name:this.configName},"Fused index closed")}getStatus(){let e=this.service.executeRawQuery("SELECT COUNT(*) as count FROM virtual_edges");return{name:this.connection.nameValue,path:this.connection.dbPath,attachedRepos:this.connection.getAttachedRepos().length,repos:this.connection.getAttachedRepos(),virtualEdgesCount:e[0]?.count||0}}searchExports(e,t=50){return this.service.searchExports(e,t)}searchFiles(e,t=50){return this.service.searchFiles(e,t)}getVirtualEdges(e,t){return this.service.getVirtualEdges(e,t)}addVirtualEdge(e){return this.service.addVirtualEdge(e)}scanEdges(){return this.service.scanEdges()}buildUnionQuery(e,t,n){return this.service.buildUnionQuery(e,t,n)}executeFederatedQuery(e,...t){return this.service.executeFederatedQuery(e,...t)}executeRawQuery(e,...t){return this.service.executeRawQuery(e,...t)}buildAdvancedQuery(e){return this.service.buildAdvancedQuery(e)}buildFtsQuery(e,t,n,i,r){return this.service.buildFtsQuery(e,t,n,i,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return Ya.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},zs=new Map;function Ka(s){let e=zs.get(s.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),i=new Set(s.repoPaths.map(o=>cd.resolve(o)));if(n.size===i.size&&[...n].every(o=>i.has(o)))return e;e.close(),zs.delete(s.name)}let t=new Us(s);return zs.set(s.name,t),t}q();var ld=S.child({module:"mcp:tools:workspace:fuse"});async function Qa(s){let{repoPaths:e,name:t}=s;ld.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=Ka({repoPaths:e,name:t||`workspace-${Date.now()}`});return{content:[{type:"text",text:JSON.stringify({message:"Fused index created",status:n.getStatus()},null,2)}]}}catch(n){throw new Error(`Failed to fuse: ${n.message}`)}}import Mi from"path";async function Xa(s){let[e,...t]=s;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${y.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${y.bold("Commands: ")}`),console.log(` ${y.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${y.cyan("link")} <args...> Link missions across repositories`),console.log(` ${y.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${y.bold("Examples: ")}`),console.log(" liquid-shadow workspace missions /frontend /backend"),console.log(" liquid-shadow workspace link /frontend 5 /backend 12"),console.log(" liquid-shadow workspace fuse /frontend /backend --name my-app"),console.log("");return}await Y(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${y.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>Mi.resolve(r)),i=await ja({repoPaths:n});if(console.log(""),console.log(` ${y.bold("Workspace Missions")}`),console.log(""),i.content&&i.content[0]){let r=JSON.parse(i.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${y.cyan("\u2022")} ${y.bold(o.name)} (ID: ${o.id})`),console.log(` ${y.dim("Repo: ")} ${o.repo_path}`),console.log(` ${y.dim("Status: ")} ${o.status}`),console.log(` ${y.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${y.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${y.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${y.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,i,r,o,a]=t;await Ba({parentRepoPath:Mi.resolve(n),parentMissionId:parseInt(i,10),childRepoPath:Mi.resolve(r),childMissionId:parseInt(o,10),relationship:a}),console.log(""),console.log(` ${y.green("\u2714")} ${y.bold("Missions linked successfully")}`),console.log(` ${y.dim("Parent: ")} ${n} (Mission ${i})`),console.log(` ${y.dim("Child: ")} ${r} (Mission ${o})`),a&&console.log(` ${y.dim("Relationship: ")} ${a}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${y.red("\u2716")} Please provide at least one repository path`);return}let n,i=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):i.push(Mi.resolve(t[o]));let r=await Qa({repoPaths:i,name:n});if(console.log(""),console.log(` ${y.green("\u2714")} ${y.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${y.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${y.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${y.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${y.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}q();q();var pd=S.child({module:"strategy-normalizer"}),Ie=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(i){return pd.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:this.normalizeSteps(t)}}static normalizeSteps(e){return Array.isArray(e)?e.map((t,n)=>typeof t=="string"?{id:`step-${n}`,description:t,status:"pending"}:typeof t=="object"&&t!==null?{id:t.id||`step-${n}`,description:t.description||t.content||t.name||`Step ${n+1}`,status:t.status||"pending",dependencies:t.dependencies||t.deps,verification:t.verification,...t}:{id:`step-${n}`,description:String(t),status:"pending"}):e.steps&&Array.isArray(e.steps)?this.normalizeSteps(e.steps):typeof e=="object"?Object.entries(e).map(([t,n],i)=>typeof n=="string"?{id:t,description:n,status:"pending"}:typeof n=="object"&&n!==null?{id:t,description:n.description||n.content||n.name||t,status:n.status||"pending",dependencies:n.dependencies||n.deps,verification:n.verification,...n}:{id:t||`step-${i}`,description:String(n),status:"pending"}):[]}static stringify(e){return JSON.stringify(e,null,2)}static validate(e){let t=[];if(!e)return{valid:!0,errors:[]};try{let n=this.normalize(e),i=new Set;for(let r of n.steps)if(i.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),i.add(r.id),r.dependencies)for(let o of r.dependencies)i.has(o)||t.push(`Step "${r.id}" depends on non-existent step "${o}"`);return{valid:t.length===0,errors:t}}catch(n){return t.push(`Strategy validation failed: ${n instanceof Error?n.message:String(n)}`),{valid:!1,errors:t}}}};q();import js from"fs";import Za from"path";import ud from"os";var dd=[{id:"step-0",description:"Analyze impact: identify dependents and call sites",status:"pending"},{id:"step-1",description:"Implement refactor and update call sites",status:"pending"},{id:"step-2",description:"Run tests and verify behavior; update docs if needed",status:"pending"}],md=[{id:"step-0",description:"Capture requirements and acceptance criteria",status:"pending"},{id:"step-1",description:"Implement feature with tests",status:"pending"},{id:"step-2",description:"Integrate and verify end-to-end",status:"pending"}],hd=[{id:"step-0",description:"Reproduce the bug and document steps",status:"pending"},{id:"step-1",description:"Diagnose root cause and plan fix",status:"pending"},{id:"step-2",description:"Apply fix and add/update regression test",status:"pending"},{id:"step-3",description:"Verify fix and run full test suite",status:"pending"}],ec=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:dd},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:md},{id:"bug-fix",name:"Bug fix",description:"Reproduction \u2192 diagnosis \u2192 fix \u2192 regression test",defaultGoal:"Fix {{target}}: reproduce, diagnose, fix, and add regression test.",steps:hd}],Bs=new Map(ec.map(s=>[s.id,s])),Ni=!1;function fd(){if(Ni)return;let s=Za.join(ud.homedir(),".shadow","templates");if(!js.existsSync(s)){S.debug({templatesDir:s},"Custom templates directory does not exist"),Ni=!0;return}try{let e=js.readdirSync(s).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=Za.join(s,t),i=js.readFileSync(n,"utf8"),r=JSON.parse(i);if(!r.id||!r.name||!r.defaultGoal||!r.steps){S.warn({file:t,template:r},"Invalid custom template structure - skipping");continue}if(!Array.isArray(r.steps)||r.steps.length===0){S.warn({file:t},"Template has no steps - skipping");continue}if(ec.some(o=>o.id===r.id)){S.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}Bs.set(r.id,r),S.info({file:t,templateId:r.id},"Loaded custom template")}catch(n){S.warn({file:t,error:n},"Failed to load custom template")}Ni=!0}catch(e){S.warn({error:e,templatesDir:s},"Failed to read custom templates directory"),Ni=!0}}function gd(s){return fd(),Bs.get(s)}function yd(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function tc(s,e,t={}){let n=gd(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(Bs.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=yd(n.defaultGoal,{...t,target:i}),a=Ie.normalize({steps:n.steps}),c=Ie.stringify(a);return{name:r,goal:o,strategy:c}}V();gn();var En=S.child({module:"mcp:tools:ops:plan"}),bd=["name","goal","strategy","parentId","outcomeContract"],_d="Mission update requires at least one updatable field: name, goal, strategy, parentId, outcomeContract.",Ed="Mission requires name and goal (or templateId with optional templateVars).";async function nc(s){let{repoPath:e,name:t,goal:n,strategy:i,missionId:r,parentId:o,outcomeContract:a,templateId:c,templateVars:l}=s,{missions:p}=O.getInstance(e),u=me(e),d=De(e);En.info({repoPath:e,name:t,missionId:r,templateId:c},"Planning mission");try{let h=t,m=n,f=i;if(!r&&c){let b=tc(c,t,l||{});h=h??b.name,m=m??b.goal,f=f??b.strategy}let _,g;if(r){let b=p.findById(r);if(!b)throw new Error(`Mission ${r} not found.`);let w;if(i!==void 0)if(i){let R=Ie.normalize(i);w=Ie.stringify(R);let k=Ie.validate(w);k.valid||En.warn({errors:k.errors,strategy:i},"Strategy validation warnings detected")}else w=null;let x={commit_sha:d};if(t!==void 0&&(x.name=t),n!==void 0&&(x.goal=n),w!==void 0&&(x.strategy_graph=w),o!==void 0&&(x.parent_id=o),a!==void 0&&(x.outcome_contract=a),Object.keys(x).length===1)throw new Error(_d);p.update(r,{...x}),_=r,g=`Mission "${t??b.name}" updated.`}else{if(!h||!m)throw new Error(Ed);let b=null;if(f){let w=Ie.normalize(f);b=Ie.stringify(w);let x=Ie.validate(b);x.valid||En.warn({errors:x.errors,strategy:f},"Strategy validation warnings detected")}_=p.create({name:h,goal:m,strategy_graph:b,status:"planned",git_branch:u,commit_sha:d,parent_id:o||null,verification_context:null,outcome_contract:a||null}),g=`Mission "${h}" planned.`}try{await new Fe(e).syncMissionToGitNotes(Number(_))}catch(b){En.info({missionId:_,...ye(b)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:_,status:"planned",message:g,strategy_saved:!!f,contract_saved:!!a,updateable_fields:bd,from_template:c??void 0,commit:d},null,2)}]}}catch(h){let m=At(h);throw En.error({repoPath:e,...ye(h)},"Failed to plan mission"),new Error(`Failed to plan mission: ${m}`)}}q();V();var Di=class s{constructor(e){this.intentLogs=e}static RECENCY_HALF_LIFE_HOURS=48;static WEIGHTS={recency:.4,activity:.3,statusBoost:.2,blockerBoost:.1};score(e){if(e.length===0)return[];let t=Math.floor(Date.now()/1e3),n=e.map(c=>c.id),i=this.intentLogs.countByMissions(n),r=this.intentLogs.findMissionsWithBlockers(n),o=Math.max(1,...Object.values(i));return e.map(c=>{let l=this.computeRecency(c.updated_at,t),p=(i[c.id]||0)/o,u=this.computeStatusBoost(c.status),d=r.has(c.id)?1:0,h=s.WEIGHTS,m=l*h.recency+p*h.activity+u*h.statusBoost+d*h.blockerBoost;return{mission:c,score:Math.round(m*1e3)/1e3,breakdown:{recency:Math.round(l*1e3)/1e3,activity:Math.round(p*1e3)/1e3,blockerBoost:d,statusBoost:u}}}).sort((c,l)=>l.score-c.score)}computeRecency(e,t){let n=Math.max(0,(t-e)/3600);return Math.pow(.5,n/s.RECENCY_HALF_LIFE_HOURS)}computeStatusBoost(e){switch(e){case"in-progress":return 1;case"verifying":return .8;case"planned":return .4;default:return 0}}};V();q();var Sd=S.child({module:"collision-service"}),Oi=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=me(this.repoPath);if(!e)return[];let{missions:t,intentLogs:n}=O.getInstance(this.repoPath),i=t.findActive().filter(a=>a.git_branch&&a.git_branch!==e),r=[],o=new Set;for(let a of i){let c=a.git_branch;if(o.has(c))continue;o.add(c),Sd.info({branch:c,currentBranch:e},"Checking predictive collisions"),wo(this.repoPath,e,c)&&r.push({branch:c,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${c}'.`});let p=t.findActive(e),u=new Set;for(let m of p)t.getWorkingSet(m.id).forEach(f=>u.add(f.file_path));let h=t.getWorkingSet(a.id).filter(m=>u.has(m.file_path));h.length>0&&r.push({branch:c,type:"intent",description:`Logical conflict: Mission '${a.name}' on '${c}' is modifying files you are currently working on.`,conflictingFiles:h.map(m=>m.file_path)})}return r}};var Fi=class{constructor(e){this.repoPath=e}async getBriefing(e={}){let{missionId:t,scope:n="mission",altitude:i,activeMissionsLimit:r,recentActivityLimit:o,compact:a}=e,c=a??(i==="orbit"||i==="atmosphere"),l=o??(i==="orbit"?0:i==="ground"?20:10),{missions:p,intentLogs:u}=O.getInstance(this.repoPath),d=De(this.repoPath),h=me(this.repoPath);return n==="project"?this.getProjectBriefing({altitude:i,activeMissionsLimit:r,recentActivityLimit:l,compact:c,currentBranch:h,currentCommit:d}):this.getMissionBriefing({missionId:t,altitude:i,recentActivityLimit:l,currentBranch:h,currentCommit:d})}async getProjectBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i}=O.getInstance(t),{altitude:r,activeMissionsLimit:o,recentActivityLimit:a,compact:c,currentBranch:l,currentCommit:p}=e,u=n.findActive(l||void 0),d=u.length;o&&u.length>o&&(u=u.slice(0,o));let h=n.findParentOnlyIds(u),m=new Set(h),f=u.filter(N=>!m.has(N.id)),g=new Di(i).score(f),b=.15,w=3,x=c&&g.length>w?g.filter((N,$)=>$<w||N.score>=b):g,R=x.map(N=>N.mission),k=new Map(x.map(N=>[N.mission.id,N.score])),D=N=>({id:N.id,name:N.name,goal:N.goal,status:N.status,relevance:k.get(N.id)});if(r==="orbit")return{scope:"project",altitude:"orbit",counts:n.getStats(),next_work_candidates:R.map(D),meta:{current_branch:l,activeMissionsTotal:d,ember:this.getEmberLabel(t)}};let U={},P=[];for(let N of u)N.parent_id!=null?(U[N.parent_id]||(U[N.parent_id]=[]),U[N.parent_id].push(N)):P.push(N);let E=n.findRecentCompleted(5).map(D),T=a>0?i.findRecentDecisionActivity(a):void 0,I=h.map(N=>{let $=u.find(L=>L.id===N);return{parent:c?{...$,strategy_graph:void 0,verification_context:void 0}:$,children:U[N]??[]}}),M=P.filter(N=>!m.has(N.id));return{scope:"project",altitude:r||"atmosphere",counts:n.getStats(),analytics:n.getAnalytics(),hierarchy:I.length>0?I:void 0,standalone_active:M.length>0?M:void 0,active_missions:I.length===0?c?u.map(N=>({...N,strategy_graph:void 0})):u:void 0,next_work_candidates:R.map(D),recent_completed:E,recent_activity:T,meta:{current_branch:l,current_commit:p,activeMissionsTotal:d,active_limit_applied:!!o,relevance_filtered:x.length<g.length?{shown:x.length,total:g.length}:void 0,ember:this.getEmberLabel(t)}}}getEmberLabel(e){try{let{status:t,progress:n}=yi(e);if(t==="idle")return;if(t==="done")return"symbols: fully embedded";let[i,r]=n.split("/").map(Number),o=r>0?Math.round(i/r*100):0;return t==="running"?`symbols: warming ${n} (${o}%)`:`symbols: ${t} ${n}`}catch{return}}async getMissionBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i}=O.getInstance(t),{missionId:r,altitude:o,recentActivityLimit:a,currentBranch:c,currentCommit:l}=e,p;if(r?p=n.findById(r):p=n.findActive(c||void 0)[0],!p)return null;let u=null;try{p.strategy_graph&&(u=JSON.parse(p.strategy_graph))}catch{}if(o==="orbit")return{altitude:"orbit",mission:{id:p.id,name:p.name,goal:p.goal,status:p.status,last_updated:new Date(p.updated_at*1e3).toISOString()},strategy_snapshot:u};let d="No external shadow changes detected.";try{new qt(t).analyzeGhostChanges(p.commit_sha||void 0),d="Shadow Trace completed: Checked for external modifications."}catch{}let h={repaired:0,failed:0};try{h=new qe(t).detectAndRepairShifts()}catch{}let m=n.getHandoffs(p.id).map(_=>{let g=null;try{g=JSON.parse(_.metadata??"")}catch{}return{artifactId:_.id,kind:_.identifier,confidence:g?.confidence??null,findingsCount:g?.findings?.length??0,risksCount:g?.risks?.length??0,missionsCreated:g?.missionsCreated??[],createdAt:_.created_at}}),f={altitude:o||"atmosphere",mission:{id:p.id,name:p.name,goal:p.goal,status:p.status,last_updated:new Date(p.updated_at*1e3).toISOString(),git_branch:p.git_branch,commit_sha:p.commit_sha,outcome_contract:p.outcome_contract},artifacts:n.getArtifacts(p.id),handoffs:m,shadow_trace:{ghost_analysis:d,symbols_repaired:h.repaired,symbols_missing:h.failed},context:{current_commit:l,working_set:n.getWorkingSet(p.id).map(_=>_.file_path)},strategy_snapshot:u,recent_activity:o==="ground"?i.findByMission(p.id,a||20):i.findByMissionPreferCrystal(p.id,15),ancestor_activity_summary:[],predictive_collisions:[]};try{let _=new Oi(t);f.predictive_collisions=await _.analyzePotentialCollisions()}catch{}if(p.parent_id){let _=o==="ground"?i.findByMission(p.parent_id,5):i.findByMissionPreferCrystal(p.parent_id,3);f.ancestor_activity_summary=_.map(g=>({type:g.type,content:g.content,date:new Date(g.created_at*1e3).toISOString()}))}return f}};var ic=S.child({module:"mcp:tools:ops:briefing"});async function sc(s){let{repoPath:e,scope:t="mission"}=s;ic.info({repoPath:e,missionId:s.missionId,scope:t},"Generating briefing");try{let i=await new Fi(e).getBriefing(s);if(!i&&t==="mission")return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let r;if(t==="project"){let o=i.counts;r=i.next_work_candidates.length===0&&o.active===0?{tool:"shadow_ops_plan",reason:"No open work; create a mission"}:{tool:"shadow_ops_track",reason:"Select a mission from hierarchy or next_work_candidates to execute"}}return{content:[{type:"text",text:JSON.stringify(i,null,2)}],suggestedNext:r}}catch(n){throw ic.error({error:n,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${n instanceof Error?n.message:String(n)}`)}}q();V();V();q();q();var wd=S.child({module:"reasoning-engine"}),Wi=class{analyze(e){wd.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[],sourceMissions:[]};for(let i of e){let r=i.content.toLowerCase(),o=this.matchesContext(r,i.type),a=this.matchesDecision(r,i.type),c=this.matchesConsequence(r,i.type),l=this.matchesRecommendation(r,i.type);o?t.context.push(i.content):a?t.decisions.push(i.content):l?t.recommendations.push(i.content):c?t.consequences.push(i.content):i.type==="decision"?t.decisions.push(i.content):i.type==="discovery"||i.type==="fix"?t.consequences.push(i.content):t.unclassified.push(i.content)}let n=new Set;for(let i of e)i.mission_id!=null&&n.add(i.mission_id);return t.sourceMissions=[...n],t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(i=>e.includes(i))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(i=>e.includes(i))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(i=>e.includes(i))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(i=>e.includes(i))}};var Hi=S.child({module:"briefing-engine"}),tt=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=O.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Wi,this.persistencePivot=new Fe(e)}async distillMission(e,t=!0){Hi.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.gatherConsolidatedLogs(e);if(n.length===0)return{missionId:e,adr:"No intent logs found for this mission.",metrics:{totalLogs:0,symbolCount:0}};let i=this.reasoningEngine.analyze(n),r=new Set(n.map(a=>a.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
976
-
977
- `;if(o+=`## Summary of Intent
978
- `,o+=`Collected ${n.length} intent events across ${r.size} symbols.
979
-
980
- `,i.context.length>0&&(o+=`### Context
981
- `,i.context.forEach(a=>{o+=`- ${a}
982
- `}),o+=`
983
- `),i.decisions.length>0&&(o+=`### Key Decisions
984
- `,i.decisions.forEach(a=>{o+=`- ${a}
985
- `}),o+=`
986
- `),i.consequences.length>0&&(o+=`### Consequences & Evolutions
987
- `,i.consequences.forEach(a=>{o+=`- ${a}
988
- `}),o+=`
989
- `),i.recommendations.length>0&&(o+=`### Strategic Recommendations
990
- `,i.recommendations.forEach(a=>{o+=`- ${a}
991
- `}),o+=`
992
- `),i.unclassified.length>0&&(o+=`### Additional Notes
993
- `,i.unclassified.forEach(a=>{o+=`- ${a}
994
- `}),o+=`
995
- `),o+=`
1062
+ `).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 jd.info({name:this.connection.nameValue},"Starting edge scan"),kc(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var Cc=x.child({module:"fused-index"}),ar=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Yi(e),this.service=new Ki(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(),Cc.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 Cc.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},or=new Map;function Ic(s){let e=or.get(s.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),i=new Set(s.repoPaths.map(o=>Gd.resolve(o)));if(n.size===i.size&&[...n].every(o=>i.has(o)))return e;e.close(),or.delete(s.name)}let t=new ar(s);return or.set(s.name,t),t}G();var qd=x.child({module:"mcp:tools:workspace:fuse"});async function Lc(s){let{repoPaths:e,name:t}=s;qd.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=Ic({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 Qi from"path";async function Mc(s){let[e,...t]=s;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${_.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${_.bold("Commands: ")}`),console.log(` ${_.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${_.cyan("link")} <args...> Link missions across repositories`),console.log(` ${_.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${_.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 Z(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${_.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>Qi.resolve(r)),i=await xc({repoPaths:n});if(console.log(""),console.log(` ${_.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(` ${_.cyan("\u2022")} ${_.bold(o.name)} (ID: ${o.id})`),console.log(` ${_.dim("Repo: ")} ${o.repo_path}`),console.log(` ${_.dim("Status: ")} ${o.status}`),console.log(` ${_.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${_.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${_.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${_.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,i,r,o,a]=t;await wc({parentRepoPath:Qi.resolve(n),parentMissionId:parseInt(i,10),childRepoPath:Qi.resolve(r),childMissionId:parseInt(o,10),relationship:a}),console.log(""),console.log(` ${_.green("\u2714")} ${_.bold("Missions linked successfully")}`),console.log(` ${_.dim("Parent: ")} ${n} (Mission ${i})`),console.log(` ${_.dim("Child: ")} ${r} (Mission ${o})`),a&&console.log(` ${_.dim("Relationship: ")} ${a}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${_.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(Qi.resolve(t[o]));let r=await Lc({repoPaths:i,name:n});if(console.log(""),console.log(` ${_.green("\u2714")} ${_.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${_.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${_.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${_.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${_.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}G();G();var Zi=x.child({module:"strategy-normalizer"}),ze=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(i){return Zi.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:this.normalizeSteps(t)}}static normalizeSteps(e){return Array.isArray(e)?e.map((t,n)=>{if(typeof t=="string")return{id:`step-${n}`,description:t,status:"pending"};if(typeof t=="object"&&t!==null){let{verification:i,...r}=t,o=this.sanitizeVerification(i);return{...r,id:t.id||`step-${n}`,description:t.description||t.content||t.name||`Step ${n+1}`,status:t.status||"pending",dependencies:t.dependencies||t.deps,...o!==void 0?{verification:o}:{}}}return{id:`step-${n}`,description:String(t),status:"pending"}}):e.steps&&Array.isArray(e.steps)?this.normalizeSteps(e.steps):typeof e=="object"?Object.entries(e).map(([t,n],i)=>{if(typeof n=="string")return{id:t,description:n,status:"pending"};if(typeof n=="object"&&n!==null){let{verification:r,...o}=n,a=this.sanitizeVerification(r);return{...o,id:t,description:n.description||n.content||n.name||t,status:n.status||"pending",dependencies:n.dependencies||n.deps,...a!==void 0?{verification:a}:{}}}return{id:t||`step-${i}`,description:String(n),status:"pending"}}):[]}static looksLikeNaturalLanguage(e){return e.trim().split(/\s+/).length>=5}static VALID_VERIFICATION_TYPES=new Set(["usage","import","pattern"]);static sanitizeVerificationRule(e){if(!e)return null;if(typeof e=="string")return this.looksLikeNaturalLanguage(e)?(Zi.warn({verification:e},"Stripping natural-language verification rule (not a valid pattern)"),null):{type:"pattern",target:e};if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.target!="string"||!t.target)return Zi.warn({verification:e},"Stripping verification rule without target"),null;if(this.looksLikeNaturalLanguage(t.target))return Zi.warn({verification:e},"Stripping natural-language verification target (not a valid pattern)"),null;let i={type:typeof t.type=="string"&&this.VALID_VERIFICATION_TYPES.has(t.type)?t.type:"pattern",target:t.target};return typeof t.context=="string"&&(i.context=t.context),typeof t.filePath=="string"&&(i.filePath=t.filePath),i}static sanitizeVerification(e){if(e!=null){if(Array.isArray(e)){let t=e.map(n=>this.sanitizeVerificationRule(n)).filter(Boolean);return t.length>0?t.length===1?t[0]:t:void 0}return this.sanitizeVerificationRule(e)??void 0}}static stringify(e){return JSON.stringify(e,null,2)}static validate(e){let t=[];if(!e)return{valid:!0,errors:[]};try{let n=this.normalize(e),i=new Set;for(let r of n.steps)if(i.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),i.add(r.id),r.dependencies)for(let o of r.dependencies)i.has(o)||t.push(`Step "${r.id}" depends on non-existent step "${o}"`);return{valid:t.length===0,errors:t}}catch(n){return t.push(`Strategy validation failed: ${n instanceof Error?n.message:String(n)}`),{valid:!1,errors:t}}}};G();import cr from"fs";import $c from"path";import Vd from"os";var Jd=[{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"}],Yd=[{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"}],Kd=[{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"}],Ac=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:Jd},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:Yd},{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:Kd}],lr=new Map(Ac.map(s=>[s.id,s])),Xi=!1;function Qd(){if(Xi)return;let s=$c.join(Vd.homedir(),".shadow","templates");if(!cr.existsSync(s)){x.debug({templatesDir:s},"Custom templates directory does not exist"),Xi=!0;return}try{let e=cr.readdirSync(s).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=$c.join(s,t),i=cr.readFileSync(n,"utf8"),r=JSON.parse(i);if(!r.id||!r.name||!r.defaultGoal||!r.steps){x.warn({file:t,template:r},"Invalid custom template structure - skipping");continue}if(!Array.isArray(r.steps)||r.steps.length===0){x.warn({file:t},"Template has no steps - skipping");continue}if(Ac.some(o=>o.id===r.id)){x.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}lr.set(r.id,r),x.info({file:t,templateId:r.id},"Loaded custom template")}catch(n){x.warn({file:t,error:n},"Failed to load custom template")}Xi=!0}catch(e){x.warn({error:e,templatesDir:s},"Failed to read custom templates directory"),Xi=!0}}function Zd(s){return Qd(),lr.get(s)}function Xd(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function Nc(s,e,t={}){let n=Zd(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(lr.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=Xd(n.defaultGoal,{...t,target:i}),a=ze.normalize({steps:n.steps}),l=ze.stringify(a);return{name:r,goal:o,strategy:l}}Y();In();import Pc from"node:path";var Nn=x.child({module:"mcp:tools:ops:plan"}),em=["name","goal","strategy","parentId","outcomeContract"],tm="Mission update requires at least one updatable field: name, goal, strategy, parentId, outcomeContract.",nm="Mission requires name and goal (or templateId with optional templateVars).";async function Dc(s){let{repoPath:e,name:t,goal:n,strategy:i,workingSet:r,missionId:o,parentId:a,outcomeContract:l,templateId:c,templateVars:p}=s,{missions:u}=F.getInstance(e),d=be(e),h=Ze(e);Nn.info({repoPath:e,name:t,missionId:o,templateId:c},"Planning mission");try{let m=t,f=n,b=i;if(!o&&c){let R=Nc(c,t,p||{});m=m??R.name,f=f??R.goal,b=b??R.strategy}let g,y,E,k;if(o){let R=u.findById(o);if(!R)throw new Error(`Mission ${o} not found.`);let w;if(i!==void 0)if(i){let U=ze.normalize(i);w=ze.stringify(U);let H=ze.validate(w);H.valid||Nn.warn({errors:H.errors,strategy:i},"Strategy validation warnings detected")}else w=null;let N={commit_sha:h};if(t!==void 0&&(N.name=t),n!==void 0&&(N.goal=n),w!==void 0&&(N.strategy_graph=w),a!==void 0&&(N.parent_id=a),l!==void 0&&(N.outcome_contract=l),Object.keys(N).length===1)throw new Error(tm);u.update(o,{...N}),g=o,y=`Mission "${t??R.name}" updated.`,E=R.status,k="updated"}else{if(!m||!f)throw new Error(nm);let R=null;if(b){let w=ze.normalize(b);R=ze.stringify(w);let N=ze.validate(R);N.valid||Nn.warn({errors:N.errors,strategy:b},"Strategy validation warnings detected")}if(g=u.create({name:m,goal:f,strategy_graph:R,status:"planned",git_branch:d,commit_sha:h,parent_id:a||null,verification_context:null,outcome_contract:l||null}),r&&r.length>0){u.clearWorkingSet(Number(g));for(let w of r){let N=Pc.isAbsolute(w)?w:Pc.join(e,w);u.addToWorkingSet(Number(g),N,"planned")}}y=`Mission "${m}" planned.`,E="planned",k="created"}try{await new et(e).syncMissionToGitNotes(Number(g))}catch(R){Nn.info({missionId:g,...Re(R)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:g,status:E,operation:k,message:y,strategy_saved:!!b,working_set_populated:r?.length||0,working_set_seeded:r?.length||0,contract_saved:!!l,updateable_fields:em,from_template:c??void 0,commit:h},null,2)}]}}catch(m){let f=qt(m);throw Nn.error({repoPath:e,...Re(m)},"Failed to plan mission"),new Error(`Failed to plan mission: ${f}`)}}G();Y();var es=class s{constructor(e){this.intentLogs=e}static RECENCY_HALF_LIFE_HOURS=48;static WEIGHTS={recency:.4,activity:.3,statusBoost:.2,blockerBoost:.1};score(e){if(e.length===0)return[];let t=Math.floor(Date.now()/1e3),n=e.map(l=>l.id),i=this.intentLogs.countByMissions(n),r=this.intentLogs.findMissionsWithBlockers(n),o=Math.max(1,...Object.values(i));return e.map(l=>{let c=this.computeRecency(l.updated_at,t),p=(i[l.id]||0)/o,u=this.computeStatusBoost(l.status),d=r.has(l.id)?1:0,h=s.WEIGHTS,m=c*h.recency+p*h.activity+u*h.statusBoost+d*h.blockerBoost;return{mission:l,score:Math.round(m*1e3)/1e3,breakdown:{recency:Math.round(c*1e3)/1e3,activity:Math.round(p*1e3)/1e3,blockerBoost:d,statusBoost:u}}}).sort((l,c)=>c.score-l.score)}computeRecency(e,t){let n=Math.max(0,(t-e)/3600);return Math.pow(.5,n/s.RECENCY_HALF_LIFE_HOURS)}computeStatusBoost(e){switch(e){case"in-progress":return 1;case"verifying":return .8;case"planned":return .4;default:return 0}}};Y();G();var im=x.child({module:"collision-service"}),ts=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=be(this.repoPath);if(!e)return[];let{missions:t}=F.getInstance(this.repoPath),n=t.findActive(e)??[],i=new Set(n.map(c=>c.id)),r=(t.findActive()??[]).filter(c=>!i.has(c.id)),o=[],a=new Set;for(let c of r){let p=c.git_branch||"unknown",u=[e,p].sort().join("::");im.info({branch:p,currentBranch:e,missionId:c.id},"Checking predictive collisions"),p!==e&&!a.has(u)&&(a.add(u),Ko(this.repoPath,e,p)&&o.push({branch:p,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${p}'.`}))}let l=this.analyzeMissionOverlaps([...i]);for(let c of l)o.push({branch:e,mission_id:c.missionB.id,mission_name:c.missionB.name,type:"intent",description:`Logical conflict: Mission '${c.missionA.name}' overlaps with '${c.missionB.name}'.`,conflictingFiles:c.sharedFiles});return o}analyzeMissionOverlaps(e){let t=be(this.repoPath);if(!t)return[];let{missions:n}=F.getInstance(this.repoPath),i=n.findActive(t)??[],r=e&&e.length>0?i.filter(a=>e.includes(a.id)):i,o=[];for(let a=0;a<r.length;a+=1){let l=r[a],c=new Set(n.getWorkingSet(l.id).map(p=>p.file_path));for(let p=a+1;p<r.length;p+=1){let u=r[p],d=n.getWorkingSet(u.id).map(m=>m.file_path),h=Array.from(new Set(d.filter(m=>c.has(m)))).sort();h.length!==0&&o.push({missionA:{id:l.id,name:l.name},missionB:{id:u.id,name:u.name},sharedFiles:h})}}return o}};Y();var pr=new Set(["planned","in-progress","verifying","suspended"]),Pn=class{constructor(e){this.repoPath=e}buildPlanForParent(e){let{missions:t,claims:n}=F.getInstance(this.repoPath);if(!t.findById(e))throw new Error(`Mission ${e} not found`);let o=t.findByParentId(e).filter(d=>pr.has(d.status)).map(d=>{let h=t.getWorkingSet(d.id).map(m=>m.file_path);return{id:d.id,name:d.name,status:d.status,files:h}}),a=this.computeOverlapMatrix(o),l=this.colorIntoWaves(o,a),c=new Set(o.map(d=>d.id)),p=Array.from(new Set(o.flatMap(d=>d.files))),u=n.getClaimsByFiles(p).filter(d=>!c.has(d.mission_id)).map(d=>({file_path:d.file_path,mission_id:d.mission_id,mission_name:d.mission_name,mission_status:d.mission_status,mission_branch:d.mission_branch}));return this.composePlan(o,a,u,e)}buildPlanForMissions(e,t={}){let{includeClaimCheck:n=!0}=t,{missions:i,claims:r}=F.getInstance(this.repoPath),a=i.findByIds(e).filter(p=>pr.has(p.status)).map(p=>({id:p.id,name:p.name,status:p.status,files:i.getWorkingSet(p.id).map(u=>u.file_path)})),l=this.computeOverlapMatrix(a),c=n?this.computeExternalClaims(a,r.getClaimsByFiles(Array.from(new Set(a.flatMap(p=>p.files))))):[];return this.composePlan(a,l,c)}toHandlerPayload(e){let t=new Map(e.child_missions.map(p=>[p.id,p])),n=e.waves.map(p=>({waveIndex:p.wave,missions:p.missions.map(u=>{let d=t.get(u);return{id:u,name:d?.name??`Mission ${u}`,workingSetSize:d?.file_count??0}})})),i=e.overlap_matrix.map(p=>({missionA:p.mission_a,missionB:p.mission_b,sharedFiles:p.shared_files})),r=e.external_claims.map(p=>({filePath:p.file_path,claimedByMissionId:p.mission_id,claimedByMissionName:p.mission_name,claimedByMissionStatus:p.mission_status,claimedByMissionBranch:p.mission_branch})),o=e.child_missions.length,a=n.length,l=n[0]?.missions.length??0,c=`${o} missions in ${a} waves, ${l} parallelizable in wave 1`;return{waves:n,overlapMatrix:i,externalClaims:r,summary:c}}groupMissionsForParallelism(e){let{missions:t}=F.getInstance(this.repoPath),i=t.findByIds(e).filter(o=>pr.has(o.status)).map(o=>({id:o.id,name:o.name,status:o.status,files:t.getWorkingSet(o.id).map(a=>a.file_path)})),r=this.computeOverlapMatrix(i);return this.colorIntoWaves(i,r)}composePlan(e,t,n,i){let r=this.colorIntoWaves(e,t);return{...i!==void 0?{parent_mission_id:i}:{},mission_ids:e.map(o=>o.id),child_missions:e.map(o=>({id:o.id,name:o.name,status:o.status,file_count:o.files.length})),waves:r,overlap_matrix:t,external_claims:n}}computeExternalClaims(e,t){let n=new Set(e.map(i=>i.id));return t.filter(i=>!n.has(i.mission_id)).map(i=>({file_path:i.file_path,mission_id:i.mission_id,mission_name:i.mission_name,mission_status:i.mission_status,mission_branch:i.mission_branch}))}computeOverlapMatrix(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n],r=new Set(i.files);for(let o=n+1;o<e.length;o+=1){let a=e[o],l=a.files.filter(c=>r.has(c));l.length!==0&&t.push({mission_a:i.id,mission_b:a.id,shared_files:Array.from(new Set(l)).sort()})}}return t}colorIntoWaves(e,t){if(e.length===0)return[];let n=new Map;for(let a of e)n.set(a.id,new Set);for(let a of t)n.get(a.mission_a)?.add(a.mission_b),n.get(a.mission_b)?.add(a.mission_a);let i=[...e].sort((a,l)=>{let c=(n.get(l.id)?.size??0)-(n.get(a.id)?.size??0);return c!==0?c:a.id-l.id}),r=new Map;for(let a of i){let l=new Set;for(let p of n.get(a.id)??[]){let u=r.get(p);u!==void 0&&l.add(u)}let c=1;for(;l.has(c);)c+=1;r.set(a.id,c)}let o=new Map;for(let[a,l]of r.entries()){let c=o.get(l)??[];c.push(a),o.set(l,c)}return[...o.entries()].sort((a,l)=>a[0]-l[0]).map(([a,l])=>({wave:a,missions:l.sort((c,p)=>c-p)}))}};var ns=class s{constructor(e){this.repoPath=e}static PROJECT_COUNT_SCOPE={total:"repo",completed:"repo",active:"repo",active_on_branch:"branch"};async getBriefing(e={}){let{missionId:t,scope:n="mission",altitude:i,activeMissionsLimit:r,recentActivityLimit:o,compact:a,branch:l}=e,c=a??(i==="orbit"||i==="atmosphere"),p=o??(i==="orbit"?0:i==="ground"?20:10),{missions:u,intentLogs:d}=F.getInstance(this.repoPath),h=Ze(this.repoPath),m=l??be(this.repoPath);return n==="project"?this.getProjectBriefing({altitude:i,activeMissionsLimit:r,recentActivityLimit:p,compact:c,currentBranch:m,currentCommit:h}):this.getMissionBriefing({missionId:t,altitude:i,recentActivityLimit:p,currentBranch:m,currentCommit:h})}async getProjectBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i,claims:r}=F.getInstance(t),{altitude:o,activeMissionsLimit:a,recentActivityLimit:l,compact:c,currentBranch:p,currentCommit:u}=e,d=n.findActive(p||void 0),h=d.length;a&&d.length>a&&(d=d.slice(0,a));let m=n.findParentOnlyIds(d),f=new Set(m),b=new Map;for(let T of d){if(T.parent_id==null)continue;let I=b.get(T.parent_id)??[];I.push(T),b.set(T.parent_id,I)}let g=new Set(d.map(T=>T.id)),y=r.listClaims().filter(T=>g.has(T.mission_id)).map(T=>({file_path:T.file_path,mission_id:T.mission_id,mission_name:T.mission_name,mission_status:T.mission_status,mission_branch:T.mission_branch,claimed_at:T.claimed_at,updated_at:T.updated_at})),E=new Pn(t).groupMissionsForParallelism(d.map(T=>T.id)),k=E.length,R=new Map;for(let T of y)R.set(T.mission_id,(R.get(T.mission_id)??0)+1);let w=new Map;for(let T of d)w.set(T.id,n.getWorkingSet(T.id).length);let N=d.filter(T=>f.has(T.id)?!1:!this.isOperationalUmbrellaMission(T,b,R,w)),H=new es(i).score(N),C=.15,M=3,D=c&&H.length>M?H.filter((T,I)=>I<M||T.score>=C):H,P=D.map(T=>T.mission),B=new Map(D.map(T=>[T.mission.id,T.score])),L=T=>({id:T.id,name:T.name,goal:T.goal,status:T.status,relevance:B.get(T.id),claimedFileCount:R.get(T.id)??0}),A=T=>({...T,claimedFileCount:R.get(T.id)??0});if(o==="orbit")return{scope:"project",altitude:"orbit",counts:{...n.getStats(),active_on_branch:h},counts_scope:s.PROJECT_COUNT_SCOPE,next_work_candidates:P.map(L),parallel_wave_count:k,claims_count:y.length,meta:{current_branch:p,activeMissionsTotal:h,ember:this.getEmberLabel(t)}};let $={},W=[];for(let T of d)T.parent_id!=null?($[T.parent_id]||($[T.parent_id]=[]),$[T.parent_id].push(T)):W.push(T);let J=n.findRecentCompleted(5).map(L),O=l>0?i.findRecentDecisionActivity(l):void 0,S=m.map(T=>{let I=d.find(j=>j.id===T);return{parent:c?{...A(I),strategy_graph:void 0,verification_context:void 0}:A(I),children:($[T]??[]).map(A)}}),v=W.filter(T=>!f.has(T.id)).map(A);return{scope:"project",altitude:o||"atmosphere",counts:{...n.getStats(),active_on_branch:h},counts_scope:s.PROJECT_COUNT_SCOPE,analytics:n.getAnalytics(),hierarchy:S.length>0?S:void 0,standalone_active:v.length>0?v:void 0,active_missions:S.length===0?c?d.map(T=>({...A(T),strategy_graph:void 0})):d.map(A):void 0,claims:y,parallel_groups:E,next_work_candidates:P.map(L),recent_completed:J,recent_activity:O,meta:{current_branch:p,current_commit:u,activeMissionsTotal:h,active_limit_applied:!!a,relevance_filtered:D.length<H.length?{shown:D.length,total:H.length}:void 0,ember:this.getEmberLabel(t)}}}getEmberLabel(e){try{let{status:t,progress:n}=$i(e);if(t==="idle")return;if(t==="done")return"symbols: fully embedded";let[i,r]=n.split("/").map(Number),o=r>0?Math.round(i/r*100):0;return t==="running"?`symbols: warming ${n} (${o}%)`:`symbols: ${t} ${n}`}catch{return}}isOperationalUmbrellaMission(e,t,n,i){return e.parent_id!=null||!t.has(e.id)||(n.get(e.id)??0)>0||(i.get(e.id)??0)>0||e.status==="in-progress"?!1:!this.hasStepWithStatus(e,"in-progress")}hasStepWithStatus(e,t){if(!e.strategy_graph)return!1;try{let n=JSON.parse(e.strategy_graph),i=n?.steps??n;return Array.isArray(i)?i.some(r=>r?.status===t):!1}catch{return!1}}async getMissionBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i,claims:r}=F.getInstance(t),{missionId:o,altitude:a,recentActivityLimit:l,currentBranch:c,currentCommit:p}=e,u;if(o?u=n.findById(o):u=n.findActive(c||void 0)[0],!u)return null;let d=null;try{u.strategy_graph&&(d=JSON.parse(u.strategy_graph))}catch{}if(a==="orbit")return{altitude:"orbit",mission:{id:u.id,name:u.name,goal:u.goal,status:u.status,last_updated:new Date(u.updated_at*1e3).toISOString()},strategy_snapshot:d};let h="No external shadow changes detected.";try{new ln(t).analyzeGhostChanges(u.commit_sha||void 0),h="Shadow Trace completed: Checked for external modifications."}catch{}let m={repaired:0,failed:0};try{m=new rt(t).detectAndRepairShifts()}catch{}let f=n.getHandoffs(u.id).map(g=>{let y=null;try{y=JSON.parse(g.metadata??"")}catch{}return{artifactId:g.id,kind:g.identifier,confidence:y?.confidence??null,findingsCount:y?.findings?.length??0,risksCount:y?.risks?.length??0,missionsCreated:y?.missionsCreated??[],createdAt:g.created_at}}),b={altitude:a||"atmosphere",mission:{id:u.id,name:u.name,goal:u.goal,status:u.status,last_updated:new Date(u.updated_at*1e3).toISOString(),git_branch:u.git_branch,commit_sha:u.commit_sha,outcome_contract:u.outcome_contract},artifacts:n.getArtifacts(u.id),handoffs:f,shadow_trace:{ghost_analysis:h,symbols_repaired:m.repaired,symbols_missing:m.failed},context:{current_commit:p,working_set:n.getWorkingSet(u.id).map(g=>g.file_path)},claims:r.getClaimsForMission(u.id),parallel_groups:new Pn(t).groupMissionsForParallelism(n.findActive(c||void 0).map(g=>g.id)),strategy_snapshot:d,recent_activity:a==="ground"?i.findByMission(u.id,l||20):i.findByMissionPreferCrystal(u.id,15),ancestor_activity_summary:[],predictive_collisions:[]};try{let g=new ts(t);b.predictive_collisions=await g.analyzePotentialCollisions()}catch{}if(u.parent_id){let g=a==="ground"?i.findByMission(u.parent_id,5):i.findByMissionPreferCrystal(u.parent_id,3);b.ancestor_activity_summary=g.map(y=>({type:y.type,content:y.content,date:new Date(y.created_at*1e3).toISOString()}))}return b}};var Oc=x.child({module:"mcp:tools:ops:briefing"});async function Fc(s){let{repoPath:e,scope:t="mission"}=s;Oc.info({repoPath:e,missionId:s.missionId,scope:t},"Generating briefing");try{let i=await new ns(e).getBriefing(s);if(!i&&t==="mission")return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let r;if(t==="project"){let o=i.counts,a=i.next_work_candidates,l=o.active_on_branch??o.active;r=a.length===0&&l===0?{tool:"shadow_ops_plan",reason:"No open work; create a mission"}:{tool:"shadow_ops_track",reason:"Select a mission from hierarchy or next_work_candidates to execute"}}return{content:[{type:"text",text:JSON.stringify(i,null,2)}],suggestedNext:r}}catch(n){throw Oc.error({error:n,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${n instanceof Error?n.message:String(n)}`)}}G();Y();Y();G();G();var sm=x.child({module:"reasoning-engine"}),is=class{analyze(e){sm.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[],sourceMissions:[]};for(let i of e){let r=i.content.toLowerCase(),o=this.matchesContext(r,i.type),a=this.matchesDecision(r,i.type),l=this.matchesConsequence(r,i.type),c=this.matchesRecommendation(r,i.type);o?t.context.push(i.content):a?t.decisions.push(i.content):c?t.recommendations.push(i.content):l?t.consequences.push(i.content):i.type==="decision"?t.decisions.push(i.content):i.type==="discovery"||i.type==="fix"?t.consequences.push(i.content):t.unclassified.push(i.content)}let n=new Set;for(let i of e)i.mission_id!=null&&n.add(i.mission_id);return t.sourceMissions=[...n],t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(i=>e.includes(i))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(i=>e.includes(i))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(i=>e.includes(i))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(i=>e.includes(i))}};var Dn=x.child({module:"briefing-engine"}),mt=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=F.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new is,this.persistencePivot=new et(e)}async distillMission(e,t=!0){Dn.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.missions.findById(e),r=(this.intentLogs.findByMission(e,1e3)??[]).filter(d=>d.type==="adr"),o=this.gatherConsolidatedLogs(e);if(o.length===0)return{missionId:e,adr:"No intent logs found for this mission.",metrics:{totalLogs:0,symbolCount:0},persistence:{adrLog:"skipped_no_logs",gitNotes:"skipped_no_logs",existingAdrCount:r.length}};let a=this.reasoningEngine.analyze(o),l=new Set(o.map(d=>d.symbol_name).filter(Boolean)),c=`# Architectural Decision Record: Mission #${e}
1063
+
1064
+ `;c+=`## Summary of Intent
1065
+ `,c+=`Collected ${o.length} intent events across ${l.size} symbols.
1066
+
1067
+ `,a.context.length>0&&(c+=`### Context
1068
+ `,a.context.forEach(d=>{c+=`- ${d}
1069
+ `}),c+=`
1070
+ `),a.decisions.length>0&&(c+=`### Key Decisions
1071
+ `,a.decisions.forEach(d=>{c+=`- ${d}
1072
+ `}),c+=`
1073
+ `),a.consequences.length>0&&(c+=`### Consequences & Evolutions
1074
+ `,a.consequences.forEach(d=>{c+=`- ${d}
1075
+ `}),c+=`
1076
+ `),a.recommendations.length>0&&(c+=`### Strategic Recommendations
1077
+ `,a.recommendations.forEach(d=>{c+=`- ${d}
1078
+ `}),c+=`
1079
+ `),a.unclassified.length>0&&(c+=`### Additional Notes
1080
+ `,a.unclassified.forEach(d=>{c+=`- ${d}
1081
+ `}),c+=`
1082
+ `),c+=`
996
1083
  ---
997
- *Generated by Liquid Shadow Reasoning Engine v1*`,t){this.intentLogs.create({mission_id:e,type:"adr",content:o,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:null});try{await this.persistencePivot.syncMissionToGitNotes(e),Hi.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(a){Hi.error({missionId:e,error:a},"Failed to sync ADR to Git Notes")}}else Hi.info({missionId:e},"Tactical Briefing synthesized (dry-run).");return{missionId:e,adr:o,metrics:{totalLogs:n.length,symbolCount:r.size}}}gatherConsolidatedLogs(e,t=0){let n=this.intentLogs.findByMissionPreferCrystal(e,500);if(t>2)return n;let i=this.missions.findByParentId(e);for(let r of i)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};q();import{Visitor as xd}from"@swc/core/Visitor.js";import*as rc from"@swc/core";var vd=S.child({module:"verification-engine"}),Gs=class extends xd{foundUsage=!1;foundImport=!1;rule;currentFunctionName=null;constructor(e){super(),this.rule=e}visitImportDeclaration(e){return this.rule.type==="import"&&e.source.value===this.rule.target&&(this.foundImport=!0),super.visitImportDeclaration(e)}visitFunctionDeclaration(e){let t=this.currentFunctionName;this.currentFunctionName=e.identifier.value;let n=super.visitFunctionDeclaration(e);return this.currentFunctionName=t,n}visitCallExpression(e){return this.rule.type==="usage"&&e.callee.type==="Identifier"&&e.callee.value===this.rule.target&&(!this.rule.context||this.currentFunctionName===this.rule.context)&&(this.foundUsage=!0),super.visitCallExpression(e)}},zi=class{async verify(e,t){try{let n=await rc.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new Gs(t);i.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=i.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=i.foundUsage,!r){let a=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${a} not found.`)}}else t.type==="pattern"&&(r=new RegExp(t.target).test(e),r||o.push(`Required pattern "${t.target}" not found.`));return{passed:r,errors:o}}catch(n){return vd.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};gn();import oc from"path";import Ui from"fs";var Le=S.child({module:"mcp:tools:ops:track"});function qs(s,e){return oc.isAbsolute(e)?e:oc.join(s,e)}async function ac(s,e,t){let{missions:n,intentLogs:i}=O.getInstance(s),r=n.findById(e);if(!r?.parent_id)return;let o=n.findByParentId(r.parent_id);if(!o.every(l=>l.status==="completed"))return;let c=n.findById(r.parent_id);if(!(!c||c.status==="completed")){Le.info({parentId:c.id,childCount:o.length},"All children completed \u2014 cascading parent completion"),n.updateStatus(c.id,"completed",t||void 0),n.clearWorkingSet(c.id),i.create({mission_id:c.id,type:"system",content:`Parent auto-completed: all ${o.length} child missions finished`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:t});try{await new tt(s).distillMission(c.id),Le.info({parentId:c.id},"Parent Auto-Synthesis completed")}catch(l){Le.info({parentId:c.id,...ye(l)},"Parent Auto-Synthesis deferred")}try{await new Fe(s).syncMissionToGitNotes(c.id)}catch(l){Le.info({parentId:c.id,...ye(l)},"Parent Git Notes sync deferred")}await ac(s,c.id,t)}}async function cc(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:a}=s,{missions:c,intentLogs:l}=O.getInstance(e),p=De(e);Le.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:a?.length},"Updating mission status");try{if(a&&Array.isArray(a))for(let h of a)c.addArtifact(t,h.type,h.identifier,h.metadata);let u=[];if(o&&Array.isArray(o)&&u.push(...o),n&&i&&u.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(c.updateStatus(t,i,p||void 0),i==="completed"&&c.clearWorkingSet(t),l.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),i==="completed"){try{await new tt(e).distillMission(t),Le.info({missionId:t},"Auto-Synthesis completed successfully")}catch(h){Le.info({missionId:t,...ye(h)},"Auto-Synthesis deferred or failed")}await ac(e,t,p)}if(!u.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:i,message:"Mission status updated successfully.",artifacts_added:a?.length||0,commit:p},null,2)}]}}if(u.length===0&&(!a||a.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let d=[];for(let h of u){let{stepId:m,status:f,contextPivot:_}=h,g=c.findById(t);if(!g)throw new Error(`Mission ID ${t} not found`);let b=JSON.parse(g.strategy_graph||"{}"),w=null;if(Array.isArray(b)?w=b.find(x=>x.id===m):b.nodes&&Array.isArray(b.nodes)?w=b.nodes.find(x=>x.id===m):b.steps?Array.isArray(b.steps)?w=b.steps.find(x=>x.id===m):w=b.steps[m]:b[m]&&(w=b[m]),!w)throw new Error(`Step ID "${m}" not found`);if(f==="completed"&&w.verification){let x=new zi,R=Array.isArray(w.verification)?w.verification:[w.verification];for(let k of R){let D=k;if(typeof k=="string"&&(D={type:"pattern",target:k}),!D||!D.target){Le.warn({rule:k},"Skipping invalid verification rule (missing target)");continue}let U=D.filePath;if(U&&(U=qs(e,U)),U){if(!Ui.existsSync(U))throw new Error(`Verification failed: File not found at ${U}`);let P=await x.verify(Ui.readFileSync(U,"utf8"),D);if(!P.passed)throw new Error(`Verification failed: ${P.errors.join("")}`)}else{let P=c.getWorkingSet(t),E=!1;P.length===0&&Le.warn("No working set files to verify against for rule");for(let T of P){let I=qs(e,T.file_path);if(!Ui.existsSync(I))continue;if((await x.verify(Ui.readFileSync(I,"utf8"),D)).passed){E=!0;break}}if(!E)throw new Error(`Verification failed: Rule "${D.target}" not satisfied in any working set file.`)}}}if(w.status=f,c.update(t,{strategy_graph:JSON.stringify(b),commit_sha:p}),l.create({mission_id:t,type:"system",content:`Step "${m}" updated to "${f}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),_){let x=_.trim();if(x.startsWith("{")||x.startsWith("["))try{let R=JSON.parse(x);if(R.files&&Array.isArray(R.files)){c.clearWorkingSet(t);for(let k of R.files)c.addToWorkingSet(t,qs(e,k))}}catch(R){Le.warn({error:R},"Failed to apply context pivot")}}d.push({stepId:m,status:f})}try{await new Fe(e).syncMissionToGitNotes(t)}catch(h){Le.info({missionId:t,...ye(h)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,updates:d,artifacts_added:a?.length||0,message:"Status updated",commit:p},null,2)}]}}catch(u){let d=At(u);throw Le.error({repoPath:e,...ye(u)},"Failed to update status"),new Error(`Failed to update status: ${d}`)}}q();var dc=S.child({module:"mcp:tools:ops:graph"});async function mc(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;dc.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(uc(),pc));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw dc.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}V();q();import hc from"node:path";var Xt=S.child({module:"mcp:tools:ops:log"}),Td=["in-progress","verifying"];function Rd(s){for(let e of Td){let t=s.find(n=>n.status===e);if(t)return t.id}return s[0]?.id??null}function kd(s,e){return e?hc.isAbsolute(e)?e:hc.join(s,e):null}async function fc(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o,standalone:a}=s;Xt.info({repoPath:e,type:n,symbolName:o,standalone:a},"Logging intent");let{missions:c,exports:l,intentLogs:p}=O.getInstance(e),u=kd(e,r);try{let d=t??null,h=me(e)||void 0;if(a)d=null,Xt.debug("Standalone intent requested; mission auto-resolution skipped");else if(d){if(!c.findById(d))throw new Error(`Mission ${d} not found. Use shadow_ops_briefing to see available missions.`)}else{let w=c.findActive(h);w.length>0?(d=Rd(w),Xt.debug({missionId:d,currentBranch:h},"Auto-resolved to active mission on current branch")):(d=null,Xt.debug({currentBranch:h},"No active mission found on current branch; logging as system/unlinked intent"))}let m=null,f=null,_=o||null,g=u;if(o){let x=(u?l.findByNameAndFile(o,u):l.findByName(o))[0];x?(m=x.id,f=x.signature,_=x.name,g=x.file_path||g):Xt.warn({symbolName:o,filePath:u??r},"Symbol not found for intent linking")}let b=p.create({mission_id:d,symbol_id:m,file_path:g,type:n,content:i,confidence:1,symbol_name:_,signature:f,commit_sha:null});return d&&g&&c.addToWorkingSet(d,g,m?"symbol":"intent"),{content:[{type:"text",text:JSON.stringify({logId:b,missionId:d,symbolId:m,status:"logged",message:m?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(d){throw Xt.error({error:d,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${d instanceof Error?d.message:String(d)}`)}}V();q();var gc=S.child({module:"mcp:tools:ops:synthesize"});async function yc(s){let{repoPath:e,missionId:t}=s;gc.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=O.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new tt(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics},null,2)}]}}catch(i){throw gc.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}import Cd from"path";var ne={...y,box:se,table:jn,list:Nr};async function bc(s){let[e,...t]=s;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${ne.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${ne.bold("Actions: ")}`),console.log(` ${ne.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${ne.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${ne.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${ne.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${ne.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${ne.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await Y(async()=>{let n=t[0]?Cd.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${ne.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let a=await nc({repoPath:n,name:r,goal:o}),c=JSON.parse(a.content[0].text);console.log(` ${ne.green("\u2714")} Mission planned (ID: ${c.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${ne.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await cc({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${ne.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...a]=t;if(!r||!o||a.length===0){console.error(` ${ne.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await fc({repoPath:n,missionId:parseInt(r),type:o,content:a.join(" ")}),console.log(` ${ne.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${ne.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await yc({repoPath:n,missionId:parseInt(r)});console.log(""),ne.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await mc({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i=await sc({repoPath:n});if(i.content&&i.content[0]){let r=i.content[0].text;try{let o=JSON.parse(r);if(o.mission){console.log(""),console.log(ne.bold(ne.cyan(` Mission Dashboard: ${o.mission.name} `))),ne.box("Tactical Goal",o.mission.goal,"cyan");let a=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",c=[["Status",ne.bold(ne[a](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];ne.table(["Field","Value"],c),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${ne.bold("Recent Activity:")}`),ne.list(o.recent_activity.slice(0,5).map(l=>`${ne.dim(`[${l.type.toUpperCase()}]`)} ${l.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import Js from"path";async function _c(s){let[e,...t]=s;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${y.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${y.bold("Actions: ")}`),console.log(` ${y.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${y.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await Y(async()=>{let n=t[0]?Js.resolve(t[0]):process.cwd();if(e==="symbol"){let i=t[1];if(!i){console.error(` ${y.red("\u2716")} Please provide a symbol name`);return}let r=await Kt({repoPath:n,symbolName:i});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let i=t[1];if(!i){console.error(` ${y.red("\u2716")} Please provide a file path`);return}let r=Js.isAbsolute(i)?i:Js.join(n,i),o=await Ci({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var Ec=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],Id=["--help","-h","--version","-v","--dir","-d"],Ld={index:["--output","-o","--level","-l","--subPath","--force","--deep"],tree:["--subPath","--depth","-d"],trace:["--dir","-d"],"search-config":["--dir","-d","--kind"],"search-concept":["--dir","-d","--interactive","-i"],"search-symbol":["--dir","-d","--interactive","-i"],"search-fuzzy":["--dir","-d","--interactive","-i"]};function $d(){let s=Object.entries(Ld).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
998
- `),e=Ec.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
1084
+ *Generated by Liquid Shadow Reasoning Engine v1*`;let p="skipped_dry_run",u="skipped_dry_run";if(t){let d=r[0];if(d?(this.intentLogs.update(d.id,{content:c,confidence:1,commit_sha:n?.commit_sha??null}),p="updated"):(this.intentLogs.create({mission_id:e,type:"adr",content:c,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:n?.commit_sha??null}),p="created"),!n?.commit_sha)u="skipped_no_commit",Dn.info({missionId:e},"Skipping Git Notes sync because mission has no commit_sha yet");else try{await this.persistencePivot.syncMissionToGitNotes(e),u="synced",Dn.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(h){u="failed",Dn.error({missionId:e,error:h},"Failed to sync ADR to Git Notes")}}else Dn.info({missionId:e},"Tactical Briefing synthesized (dry-run).");return{missionId:e,adr:c,metrics:{totalLogs:o.length,symbolCount:l.size},persistence:{adrLog:p,gitNotes:u,existingAdrCount:r.length}}}gatherConsolidatedLogs(e,t=0){let n=this.intentLogs.findByMissionPreferCrystal(e,500);if(t>2)return n;let i=this.missions.findByParentId(e);for(let r of i)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};G();import{Visitor as rm}from"@swc/core/Visitor.js";import*as Wc from"@swc/core";var om=x.child({module:"verification-engine"}),ur=class extends rm{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)}},ss=class{async verify(e,t){try{let n=await Wc.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new ur(t);i.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=i.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=i.foundUsage,!r){let a=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${a} not found.`)}}else t.type==="pattern"&&(r=new RegExp(t.target).test(e),r||o.push(`Required pattern "${t.target}" not found.`));return{passed:r,errors:o}}catch(n){return om.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};In();import Hc from"path";import rs from"fs";var Te=x.child({module:"mcp:tools:ops:track"});function dr(s,e){return Hc.isAbsolute(e)?e:Hc.join(s,e)}function zc(s){let{topLevelStatus:e,stepUpdatesApplied:t,artifactsAdded:n}=s;return e&&t>0&&n>0?"Mission status updated, step updates applied, and artifacts recorded.":e&&t>0?"Mission status updated and step updates applied.":e&&n>0?"Mission status updated and artifacts recorded.":e?"Mission status updated successfully.":t>0&&n>0?"Step updates applied and artifacts recorded.":t>0?"Step updates applied.":n>0?"Artifacts recorded.":"No changes applied."}async function Bc(s,e,t){let{missions:n,intentLogs:i}=F.getInstance(s),r=n.findById(e);if(!r?.parent_id)return;let o=n.findByParentId(r.parent_id);if(!o.every(p=>p.status==="completed"))return;let l=n.findById(r.parent_id);if(!l||l.status==="completed")return;Te.info({parentId:l.id,childCount:o.length},"All children completed \u2014 cascading parent completion"),n.updateStatus(l.id,"completed",t||void 0),n.clearWorkingSet(l.id);let{claims:c}=F.getInstance(s);c.releaseAllForMission(l.id),i.create({mission_id:l.id,type:"system",content:`Parent auto-completed: all ${o.length} child missions finished`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:t});try{await new mt(s).distillMission(l.id),Te.info({parentId:l.id},"Parent Auto-Synthesis completed")}catch(p){Te.info({parentId:l.id,...Re(p)},"Parent Auto-Synthesis deferred")}try{await new et(s).syncMissionToGitNotes(l.id)}catch(p){Te.info({parentId:l.id,...Re(p)},"Parent Git Notes sync deferred")}await Bc(s,l.id,t)}async function Uc(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:a}=s,{missions:l,intentLogs:c}=F.getInstance(e),p=Ze(e);Te.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:a?.length},"Updating mission status");try{let u=a?.length||0,d,h=0;if(a&&Array.isArray(a))for(let b of a)l.addArtifact(t,b.type,b.identifier,b.metadata);let m=[];if(o&&Array.isArray(o)&&m.push(...o),n&&i&&m.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(d=i,l.updateStatus(t,i,p||void 0),i==="completed"){l.clearWorkingSet(t);let{claims:b}=F.getInstance(e),g=b.releaseAllForMission(t);g>0&&Te.info({missionId:t,released:g},"Auto-released file claims on completion")}if(c.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),i==="completed"){try{await new mt(e).distillMission(t),Te.info({missionId:t},"Auto-Synthesis completed successfully")}catch(b){Te.info({missionId:t,...Re(b)},"Auto-Synthesis deferred or failed")}await Bc(e,t,p)}if(!m.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:i,top_level_status:i,operation:u>0?"status_and_artifacts_updated":"status_updated",message:zc({topLevelStatus:i,stepUpdatesApplied:0,artifactsAdded:u}),artifacts_added:u,step_updates_applied:0,working_set_reseeded:0,commit:p},null,2)}]}}if(m.length===0&&(!a||a.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let f=[];for(let b of m){let{stepId:g,status:y,contextPivot:E}=b,k=l.findById(t);if(!k)throw new Error(`Mission ID ${t} not found`);let R=JSON.parse(k.strategy_graph||"{}"),w=null;if(Array.isArray(R)?w=R.find(N=>N.id===g):R.nodes&&Array.isArray(R.nodes)?w=R.nodes.find(N=>N.id===g):R.steps?Array.isArray(R.steps)?w=R.steps.find(N=>N.id===g):w=R.steps[g]:R[g]&&(w=R[g]),!w)throw new Error(`Step ID "${g}" not found`);if(y==="completed"&&w.verification){let N=new ss,U=Array.isArray(w.verification)?w.verification:[w.verification];for(let H of U){let C=H;if(typeof H=="string"){if(H.trim().split(/\s+/).length>=5){Te.warn({rule:H},"Skipping natural-language verification rule");continue}C={type:"pattern",target:H}}if(!C||!C.target){Te.warn({rule:H},"Skipping invalid verification rule (missing target)");continue}if(typeof C.target=="string"&&C.target.trim().split(/\s+/).length>=5){Te.warn({rule:C},"Skipping natural-language verification target");continue}let M=C.filePath;if(M&&(M=dr(e,M)),M){if(!rs.existsSync(M))throw new Error(`Verification failed: File not found at ${M}`);let D=await N.verify(rs.readFileSync(M,"utf8"),C);if(!D.passed)throw new Error(`Verification failed: ${D.errors.join("")}`)}else{let D=l.getWorkingSet(t),P=!1;D.length===0&&Te.warn("No working set files to verify against for rule");for(let B of D){let L=dr(e,B.file_path);if(!rs.existsSync(L))continue;if((await N.verify(rs.readFileSync(L,"utf8"),C)).passed){P=!0;break}}if(!P)throw new Error(`Verification failed: Rule "${C.target}" not satisfied in any working set file.`)}}}if(w.status=y,l.update(t,{strategy_graph:JSON.stringify(R),commit_sha:p}),c.create({mission_id:t,type:"system",content:`Step "${g}" updated to "${y}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),E){let N=E.trim();if(N.startsWith("{")||N.startsWith("["))try{let U=JSON.parse(N);if(U.files&&Array.isArray(U.files)){l.clearWorkingSet(t);for(let H of U.files)l.addToWorkingSet(t,dr(e,H));h+=U.files.length}}catch(U){Te.warn({error:U},"Failed to apply context pivot")}}f.push({stepId:g,status:y})}try{await new et(e).syncMissionToGitNotes(t)}catch(b){Te.info({missionId:t,...Re(b)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,...d?{top_level_status:d}:{},updates:f,artifacts_added:u,step_updates_applied:f.length,working_set_reseeded:h,operation:d&&f.length>0&&u>0?"status_steps_and_artifacts_updated":d&&f.length>0?"status_and_steps_updated":d&&u>0?"status_and_artifacts_updated":f.length>0&&u>0?"steps_and_artifacts_updated":f.length>0?"steps_updated":u>0?"artifacts_recorded":"no_changes",message:zc({topLevelStatus:d,stepUpdatesApplied:f.length,artifactsAdded:u}),commit:p},null,2)}]}}catch(u){let d=qt(u);throw Te.error({repoPath:e,...Re(u)},"Failed to update status"),new Error(`Failed to update status: ${d}`)}}G();var Vc=x.child({module:"mcp:tools:ops:graph"});async function Jc(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;Vc.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(qc(),Gc));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw Vc.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}Y();G();import Yc from"node:path";var Jt=x.child({module:"mcp:tools:ops:log"}),am=["in-progress","verifying"],cm=5;function lm(s){for(let e of am){let t=s.find(n=>n.status===e);if(t)return t.id}return s[0]?.id??null}function pm(s,e){return e?Yc.isAbsolute(e)?e:Yc.join(s,e):null}async function Kc(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o,standalone:a}=s;Jt.info({repoPath:e,type:n,symbolName:o,standalone:a},"Logging intent");let{missions:l,exports:c,intentLogs:p}=F.getInstance(e),u=pm(e,r);try{let d=t??null,h=be(e)||void 0;if(a)d=null,Jt.debug("Standalone intent requested; mission auto-resolution skipped");else if(d){if(!l.findById(d))throw new Error(`Mission ${d} not found. Use shadow_ops_briefing to see available missions.`)}else{let R=l.findActive(h);R.length>0?(d=lm(R),Jt.debug({missionId:d,currentBranch:h},"Auto-resolved to active mission on current branch")):(d=null,Jt.debug({currentBranch:h},"No active mission found on current branch; logging as system/unlinked intent"))}let m=null,f=null,b=o||null,g=u,y;if(o){let R=u?c.findByNameAndFile(o,u):c.findByName(o);if(R.length===1){let w=R[0];m=w.id,f=w.signature,b=w.name,g=w.file_path||g,y={requested:o,status:"resolved",matchCount:1,resolvedSymbolId:w.id,resolvedFilePath:g}}else R.length===0?(y={requested:o,status:"not_found",matchCount:0},Jt.warn({symbolName:o,filePath:u??r},"Symbol not found for intent linking")):(y={requested:o,status:"ambiguous",matchCount:R.length,candidates:R.slice(0,cm).map(w=>({id:w.id,name:w.name,kind:w.kind,file_path:w.file_path}))},Jt.warn({symbolName:o,filePath:u??r,matchCount:R.length},"Symbol resolution was ambiguous; intent left unlinked"))}let E=p.create({mission_id:d,symbol_id:m,file_path:g,type:n,content:i,confidence:1,symbol_name:b,signature:f,commit_sha:null});d&&g&&l.addToWorkingSet(d,g,m?"symbol":"intent");let k=y?y.status==="resolved"?`Intent linked to symbol "${y.requested}"`:y.status==="ambiguous"?`Intent logged without symbol link: "${y.requested}" matched ${y.matchCount} symbols`:`Intent logged without symbol link: "${y.requested}" was not found`:"Intent logged";return{content:[{type:"text",text:JSON.stringify({logId:E,missionId:d,symbolId:m,filePath:g,symbolName:b,symbolResolution:y,status:"logged",message:k},null,2)}]}}catch(d){throw Jt.error({error:d,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${d instanceof Error?d.message:String(d)}`)}}Y();G();var Qc=x.child({module:"mcp:tools:ops:synthesize"});async function Zc(s){let{repoPath:e,missionId:t}=s;Qc.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=F.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new mt(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics,persistence:o.persistence,message:o.persistence.adrLog==="skipped_no_logs"?"No intent logs available to synthesize.":o.persistence.gitNotes==="failed"?"ADR synthesized, but Git Notes sync failed.":o.persistence.gitNotes==="skipped_no_commit"?"ADR synthesized; Git Notes sync skipped because the mission has no commit SHA.":"ADR synthesized successfully."},null,2)}]}}catch(i){throw Qc.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}import um from"path";var oe={..._,box:ue,table:ri,list:lo};async function Xc(s){let[e,...t]=s;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${oe.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${oe.bold("Actions: ")}`),console.log(` ${oe.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${oe.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${oe.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${oe.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${oe.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${oe.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await Z(async()=>{let n=t[0]?um.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${oe.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let a=await Dc({repoPath:n,name:r,goal:o}),l=JSON.parse(a.content[0].text);console.log(` ${oe.green("\u2714")} Mission planned (ID: ${l.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${oe.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await Uc({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${oe.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...a]=t;if(!r||!o||a.length===0){console.error(` ${oe.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await Kc({repoPath:n,missionId:parseInt(r),type:o,content:a.join(" ")}),console.log(` ${oe.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${oe.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await Zc({repoPath:n,missionId:parseInt(r)});console.log(""),oe.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await Jc({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i=await Fc({repoPath:n});if(i.content&&i.content[0]){let r=i.content[0].text;try{let o=JSON.parse(r);if(o.mission){console.log(""),console.log(oe.bold(oe.cyan(` Mission Dashboard: ${o.mission.name} `))),oe.box("Tactical Goal",o.mission.goal,"cyan");let a=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",l=[["Status",oe.bold(oe[a](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];oe.table(["Field","Value"],l),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${oe.bold("Recent Activity:")}`),oe.list(o.recent_activity.slice(0,5).map(c=>`${oe.dim(`[${c.type.toUpperCase()}]`)} ${c.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import fr from"path";async function el(s){let[e,...t]=s;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${_.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${_.bold("Actions: ")}`),console.log(` ${_.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${_.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await Z(async()=>{let n=t[0]?fr.resolve(t[0]):process.cwd();if(e==="symbol"){let i=t[1];if(!i){console.error(` ${_.red("\u2716")} Please provide a symbol name`);return}let r=await mn({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(` ${_.red("\u2716")} Please provide a file path`);return}let r=fr.isAbsolute(i)?i:fr.join(n,i),o=await Gi({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var tl=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],dm=["--help","-h","--version","-v","--dir","-d"],mm={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 fm(){let s=Object.entries(mm).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
1085
+ `),e=tl.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
999
1086
  _liquid_shadow() {
1000
1087
  local cur="\${COMP_WORDS[COMP_CWORD]}"
1001
1088
  local words=("\${COMP_WORDS[@]}")
@@ -1005,7 +1092,7 @@ _liquid_shadow() {
1005
1092
  if [[ "\${words[$i]}" != -* ]]; then cmd="\${words[$i]}"; break; fi
1006
1093
  ((i++))
1007
1094
  done
1008
- local opts="${Id.join(" ")}"
1095
+ local opts="${dm.join(" ")}"
1009
1096
  if [ -n "$cmd" ]; then
1010
1097
  case "$cmd" in
1011
1098
  ${s}
@@ -1017,11 +1104,11 @@ ${s}
1017
1104
  COMPREPLY=($(compgen -W "$opts" -- "$cur"))
1018
1105
  }
1019
1106
  complete -F _liquid_shadow liquid-shadow
1020
- `}function Ad(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
1107
+ `}function hm(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
1021
1108
  # Run after compinit (e.g. in .zshrc after compinit)
1022
1109
 
1023
1110
  _liquid_shadow() {
1024
- local -a cmds; cmds=(${Ec.map(e=>`'${e}'`).join(" ")})
1111
+ local -a cmds; cmds=(${tl.map(e=>`'${e}'`).join(" ")})
1025
1112
  if [ $CURRENT -eq 2 ]; then
1026
1113
  _describe 'command' cmds
1027
1114
  return
@@ -1038,7 +1125,8 @@ _liquid_shadow() {
1038
1125
  _describe 'flag' fl
1039
1126
  }
1040
1127
  compdef _liquid_shadow liquid-shadow
1041
- `}async function Sc(s){s==="bash"?console.log($d()):s==="zsh"?console.log(Ad()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}import Pd from"fs";import Md from"path";var Nd=2e3;async function wc(s){let e=Md.resolve(s);await Y(async()=>{pe("Watch mode");let t=Ke(e),n=null,i=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(y.dim(" Changes detected, reindexing...")),await X(e,5,!1,!0),console.log(y.green(" Reindex complete."))}catch(r){console.error(y.red(" Reindex failed:"),r instanceof Error?r.message:r)}},Nd)};try{Pd.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&i()}),console.log(y.cyan(` Watching ${e}`)),console.log(y.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),Pe("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)}})}V();q();var Dd=S.child({module:"narrative-service"}),ji=class{missions;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t}=O.getInstance(e);this.missions=t,this.briefingEngine=new tt(e)}async generateChronicle(e={}){Dd.info(e,"Generating Repo Chronicle...");let n=this.missions.findAll().filter(l=>l.parent_id===null&&l.status!=="planned");e.branch&&(n=n.filter(l=>!l.git_branch||l.git_branch===e.branch)),e.since&&(n=n.filter(l=>l.updated_at>=e.since)),e.until&&(n=n.filter(l=>l.updated_at<=e.until)),n.sort((l,p)=>p.updated_at-l.updated_at);let i=e.offset||0,r=e.limit||10;n=n.slice(i,i+r);let o=[],a=[],c=[];for(let l of n){let p=this.missions.findByParentId(l.id),u=p.length>0,d=await this.briefingEngine.distillMission(l.id,!1);if(u){let h=[];for(let f of p)h.push(await this.mapMissionToEpisode(f));h.unshift(await this.mapMissionToEpisode(l));let m={kind:"initiative",root_mission_id:l.id,title:l.name,strategy_graph:l.strategy_graph?JSON.parse(l.strategy_graph):{},episodes:e.compact?[]:h,synthesized_narrative:e.compact?this.truncateText(d.adr):d.adr||""};o.push(m),c.push(m)}else{let h=await this.mapMissionToEpisode(l,d.adr,e.compact);a.push(h),c.push(h)}}return{repo_path:this.repoPath,generated_at:Date.now(),initiatives:o,unattached_episodes:a,timeline:c}}async mapMissionToEpisode(e,t,n=!1){let i=t;return i||(i=(await this.briefingEngine.distillMission(e.id,!1)).adr),{kind:"episode",mission_id:e.id,title:e.name,goal:e.goal,outcome:e.outcome_contract,intents:[],adr_summary:n?this.truncateText(i):i}}truncateText(e,t=300){return e?e.length<=t?e:e.slice(0,t)+"... (truncated)":""}renderChronicleMarkdown(e){let t=`# Repository Chronicle
1128
+ `}async function nl(s){s==="bash"?console.log(fm()):s==="zsh"?console.log(hm()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}import gm from"fs";import ym from"path";var bm=2e3;async function il(s){let e=ym.resolve(s);await Z(async()=>{ge("Watch mode");let t=lt(e),n=null,i=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(_.dim(" Changes detected, reindexing...")),await se(e,5,!1,!0),console.log(_.green(" Reindex complete."))}catch(r){console.error(_.red(" Reindex failed:"),r instanceof Error?r.message:r)}},bm)};try{gm.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&i()}),console.log(_.cyan(` Watching ${e}`)),console.log(_.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),Je("Ctrl+C to stop"),await new Promise((r,o)=>{process.on("SIGINT",()=>o(new Error("SIGINT"))),process.on("SIGTERM",()=>o(new Error("SIGTERM")))}).catch(()=>{})}finally{n&&clearTimeout(n),await ne(e)}})}Y();G();var _m=x.child({module:"narrative-service"}),os=class{missions;intentLogs;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t,intentLogs:n}=F.getInstance(e);this.missions=t,this.intentLogs=n,this.briefingEngine=new mt(e)}async generateChronicle(e={}){_m.info(e,"Generating Repo Chronicle...");let n=this.missions.findAll().filter(c=>c.parent_id===null&&c.status!=="planned");e.branch&&(n=n.filter(c=>!c.git_branch||c.git_branch===e.branch)),e.since&&(n=n.filter(c=>c.updated_at>=e.since)),e.until&&(n=n.filter(c=>c.updated_at<=e.until)),n.sort((c,p)=>p.updated_at-c.updated_at);let i=e.offset||0,r=e.limit||10;n=n.slice(i,i+r);let o=[],a=[],l=[];for(let c of n){let p=this.missions.findByParentId(c.id),u=p.length>0,d=await this.briefingEngine.distillMission(c.id,!1),h=this.resolveNarrativeText(c.id,d.adr);if(u){let m=[];for(let g of p){let y=await this.mapMissionToEpisode(g);y&&m.push(y)}let f=await this.mapMissionToEpisode(c);if(f&&m.unshift(f),!h&&m.length===0)continue;let b={kind:"initiative",root_mission_id:c.id,title:c.name,strategy_graph:c.strategy_graph?JSON.parse(c.strategy_graph):{},episodes:e.compact?[]:m,synthesized_narrative:e.compact?this.truncateText(h):h};o.push(b),l.push(b)}else{let m=await this.mapMissionToEpisode(c,h,e.compact);if(!m)continue;a.push(m),l.push(m)}}return{repo_path:this.repoPath,generated_at:Date.now(),initiatives:o,unattached_episodes:a,timeline:l}}async mapMissionToEpisode(e,t,n=!1){let i=t;if(!i){let r=await this.briefingEngine.distillMission(e.id,!1);i=this.resolveNarrativeText(e.id,r.adr)}return i?{kind:"episode",mission_id:e.id,title:e.name,goal:e.goal,outcome:e.outcome_contract,intents:[],adr_summary:n?this.truncateText(i):i}:null}resolveNarrativeText(e,t){let n=t?.trim()??"";if(n&&n!=="No intent logs found for this mission.")return n;let i=this.intentLogs.findByMission(e,1e3)??[],r=i.filter(a=>a.type==="adr");if(r.length>0)return r.sort((l,c)=>c.created_at-l.created_at)[0].content?.trim()??"";let o=i.filter(a=>["decision","discovery","fix","blocker","note","heritage","crystal"].includes(a.type));return o.length>0?o.map(a=>`- [${a.type}] ${a.content}`).join(`
1129
+ `):""}truncateText(e,t=300){return e?e.length<=t?e:e.slice(0,t)+"... (truncated)":""}renderChronicleMarkdown(e){let t=`# Repository Chronicle
1042
1130
 
1043
1131
  `;if(t+=`*Generated at ${new Date(e.generated_at).toISOString()}*
1044
1132
 
@@ -1049,334 +1137,348 @@ compdef _liquid_shadow liquid-shadow
1049
1137
  `,t+=`${n.adr_summary}
1050
1138
 
1051
1139
  `),t+=`---
1052
- `;return t}};q();import Od from"path";async function xc(s,e){let t=Od.resolve(s||process.cwd()),n=e.format==="json"?"json":"markdown",i=S.child({module:"cli:chronicle",repoPath:t});i.info("Generating repository chronicle...");try{let r=new ji(t),o=await r.generateChronicle({limit:e.limit,offset:e.offset,since:e.since,until:e.until});console.log(n==="json"?JSON.stringify(o,null,2):r.renderChronicleMarkdown(o))}catch(r){i.error({error:r},"Failed to generate chronicle"),console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}}import bt from"fs";import Zt from"path";import Hd from"os";import $e from"fs";import Je from"path";import Fd from"os";var vc={shadow_audit:'---\nname: audit\ndescription: Perform codebase health audits to identify dead code, circular dependencies, and technical debt. Use when auditing code quality, finding unused code, detecting circular dependencies, or when the user asks about codebase health, technical debt, or code cleanup.\n---\n\n# Codebase Audit\n\nComprehensive health audit using Shadow analyze toolkit.\n\n## \u{1F680} Workflow\n\n1. **Session Context**: `shadow_ops_context` (repoPath) \u2014 **ONE CALL** for hologram + chronicle + briefing. Get architecture baseline.\n2. **Dead Code Detection**: `shadow_analyze_debt` (mode: "dead-code", limit: 100, includeTests: false, repoPath) \u2014 Unused exports.\n3. **Circular Dependencies**: `shadow_analyze_debt` (mode: "circular-deps", limit: 20, repoPath) \u2014 Import cycles.\n4. **Layer Integrity** (optional): `shadow_recon_topography` (repoPath) \u2014 Detailed layer analysis if hologram summary isn\'t enough.\n5. **Log Findings**: `shadow_ops_log` (missionId, type: "discovery", content, repoPath).\n6. **Create Cleanup Mission** (optional): `shadow_ops_plan` (name: "Codebase Cleanup", templateId: "refactoring", templateVars, repoPath).\n\n## \u{1F6E0} Precise Tooling\n\n| Audit Target | Atomic Tool |\n| :------------------- | :------------------------------------------------------------------------------------- |\n| **Session Start** \u{1F680} | `shadow_ops_context` (repoPath) \u2014 **START HERE** for baseline |\n| **Architecture** | `shadow_recon_hologram` (repoPath) \u2014 if you need standalone |\n| **Dead Code** | `shadow_analyze_debt` (mode: "dead-code", limit: 100, **confidenceThreshold: "high"**) |\n| **Circular Deps** | `shadow_analyze_debt` (mode: "circular-deps") |\n| **Layers** | `shadow_recon_topography` \u2014 detailed breakdown if needed |\n| **Config Audit** | `shadow_search_config` (kind: "Env", **showUsage: true**) \u2014 find orphaned env vars |\n| **Event Mesh** | `shadow_analyze_mesh` (repoPath) \u2014 audit all HTTP routes, socket events, pubsub topics |\n| **Type Integrity** | `shadow_analyze_type_graph` (filePath, repoPath) \u2014 interface/type inheritance chains |\n| **Theme Patterns** | `shadow_ops_crystallize_theme` (query, repoPath) \u2014 recurring issues across missions |\n\n## \u{1F4A1} Intelligence Options\n\n- **`shadow_analyze_debt` confidence levels**: Use `confidenceThreshold: "high"` for likely dead code, `"medium"` for possibly intentional (test fixtures, etc.), `"all"` for everything.\n- **`shadow_analyze_debt` exclusion filters**: Use `excludePatterns`, `includeMigrations: false`, `includeFixtures: false` to reduce noise.\n- **`shadow_search_config` with `showUsage: true`**: Cross-references config vars with code to show usage counts and identify orphaned vars (defined but never used).\n\n## \u{1F50D} Health Criteria\n\n- **Critical Issues**: Circular deps in core logic, >50 dead exports, orphaned env vars with secrets\n- **Warning Signs**: Layer violations (Test \u2192 Logic), >20 dead exports, >10 orphaned configs\n- **Good Health**: Clean layers, <10 dead exports, no circular deps, all configs in use\n',shadow_chronicle:`---
1140
+ `;return t}};G();import Em from"path";async function sl(s,e){let t=Em.resolve(s||process.cwd()),n=e.format==="json"?"json":"markdown",i=x.child({module:"cli:chronicle",repoPath:t});i.info("Generating repository chronicle...");try{let r=new os(t),o=await r.generateChronicle({limit:e.limit,offset:e.offset,since:e.since,until:e.until});console.log(n==="json"?JSON.stringify(o,null,2):r.renderChronicleMarkdown(o))}catch(r){i.error({error:r},"Failed to generate chronicle"),console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}}import At from"fs";import hn from"path";import wm from"os";import Be from"fs";import ot from"path";import Sm from"os";var rl={shadow_audit:'---\nname: audit\ndescription: Audit repository health with Shadow tools. Use when hunting dead code, import cycles, layer drift, orphaned config, structural risks, or when turning audit findings into cleanup work.\n---\n\n# Audit\n\nUse this skill when the goal is repository health, not feature delivery.\n\n## Start\n\n1. `shadow_ops_context({ repoPath, compact: true })`\n2. `shadow_analyze_debt({ repoPath, mode: "dead-code", confidenceThreshold: "high" })`\n3. `shadow_analyze_debt({ repoPath, mode: "circular-deps" })`\n\n## Add depth only when needed\n\n- `shadow_recon_topography({ repoPath })` for layer drift and boundary violations.\n- `shadow_recon_scout({ repoPath })` for architectural drift and anomalies.\n- `shadow_search_config({ repoPath, kind: "Env", showUsage: true })` for orphaned config and env keys.\n- `shadow_analyze_impact({ repoPath, symbolName, filePath? })` for risky hubs.\n- `shadow_analyze_type_graph({ repoPath, symbolName, filePath? })` when a central interface or base class is involved.\n- `shadow_analyze_mesh({ repoPath, topic, type? })` only when you already have a concrete route or event fragment such as `"/api/"` or `"order."`.\n\n## Close the loop\n\n- `shadow_ops_log({ repoPath, missionId?, type: "discovery", content, filePath?, symbolName? })`\n- `shadow_ops_handoff({ repoPath, missionId?, kind: "debt_scan", findings, risks?, gaps? })`\n- `shadow_ops_plan({ repoPath, name, goal, templateId: "refactoring", workingSet? })`\n\n## Rules\n\n- Start with `confidenceThreshold: "high"` and widen only if the user wants a broader sweep.\n- `shadow_ops_crystallize_theme` takes `theme`, not `query`.\n- `shadow_analyze_type_graph` requires `symbolName`.\n',shadow_chronicle:`---
1053
1141
  name: chronicle
1054
- description: Retrieve and analyze the repository's narrative archive as recorded in Git-native memory. Use when you need to understand historical decisions, catch up on repository progress, review recently completed missions, or when the user asks for a project history, changelog, or chronological overview of architectural changes.
1142
+ description: Read the repository narrative archive. Use when you need project history, ADR context, recent completed work, release-note material, or a chronological view of architectural changes.
1055
1143
  ---
1056
1144
 
1057
- # Repository Chronicle
1058
-
1059
- Retrieve narrative archive from Git-native memory.
1060
-
1061
- ## \u{1F680} Workflow
1145
+ # Chronicle
1062
1146
 
1063
- 1. **Recent History**: \`shadow_ops_chronicle\` (limit: 10, format: "markdown", repoPath) \u2014 Last 10 entries.
1064
- 2. **Time-Filtered**:
1065
- - \`shadow_ops_chronicle\` (since: &lt;unix&gt;, limit: 20, repoPath)
1066
- - \`shadow_ops_chronicle\` (until: &lt;unix&gt;, limit: 20, repoPath)
1067
- 3. **Structured Data**: \`shadow_ops_chronicle\` (format: "json", limit: 50, repoPath) \u2014 For processing.
1068
- 4. **Paginated**: \`shadow_ops_chronicle\` (limit: 10, offset: 10, repoPath) \u2014 Second page.
1147
+ Use this skill when the answer lives in mission history rather than the current code graph.
1069
1148
 
1070
- ## \u{1F6E0} Precise Tooling
1149
+ ## Core calls
1071
1150
 
1072
- | Chronicle Query | Atomic Tool |
1073
- | :-------------------- | :---------------------------------------------------------------- |
1074
- | **Recent (Markdown)** | \`shadow_ops_chronicle\` (limit: 10, format: "markdown") |
1075
- | **Time Range** | \`shadow_ops_chronicle\` (since: &lt;unix&gt;, until: &lt;unix&gt;) |
1076
- | **JSON Data** | \`shadow_ops_chronicle\` (format: "json", limit: 50) |
1077
- | **Pagination** | \`shadow_ops_chronicle\` (limit: 10, offset: 10) |
1151
+ - Recent narrative: \`shadow_ops_chronicle({ repoPath, limit: 10, format: "markdown" })\`
1152
+ - Structured output: \`shadow_ops_chronicle({ repoPath, format: "json", limit: 50 })\`
1153
+ - Time window: \`shadow_ops_chronicle({ repoPath, since, until })\`
1154
+ - Branch-scoped history: \`shadow_ops_chronicle({ repoPath, branch, limit })\`
1155
+ - Pagination: \`shadow_ops_chronicle({ repoPath, limit, offset })\`
1078
1156
 
1079
- ## Output Formats
1157
+ ## Good pairings
1080
1158
 
1081
- - **\`format: "markdown"\`** (default): Human-readable narrative feed with missions grouped as Strategic Initiatives and Standalone Episodes
1082
- - **\`format: "json"\`**: Structured data for programmatic analysis (includes missionId, steps, timestamps, ADRs)
1159
+ - \`shadow_ops_context({ repoPath, compact: true })\` if you also need the current mission landscape.
1160
+ - \`shadow_ops_graph({ repoPath, missionId, format: "mermaid" })\` when a historical mission hierarchy matters.
1083
1161
 
1084
- ## Use Cases
1085
-
1086
- - **Onboarding**: Read last 10 entries to catch up
1087
- - **Release Notes**: Get completed missions since last release
1088
- - **ADR Review**: Extract all architectural decisions
1089
- - **Progress Reports**: Show what's been done this week
1162
+ ## Notes
1090
1163
 
1091
- **Note:** Chronicle reads from Git Notes, so it's persistent across branches and clones.
1092
- `,shadow_continue:'---\nname: continue\ndescription: Get briefing, pick one mission from next_work_candidates, then work that mission to completion with all remaining steps in one run. Use when continuing work on missions, executing mission steps, or when the user asks to continue work, finish a mission, or proceed with development tasks.\n---\n\n**In one sentence:** Get briefing (+ optional trace), pick **one mission** from **next_work_candidates** (ranked by relevance), then work that mission to completion \u2014 all remaining steps in one run. Update and log as you go. No status reports; when you\'re done with that mission, it\'s done.\n\n---\n\n## 1. Context\n\n- **Option A (one shot):** `shadow_ops_context` (repoPath) \u2192 returns hologram + chronicle(5) + **briefing** (counts, **next_work_candidates** ranked by relevance). Use when you want architecture + history + backlog in one call at the start of /continue.\n- **Option B:** `shadow_ops_briefing` (scope: "project", repoPath) \u2192 **next_work_candidates** (relevance-ranked), hierarchy, analytics.\n - Use **altitude** to control output density: `orbit` (~200 tokens, counts + candidates only), `atmosphere` (default, strategy + crystals), `ground` (raw logs + working set + collisions).\n- `shadow_sync_trace` (repoPath) only if you care about external changes. Otherwise skip.\n\n## 2. Pick one mission\n\n- **`next_work_candidates`** are ranked by the MissionRelevanceScorer (recency \xD7 0.4 + activity \xD7 0.3 + status \xD7 0.2 + blockers \xD7 0.1). Higher score = more relevant.\n- Choose the top-ranked candidate. Prefer in-progress over planned. Parent-only missions (umbrellas) are already filtered out.\n\n## 3. Work the whole mission\n\n- For that mission, run through **all remaining steps** (not just one):\n - **Surgical Discovery:** `shadow_analyze_flow` (symbolName, filePath, repoPath).\n - **Execute Step**: Set in-progress \u2192 implement \u2192 `shadow_ops_track` (missionId, stepId, status: "completed", contextPivot, repoPath).\n - **Atomic Logging:** At least once per step. `shadow_ops_log` (missionId, type: "decision", content, symbolName, repoPath).\n - **Inter-agent handoff** (multi-agent pipelines only): When handing off findings to another agent, call `shadow_ops_handoff` (missionId, role, summary, findings, repoPath) to persist a typed artifact with embedding. The receiving agent calls `shadow_ops_handoff_read` (missionId, query, repoPath) to semantically retrieve relevant prior handoffs.\n- **Seal the mission**: `shadow_ops_track` (missionId, status: "completed", repoPath).\n - This **auto-triggers**: ADR synthesis, Git Notes persistence, and cascade parent completion (if all sibling missions are also done, the parent auto-completes too).\n - No need to call `shadow_ops_synthesize` separately \u2014 it\'s automatic on completion.\n- **Optional \u2014 Crystallize** (for long-running missions with many logs): `shadow_ops_crystallize` (missionId, repoPath) compresses raw intent logs into a single crystal summary. Useful mid-mission to keep briefings lean.\n- **Optional \u2014 Theme Crystallize** (cross-mission patterns): `shadow_ops_crystallize_theme` (query, repoPath) clusters semantically related intent logs across ALL missions to surface recurring architectural themes. Use when you sense a pattern repeating across missions.\n\n## \u{1F6E0} Precise Tooling\n\n| Action | Atomic Tool | Example |\n| :--------------------- | :----------------------------- | :--------------------------------------------------------------- |\n| **Context (one shot)** | `shadow_ops_context` | repoPath \u2014 hologram + chronicle + briefing |\n| **Briefing** | `shadow_ops_briefing` | scope: "project", altitude: "orbit", repoPath |\n| **Flow Trace** | `shadow_analyze_flow` | symbolName: "handleRequest", filePath, repoPath |\n| **Step Update** | `shadow_ops_track` | missionId: 4, stepId: "s2", status: "completed" |\n| **Intent Log** | `shadow_ops_log` | missionId: 4, type: "fix", content: "..." |\n| **Complete Mission** | `shadow_ops_track` | missionId: 4, status: "completed" \u2014 auto-synthesizes ADR |\n| **Crystallize** | `shadow_ops_crystallize` | missionId: 4 \u2014 compress logs mid-mission |\n| **Theme Crystallize** | `shadow_ops_crystallize_theme` | query: "auth patterns" \u2014 cross-mission semantic clustering |\n| **Handoff (write)** | `shadow_ops_handoff` | missionId, role: "RECON", summary, findings \u2014 persist artifact |\n| **Handoff (read)** | `shadow_ops_handoff_read` | missionId, query: "auth findings" \u2014 semantic retrieval |\n| **Event Mesh** | `shadow_analyze_mesh` | repoPath \u2014 surface all HTTP routes, socket events, pubsub topics |\n| **Type Graph** | `shadow_analyze_type_graph` | filePath, repoPath \u2014 interface/type inheritance map |\n| **Explain Diff** | `shadow_analyze_explain_diff` | fromCommit, toCommit, repoPath \u2014 semantic diff narrative |\n\n_Note: Always use `symbolName` in `shadow_ops_log` to create Liquid Anchors._\n\n## 4. Don\'t\n\n- Don\'t do one step and stop \u2014 /continue is "finish a mission," not "do one step."\n- Don\'t call `shadow_ops_synthesize` after completing \u2014 it\'s automatic on `status: "completed"`.\n- Don\'t long status reports. Don\'t ask "what should I work on?" unless a real tie. Don\'t auto-commit.\n\n---\n\n**Tools:** `shadow_ops_context` (optional start), `shadow_ops_briefing`, `shadow_ops_track`, `shadow_ops_log`, `shadow_ops_crystallize`, `shadow_ops_crystallize_theme`, `shadow_ops_handoff`, `shadow_ops_handoff_read`, `shadow_sync_trace`. For discovery: `shadow_search_*`, `shadow_recon_*`, `shadow_analyze_*` (including `shadow_analyze_mesh`, `shadow_analyze_type_graph`, `shadow_analyze_explain_diff`).\n',shadow_crystallize:`---
1093
- name: crystallize
1094
- description: Compress a mission's intent logs into a dense crystal summary for token-efficient briefings. Use when a mission has accumulated many raw logs, when briefings are too verbose, or when the user asks about log compression, crystallization, or context reduction.
1164
+ - \`format: "markdown"\` is best for humans.
1165
+ - \`format: "json"\` is best when another tool or agent will process the result.
1166
+ - Chronicle is backed by Git Notes, so it survives across branches and clones.
1167
+ `,shadow_continue:`---
1168
+ name: continue
1169
+ description: Get briefing, pick one mission from next_work_candidates, then work that mission to completion with all remaining steps in one run. Use when continuing work on missions, executing mission steps, or when the user asks to continue work, finish a mission, or proceed with development tasks.
1095
1170
  ---
1096
1171
 
1097
- # Intent Log Crystallization
1098
-
1099
- Compress raw intent logs into a single crystal summary node. The crystal replaces verbose raw logs in briefings, reducing token usage while preserving the mission's key decisions, context, and consequences.
1100
-
1101
- ## When to Crystallize
1172
+ # Continue
1173
+
1174
+ Pick one mission from \`next_work_candidates\` and finish it end to end.
1175
+
1176
+ ## Start
1177
+
1178
+ 1. \`shadow_ops_context({ repoPath, compact: true })\` or \`shadow_ops_briefing({ repoPath, scope: "project", altitude: "orbit" })\`
1179
+ 2. Pick one leaf mission from \`next_work_candidates\`. Prefer in-progress over planned.
1180
+ 3. If there is no candidate, stop and plan new work instead of inventing a mission.
1181
+
1182
+ ## Work loop
1183
+
1184
+ - Mark the active step: \`shadow_ops_track({ repoPath, missionId, stepId, status: "in-progress" })\`
1185
+ - If multiple agents may edit the same area, check and claim first:
1186
+ - \`shadow_working_set_check({ repoPath, filePaths })\`
1187
+ - \`shadow_ops_claim({ repoPath, missionId, filePaths, agentTag? })\`
1188
+ - Do focused discovery with the relevant search, recon, analyze, and inspect tools.
1189
+ - Record at least one meaningful log per step:
1190
+ - \`shadow_ops_log({ repoPath, missionId, type: "decision" | "discovery" | "fix", content, filePath?, symbolName? })\`
1191
+ - Mark each finished step:
1192
+ - \`shadow_ops_track({ repoPath, missionId, stepId, status: "completed", contextPivot? })\`
1193
+
1194
+ ## Finish
1195
+
1196
+ - Optional handoff for downstream agents:
1197
+ - \`shadow_ops_handoff({ repoPath, missionId, kind, findings, risks?, gaps?, confidence?, agentTag? })\`
1198
+ - \`shadow_ops_handoff_read({ repoPath, missionId?, kind?, query?, limit? })\`
1199
+ - Optional review gate, but only after the user explicitly asks for Tribunal or clearly approves it:
1200
+ - \`shadow_ops_tribunal_submit({ repoPath, missionId })\`
1201
+ - \`shadow_ops_tribunal_status({ repoPath, missionId })\`
1202
+ - Release any claims you took:
1203
+ - \`shadow_ops_release({ repoPath, missionId, filePaths? })\`
1204
+ - Complete the mission:
1205
+ - \`shadow_ops_track({ repoPath, missionId, status: "completed" })\`
1206
+
1207
+ ## Rules
1208
+
1209
+ - Don't do one step and stop \u2014 /continue is "finish a mission," not "do one step."
1210
+ - Don't call \`shadow_ops_synthesize\` after completion unless you are intentionally regenerating the record.
1211
+ - Never run Tribunal without explicit user consent.
1212
+ - \`shadow_ops_handoff\` does not take \`role\` or \`summary\`; use \`kind\` plus structured \`findings\`.
1213
+ - \`shadow_ops_crystallize_theme\` takes \`theme\`, not \`query\`.
1214
+ `,shadow_coordinate:`---
1215
+ name: coordinate
1216
+ description: Coordinate multi-agent or parallel work with working-set checks, file claims, dispatch waves, handoffs, and user-approved Tribunal review. Use when several agents may edit at once or when work must be transferred cleanly.
1217
+ ---
1102
1218
 
1103
- - A mission has **10+ raw intent logs** and briefings are getting verbose.
1104
- - Mid-mission, before requesting a detailed briefing \u2014 keeps \`atmosphere\` altitude lean.
1105
- - Before synthesis (optional) \u2014 produces cleaner ADRs from compressed input.
1106
- - The briefing at \`atmosphere\` altitude already prefers crystals over raw logs (\`findByMissionPreferCrystal\`), so crystallizing makes those briefings significantly leaner.
1219
+ # Coordinate
1107
1220
 
1108
- ## Workflow
1221
+ Use this skill when execution risk comes from overlap, not code complexity.
1109
1222
 
1110
- 1. **Crystallize**: \`shadow_ops_crystallize\` (missionId, repoPath) \u2014 Compresses all raw logs into one crystal node. Raw logs are marked as \`absorbed\`.
1111
- 2. **Verify**: \`shadow_ops_briefing\` (scope: "mission", missionId, altitude: "atmosphere", repoPath) \u2014 Crystal should appear in \`recent_activity\` instead of raw logs.
1223
+ ## Conflict control
1112
1224
 
1113
- ## Precise Tooling
1225
+ - \`shadow_working_set_check({ repoPath, filePaths })\`
1226
+ - \`shadow_ops_claim({ repoPath, missionId, filePaths, agentTag? })\`
1227
+ - \`shadow_ops_release({ repoPath, missionId, filePaths? })\`
1114
1228
 
1115
- | Action | Atomic Tool | Usage |
1116
- | :--------------- | :--------------------------------------------- | :-------------------------------------- |
1117
- | **Crystallize** | \`shadow_ops_crystallize\` | missionId, repoPath \u2014 compress raw logs |
1118
- | **Check Status** | \`shadow_ops_briefing\` (altitude: "atmosphere") | Verify crystal appears in activity |
1119
- | **Full Logs** | \`shadow_ops_briefing\` (altitude: "ground") | Still shows raw logs if needed |
1229
+ ## Parallel planning
1120
1230
 
1121
- ## What the Crystal Contains
1231
+ - \`shadow_ops_dispatch_plan({ repoPath, parentMissionId?, missionIds?, includeClaimCheck: true })\`
1232
+ - \`shadow_ops_graph({ repoPath, missionId, depth?, format: "mermaid" | "json" })\`
1122
1233
 
1123
- - Mission name and ID
1124
- - Count of compressed logs and symbols
1125
- - Log types present (decision, fix, discovery, blocker)
1126
- - Structured breakdown: decisions, context, consequences, recommendations
1234
+ ## Handoffs
1127
1235
 
1128
- ## Notes
1236
+ - Write: \`shadow_ops_handoff({ repoPath, missionId?, kind, findings, risks?, gaps?, missionsCreated?, confidence?, agentTag? })\`
1237
+ - Read: \`shadow_ops_handoff_read({ repoPath, missionId?, kind?, query?, limit? })\`
1129
1238
 
1130
- - Crystallization is **idempotent**: if no new raw logs exist, it reports \`already_crystallized\`.
1131
- - New logs added after crystallization remain as raw until the next crystallize call.
1132
- - Raw logs are **not deleted** \u2014 they're marked as absorbed. \`ground\` altitude still shows them.
1133
- `,shadow_mission:`---
1134
- name: mission
1135
- description: Define the objective, strategy, and success criteria for a new development mission. Use when planning strategic initiatives, creating missions, setting up development goals, or when the user asks about mission planning, strategic alignment, or outcome contracts.
1136
- ---
1239
+ Available \`kind\` values:
1137
1240
 
1138
- # Mission Strategy & Setup
1241
+ - \`recon_report\`
1242
+ - \`risk_assessment\`
1243
+ - \`impact_map\`
1244
+ - \`debt_scan\`
1245
+ - \`custom\`
1139
1246
 
1140
- Define the objective, strategy, and success criteria for a new mission. This workflow is for **Strategic Alignment and Planning**.
1247
+ ## Tribunal
1141
1248
 
1142
- > **IMPORTANT**: This workflow stops at the "Ready to Execute" state. For implementation and automated execution, use **/continue**.
1249
+ Never run Tribunal unless the user explicitly asks for it or clearly approves it.
1143
1250
 
1144
- ## Workflow
1251
+ - \`shadow_ops_tribunal_submit({ repoPath, missionId })\`
1252
+ - \`shadow_ops_tribunal_status({ repoPath, missionId? or sessionId? })\`
1145
1253
 
1146
- 1. **Session Context**: \`shadow_ops_context\` (repoPath) \u2014 **ONE CALL** for hologram + chronicle(5) + briefing (with relevance-ranked \`next_work_candidates\`). Check existing candidates and recent decisions before creating new work.
1147
- 2. **Optional Expanded Context** (only if needed):
1148
- - \`shadow_recon_topography\` (repoPath) \u2014 Detailed layer breakdown to align goal with architecture.
1149
- - \`shadow_ops_chronicle\` (limit: 10, repoPath) \u2014 More historical ADRs if 5 isn't enough.
1150
- - \`shadow_ops_briefing\` (scope: "project", altitude: "ground", repoPath) \u2014 Full detail with analytics, collisions, and working sets.
1151
- 3. **Strategic Plan**: \`shadow_ops_plan\` (name, goal, outcomeContract, ...).
1152
- - **Strategy DAG**: Define logical steps and verification rules.
1153
- - **Initiative vs Mission**: Decide if this is a parent (Initiative) or a leaf (Mission). Parent missions auto-complete via cascade when all children finish.
1154
- 4. **Alignment**: Present the plan to the user. Do not begin execution until the user approves the strategy.
1254
+ ## Rules
1155
1255
 
1156
- ## Precise Tooling
1256
+ - Claim only the files you expect to edit.
1257
+ - Release claims promptly when the work is done.
1258
+ - Tribunal is opt-in only. Treat it as a user-consent gate, not an automatic review step.
1259
+ - Handoffs must be structured. There is no \`role\` or \`summary\` field.
1260
+ `,shadow_crystallize:`---
1261
+ name: crystallize
1262
+ description: Compress a mission's intent logs into a dense crystal summary for token-efficient briefings. Use when a mission has accumulated many raw logs, when briefings are too verbose, or when the user asks about log compression, crystallization, or context reduction.
1263
+ ---
1157
1264
 
1158
- | Setup Action | Precise Tool Call | Usage |
1159
- | :-------------------- | :----------------------------------------- | :-------------------------------------------------------------------------------------------------- |
1160
- | **Session Start** | \`shadow_ops_context\` | **START HERE** \u2014 hologram + chronicle + briefing in one call |
1161
- | **Establish Plan** | \`shadow_ops_plan\` | Create the mission and strategy. |
1162
- | **Architectural Map** | \`shadow_recon_topography\` | Contextualize the target layers (if context wasn't enough). |
1163
- | **Detailed Briefing** | \`shadow_ops_briefing\` (altitude: "ground") | Full analytics, collisions, working sets. |
1164
- | **Lean Briefing** | \`shadow_ops_briefing\` (altitude: "orbit") | Counts + candidates only (~200 tokens). |
1165
- | **Graph View** | \`shadow_ops_graph\` | Visualize the initiative's hierarchy. |
1166
- | **Theme Patterns** | \`shadow_ops_crystallize_theme\` | Before planning: surface recurring themes across past missions to avoid repeating solved problems. |
1167
- | **Prior Handoffs** | \`shadow_ops_handoff_read\` | In multi-agent contexts: retrieve typed findings from a prior RECON agent before defining strategy. |
1168
- | **Event Mesh** | \`shadow_analyze_mesh\` | When planning event-driven or API work: map all HTTP routes, socket events, pubsub topics. |
1265
+ # Crystallize
1169
1266
 
1170
- _Note: **Always start with \`shadow_ops_context\`** for instant mission landscape + architectural context. Ensure the \`outcomeContract\` is binary and verifiable. Parent initiatives auto-cascade on child completion \u2014 no manual closing needed._
1267
+ Compress raw intent logs into a crystal so briefings stay useful instead of noisy.
1171
1268
 
1172
- ## Briefing Altitude Levels
1269
+ ## Core calls
1173
1270
 
1174
- - **\`orbit\`** (~200 tokens): Counts + relevance-ranked candidates only. Use for quick checks.
1175
- - **\`atmosphere\`** (default): Strategy graphs, crystal summaries, hierarchy, analytics.
1176
- - **\`ground\`** (full): Raw logs, working sets, collision analysis, ancestor activity.
1271
+ - Mission-level compression: \`shadow_ops_crystallize({ repoPath, missionId })\`
1272
+ - Verify the result: \`shadow_ops_briefing({ repoPath, scope: "mission", missionId, altitude: "atmosphere" })\`
1273
+ - Cross-mission theme compression: \`shadow_ops_crystallize_theme({ repoPath, theme, missionIds?, limit? })\`
1177
1274
 
1178
- ## Intent Logging (Strategic Quality)
1275
+ ## When to use it
1179
1276
 
1180
- Capture the "Why" and "How" during the planning phase to ensure the final ADR has architectural depth.
1277
+ - A mission has many raw logs and \`atmosphere\` briefings are getting bloated.
1278
+ - You want cleaner synthesis input before closing a mission.
1279
+ - You want to surface repeating patterns across missions with \`theme\`.
1181
1280
 
1182
- - **Decision Logs**: Capture why a specific strategy or library was chosen.
1183
- - **Discovery Logs**: Record insights found during initial reconnaissance.
1281
+ ## Notes
1184
1282
 
1185
- **Hand-off**: Once the mission is planned and logged, the setup phase is over. Execute via \`/continue\`.
1186
- `,shadow_onboard:'---\nname: onboard\ndescription: Initialize and analyze a new repository for deep intelligence by building semantic index, syncing state, activating git hooks, and establishing missions. Use when onboarding to a new repository, initializing Shadow Engine, setting up git hooks, or when the user asks about repository setup, initialization, or first-time configuration.\n---\n\n# Repository Onboarding\n\nInitialize and analyze a new repository for deep intelligence.\n\n## Workflow\n\n1. **Semantic Init**: `shadow_recon_onboard` (repoPath) \u2014 **Only run once** per repo to build the baseline. Auto-populates the hologram.\n2. **Read Hologram**: `shadow_recon_hologram` (repoPath) \u2014 Get instant architectural context (~1300 tokens: topography + gravity zones).\n3. **Unified Sync**: `shadow_sync_trace` (repoPath) \u2014 **The One-Stop Shop**. Performs indexing + ghost analysis + mission re-hydration.\n4. **Active Briefing**: `shadow_ops_briefing` (scope: "project", altitude: "atmosphere", repoPath) \u2014 Resumes the shared backlog with relevance-ranked candidates.\n - Use `altitude: "orbit"` for a lean overview (~200 tokens), or `altitude: "ground"` for full detail.\n5. **Architectural Deep Dive** (optional):\n - `shadow_recon_topography` (repoPath) \u2014 View layers (Entry/Logic/Data/Utility/Test).\n - `shadow_ops_chronicle` (limit: 5, repoPath) \u2014 Narrative feed.\n - `shadow_analyze_mesh` (repoPath) \u2014 If repo is event-driven: map HTTP routes, socket events, pubsub topics immediately.\n - `shadow_env_diagnose` (repoPath) \u2014 Verify environment health: hooks installed, index state, ember daemon status.\n6. **Hooks Activation**: `shadow_env_hooks` (action: "install", repoPath) \u2014 installs post-commit and **post-checkout** hooks. Post-checkout fires incremental reindex in background on every branch switch.\n7. **Establish Mission**: `shadow_ops_plan` (name, goal, repoPath).\n\n## Precise Tooling\n\n| Action | Atomic Tool |\n| :---------------- | :----------------------------------------------------------------------------------- |\n| **Index** | `shadow_recon_onboard` |\n| **Hologram** | `shadow_recon_hologram` (repoPath) |\n| **Layers** | `shadow_recon_topography` |\n| **History** | `shadow_ops_chronicle` (limit: 10) |\n| **Resume (lean)** | `shadow_ops_briefing` (scope: "project", altitude: "orbit") |\n| **Resume (full)** | `shadow_ops_briefing` (scope: "project", altitude: "atmosphere") |\n| **Hooks** | `shadow_env_hooks` (action: "install") |\n| **Env Health** | `shadow_env_diagnose` (repoPath) \u2014 hooks status, index state, ember warming progress |\n| **Event Mesh** | `shadow_analyze_mesh` (repoPath) \u2014 event-driven repos: routes + topics surface |\n\n_Note: Always use absolute paths for `repoPath`. Call `shadow_recon_hologram` immediately after init for instant architectural context. `shadow_env_hooks` now installs both post-commit and post-checkout hooks \u2014 branch switches will auto-reindex in background via Ember daemon._\n',shadow_research:`---
1283
+ - Crystallization is **idempotent**: if no new raw logs exist, it reports \`already_crystallized\`.
1284
+ - Raw logs are not deleted; they are marked as absorbed.
1285
+ - New logs stay raw until the next crystallize call.
1286
+ - \`shadow_ops_crystallize_theme\` takes \`theme\`, not \`query\`.
1287
+ `,shadow_mission:'---\nname: mission\ndescription: Define the objective, strategy, and success criteria for a mission. Use when planning new work, shaping initiatives, writing outcome contracts, or aligning a task before execution starts.\n---\n\n# Mission\n\nThis skill is for planning. It stops at "ready to execute."\n\n## Start\n\n1. `shadow_ops_context({ repoPath, compact: true })`\n2. If needed, expand with:\n - `shadow_recon_topography({ repoPath })`\n - `shadow_ops_briefing({ repoPath, scope: "project", altitude: "ground" })`\n - `shadow_ops_chronicle({ repoPath, limit: 10 })`\n3. Reuse prior intelligence when available:\n - `shadow_ops_handoff_read({ repoPath, missionId?, kind?, query? })`\n - `shadow_ops_crystallize_theme({ repoPath, theme, missionIds? })`\n\n## Create the mission\n\nUse `shadow_ops_plan` with the fields that matter:\n\n- `name`: short, concrete title\n- `goal`: what changes and why\n- `outcomeContract`: binary success test\n- `strategy`: JSON step graph when the work has multiple stages\n- `workingSet`: expected files or directories\n- `templateId`: `refactoring`, `feature`, or `bug-fix`\n- `parentId`: when this mission belongs under an initiative\n\n## Planning rules\n\n- Prefer a leaf mission when one deliverable can be completed in one run.\n- Use a parent initiative only when the work is intentionally split into child missions.\n- Keep `outcomeContract` verifiable. "Looks good" is not a contract.\n- If API or event boundaries matter, use `shadow_analyze_mesh({ repoPath, topic, type? })` with a concrete route or topic fragment.\n- Present the plan for approval before execution. Use `/continue` for the actual implementation pass.\n',shadow_onboard:'---\nname: onboard\ndescription: Initialize and analyze a repository for Shadow workflows. Use when onboarding a repo, bootstrapping indexes and hooks, checking intelligence health, or preparing the first mission.\n---\n\n# Onboard\n\nUse this skill when a repository needs its first Shadow pass or when a fresh clone needs to be made operational.\n\n## Core workflow\n\n1. `shadow_recon_onboard({ repoPath })`\n2. `shadow_recon_hologram({ repoPath, compact: true })`\n3. `shadow_sync_trace({ repoPath })`\n4. `shadow_ops_health({ repoPath })`\n5. `shadow_ops_context({ repoPath, compact: true })`\n\n## Useful follow-ups\n\n- `shadow_recon_topography({ repoPath })` for layer breakdown.\n- `shadow_ops_chronicle({ repoPath, limit: 5 })` for recent decisions.\n- `shadow_env_diagnose({ repoPath })` for hooks, index, and daemon health.\n- `shadow_env_hooks({ repoPath, action: "install", enableAutoRefresh: true, enableSymbolHealing: true })`\n- `shadow_ops_plan({ repoPath, name, goal, outcomeContract? })` for the first mission.\n\n## Rules\n\n- Always use an absolute `repoPath`.\n- `shadow_recon_onboard` is the baseline bootstrap; `shadow_sync_trace` is the normal follow-up maintenance pass.\n- Do not call `shadow_analyze_mesh` without a concrete `topic`.\n',shadow_research:`---
1187
1288
  name: research
1188
- description: Conduct high-signal research for external dependencies by combining local context, web search, and Context7 documentation. Use when researching libraries, checking integration examples, verifying versions, or when the user asks about external dependencies, library documentation, or integration patterns.
1289
+ description: Research external dependencies without losing local context. Use when checking library usage, verifying versions, finding integration examples, or comparing official documentation against what the repo already does.
1189
1290
  ---
1190
1291
 
1191
- # External Research
1192
-
1193
- High-signal research for external dependencies.
1292
+ # Research
1194
1293
 
1195
- ## \u{1F680} Workflow
1294
+ Start local, then verify externally.
1196
1295
 
1197
- 1. **Local Context**: \`shadow_search_concept\` (query: "library name", repoPath). Find existing integration examples.
1198
- 2. **Web Search**: Use the \`WebSearch\` tool for official docs and latest versions.
1199
- 3. **Deep Intel (Context7)**: resolve-library-id, query-docs (server: user-context7).
1200
- 4. **Integration Check**: \`shadow_inspect_file\` (filePath, detailLevel: "signatures", repoPath).
1201
- 5. **Log Findings**: \`shadow_ops_log\` (type: "discovery", content, repoPath).
1296
+ ## Local first
1202
1297
 
1203
- ## \u{1F6E0} Precise Tooling
1298
+ - \`shadow_search_concept({ repoPath, query, compact: true })\` for existing patterns.
1299
+ - \`shadow_search_path({ repoPath, query, ranked: true })\` for likely integration files.
1300
+ - \`shadow_search_config({ repoPath, key?, query?, showUsage: true })\` for env and config hooks.
1301
+ - \`shadow_analyze_deps({ repoPath, filePath, direction: "imports" | "imported_by" })\` to see how the dependency sits in the graph.
1302
+ - \`shadow_inspect_file({ repoPath, filePath, detailLevel: "signatures" })\` for a quick local API read.
1204
1303
 
1205
- | Discovery Layer | Atomic Tool |
1206
- | :----------------- | :-------------------------------------------------------------------------- |
1207
- | **Local Usage** | \`shadow_search_concept\` (query, **compact: true** for broad search) |
1208
- | **File Discovery** | \`shadow_search_path\` (query, **ranked: true**) \u2014 gravity-sorted with layers |
1209
- | **Config Check** | \`shadow_search_config\` (key, **showUsage: true**) \u2014 with usage counts |
1210
- | **External Docs** | context7 tools (user-context7) |
1211
- | **Relational** | \`shadow_analyze_deps\` (filePath, direction) |
1304
+ ## External verification
1212
1305
 
1213
- ## \u{1F4A1} Intelligence Options
1306
+ - Use the host model's documentation or web tools to read official vendor docs and primary sources.
1307
+ - Check the exact installed version in \`package.json\`, lockfiles, or existing imports before trusting examples.
1308
+ - Prefer official docs over blogs, and repo-local patterns over generic snippets.
1214
1309
 
1215
- - **\`shadow_search_concept\` with \`compact: true\`**: Returns file paths + scores without snippets (~60% token savings). Use for broad exploration.
1216
- - **\`shadow_search_path\` with \`ranked: true\`**: Results sorted by gravity (high-import files first) with layer classification. Reveals architecturally important files.
1217
- - **\`shadow_search_config\` with \`showUsage: true\`**: Shows usage counts per config var and identifies orphaned vars (defined but never used in code).
1310
+ ## Closeout
1218
1311
 
1219
- _Note: Always check \`package.json\` for the exact version before querying Context7 to ensure documentation alignment._
1312
+ - \`shadow_ops_log({ repoPath, missionId?, type: "discovery", content, filePath? })\` when the research affects an ongoing mission.
1220
1313
  `,shadow_sync:`---
1221
1314
  name: sync
1222
1315
  description: 'Sync index and mission state after external changes. Day-to-day: index + NanoRepair run automatically when MCP tools (search, inspect, etc.) trigger reindex. Use trace after git pull/checkout/merge (or rely on hooks); use index deep:true for full rebuild.'
1223
1316
  ---
1224
1317
 
1225
- # Repository Synchronization
1318
+ # Sync
1226
1319
 
1227
- **Day-to-day:** Index and NanoRepair run automatically when you use MCP tools (search, inspect, analyze, etc.) and a reindex occurs. No manual sync needed for edits or renames.
1320
+ Day-to-day, Shadow often reindexes on demand. Use manual sync when the repository changed outside the normal flow.
1228
1321
 
1229
- ## When to run sync manually
1322
+ ## Prefer these calls
1230
1323
 
1231
- | Situation | Action |
1232
- | :-------------------------------- | :----------------------------------------------------------------- |
1233
- | **After git pull/checkout/merge** | \`shadow_sync_trace\` (repoPath) \u2014 or rely on Git hooks if installed |
1234
- | **Full rebuild (corruption)** | \`shadow_sync_index\` (repoPath; use deep: true if supported) |
1235
- | **Repair only (rare)** | \`shadow_sync_repair\` (repoPath) |
1324
+ - After \`pull\`, \`checkout\`, \`merge\`, or large rebases:
1325
+ - \`shadow_sync_trace({ repoPath, sinceCommit?, enableContextPivot?, enableMergeSentinel? })\`
1326
+ - For an explicit rebuild:
1327
+ - \`shadow_sync_index({ repoPath, deep: true })\`
1328
+ - For repair only:
1329
+ - \`shadow_sync_repair({ repoPath })\`
1236
1330
 
1237
- **Note:** \`trace\` does index + ghost analysis + NanoRepair + lifecycle + mission re-hydration. Hooks run it on commit/checkout/merge.
1331
+ ## Health checks
1332
+
1333
+ - \`shadow_ops_health({ repoPath })\`
1334
+ - \`shadow_env_diagnose({ repoPath })\`
1335
+
1336
+ ## Rules
1337
+
1338
+ - Prefer \`shadow_sync_trace\` over \`shadow_sync_index\` unless you specifically want a rebuild.
1339
+ - Use \`deep: true\` sparingly; it is the expensive option.
1238
1340
  `,shadow_synthesize:`---
1239
1341
  name: synthesize
1240
1342
  description: Distill mission logs into Architectural Decision Records (ADRs) and persist them to the Shadow Engine and Git Notes. Use when completing missions, creating ADRs, synthesizing architectural decisions, or when the user asks about decision records, mission completion, or architectural documentation.
1241
1343
  ---
1242
1344
 
1243
- # Architectural Synthesis
1345
+ # Synthesize
1346
+
1347
+ Use this skill when a mission needs to become durable project memory.
1244
1348
 
1245
- Distill mission logs into an Architectural Decision Record (ADR) and persist it to the Shadow Engine.
1349
+ ## Primary path
1246
1350
 
1247
- > **AUTO-PILOT ACTIVE**: Synthesis is **automatically triggered** when a mission status is set to \`completed\` via \`shadow_ops_track\`. The system handles: ADR distillation (recursive for child missions), Git Notes persistence, and **cascade parent completion** (if all siblings are done, the parent auto-completes and synthesizes too).
1351
+ - Complete the mission:
1352
+ - \`shadow_ops_track({ repoPath, missionId, status: "completed" })\`
1353
+ - Verify the synthesized record:
1354
+ - \`shadow_ops_chronicle({ repoPath, limit: 5 })\`
1248
1355
 
1249
- ## Workflow
1356
+ ## Secondary tools
1250
1357
 
1251
- 1. **Complete Mission**: \`shadow_ops_track\` (missionId, status: "completed", repoPath).
1252
- - The Shadow Engine will automatically:
1253
- - Distill all intent logs (recursive for child missions).
1254
- - Format the ADR using markdown and **Liquid Anchors**.
1255
- - Persist the record to SQLite and **Git Notes**.
1256
- - **Cascade**: If all sibling missions under the same parent are completed, the parent mission auto-completes with its own ADR synthesis.
1257
- 2. **Verify**: Check the synthesized record via \`shadow_ops_chronicle\` (limit: 5, repoPath).
1258
- 3. **Manual Synthesis**: Use \`shadow_ops_synthesize\` only to **re-generate** an existing record or for specific partial distillations.
1259
- 4. **Pre-synthesis Compression** (optional): For missions with many raw logs, \`shadow_ops_crystallize\` (missionId, repoPath) compresses logs into a crystal summary before synthesis for cleaner ADRs.
1358
+ - \`shadow_ops_synthesize({ repoPath, missionId })\` only when you need to regenerate the ADR after the mission is already complete.
1359
+ - \`shadow_ops_crystallize({ repoPath, missionId })\` before completion if the mission has many raw logs.
1360
+ - \`shadow_ops_crystallize_theme({ repoPath, theme, missionIds? })\` when you want a cross-mission architectural thread.
1260
1361
 
1261
- ## Precise Tooling
1362
+ ## Rules
1262
1363
 
1263
- | Action | Atomic Tool | Usage |
1264
- | :-------------------- | :--------------------------------------- | :---------------------------------------------------------------- |
1265
- | **Complete & Seal** | \`shadow_ops_track\` (status: "completed") | **Primary**. Triggers auto-synthesis + cascade. |
1266
- | **Manual Distill** | \`shadow_ops_synthesize\` | Re-run synthesis manually (re-gen only). |
1267
- | **Crystallize First** | \`shadow_ops_crystallize\` | Compress raw logs before synthesis. |
1268
- | **Theme Crystallize** | \`shadow_ops_crystallize_theme\` | Cross-mission: cluster semantic themes across ALL missions' logs. |
1269
- | **View Chronicle** | \`shadow_ops_chronicle\` | View the combined narrative feed. |
1364
+ - Completion auto-triggers synthesis and parent cascade behavior.
1365
+ - Do not maintain parallel ADR markdown files unless the user explicitly wants one.
1366
+ `,shadow_trace_impact:`---
1367
+ name: trace-impact
1368
+ description: Map the blast radius of a change by analyzing impact, flow traces, cross-repo dependencies, and boundary maps. Use when analyzing change impact, assessing risk, tracing dependencies, or when the user asks about change impact, blast radius, or dependency analysis.
1369
+ ---
1270
1370
 
1271
- _Note: Synthesis consolidation includes all child missions recursively. Cascade parent completion propagates upward through the entire hierarchy._
1371
+ # Trace Impact
1272
1372
 
1273
- ## Cascade Parent Completion
1373
+ Use this skill to answer "what breaks if we touch this?"
1274
1374
 
1275
- When the last child mission under a parent is completed:
1375
+ ## Core workflow
1276
1376
 
1277
- 1. Parent status is set to \`completed\`
1278
- 2. A system intent log records the cascade event
1279
- 3. Parent ADR is synthesized (recursive child distillation)
1280
- 4. Parent is synced to Git Notes
1281
- 5. If the parent itself has a parent, the cascade continues upward
1377
+ 1. \`shadow_ops_context({ repoPath, compact: true })\`
1378
+ 2. \`shadow_analyze_impact({ repoPath, symbolName, filePath?, depth: 3 })\`
1379
+ 3. \`shadow_analyze_deps({ repoPath, filePath, direction: "imported_by" })\`
1380
+ 4. \`shadow_analyze_deps({ repoPath, filePath, direction: "imports" })\`
1381
+ 5. \`shadow_analyze_flow({ repoPath, filePath, symbolName? })\`
1282
1382
 
1283
- ## Tooling Strategy
1383
+ ## Add precision
1284
1384
 
1285
- Synthesis is the final commit of the mission's logic into the repository's permanent history. Avoid manual markdown files for ADRs; trust the **Git Notes** architecture to preserve the "Story of the Code."
1286
- `,shadow_trace_impact:`---
1287
- name: trace-impact
1288
- description: Map the blast radius of a change by analyzing impact, flow traces, cross-repo dependencies, and boundary maps. Use when analyzing change impact, assessing risk, tracing dependencies, or when the user asks about change impact, blast radius, or dependency analysis.
1385
+ - \`shadow_analyze_explain_diff({ repoPath, baseCommit?, headCommit?, staged? })\` for a semantic read of an actual diff.
1386
+ - \`shadow_analyze_type_graph({ repoPath, symbolName, filePath?, direction?, relationship? })\` when the change is type-heavy.
1387
+ - \`shadow_analyze_debt({ repoPath, mode: "circular-deps" })\` for cycle risk.
1388
+ - \`shadow_recon_topography({ repoPath })\` for layer-crossing risk.
1389
+ - \`shadow_workspace_fuse({ repoPaths, name? })\` before cross-repo analysis.
1390
+ - \`shadow_analyze_mesh({ repoPath, topic, includeCrossRepo: true })\` when the affected boundary is a known route or event.
1391
+
1392
+ ## Closeout
1393
+
1394
+ - \`shadow_ops_log({ repoPath, missionId?, type: "discovery", content, symbolName?, filePath? })\`
1395
+ - \`shadow_ops_handoff({ repoPath, missionId?, kind: "impact_map", findings, risks?, gaps? })\`
1396
+
1397
+ ## Rules
1398
+
1399
+ - Keep \`depth: 3\` by default; only widen for foundational primitives.
1400
+ - \`shadow_analyze_mesh\` requires a concrete \`topic\`.
1401
+ `,shadow_understand:`---
1402
+ name: understand
1403
+ description: Find the high-signal path to understanding complex logic through intent retrieval, topological placement, relational analysis, and mechanics inspection. Use when understanding architecture, analyzing complex code, tracing logic flow, or when the user asks about how something works, architectural patterns, or code comprehension.
1289
1404
  ---
1290
1405
 
1291
- # Impact Analysis
1292
-
1293
- Map the blast radius of a change using the full Shadow analyze toolkit.
1294
-
1295
- ## \u{1F680} Workflow
1296
-
1297
- 1. **Session Context**: \`shadow_ops_context\` (repoPath) \u2014 **ONE CALL** for hologram + chronicle + briefing. Check if symbol is in gravity zones.
1298
- 2. **Impact (Blast Radius)**: \`shadow_analyze_impact\` (symbolName, filePath, depth: 3, repoPath) \u2014 ALL affected files.
1299
- 3. **Dependencies**:
1300
- - \`shadow_analyze_deps\` (filePath, direction: "imported_by", repoPath) \u2014 Who imports this?
1301
- - \`shadow_analyze_deps\` (filePath, direction: "imports", repoPath) \u2014 What does it import?
1302
- 4. **Flow Trace**: \`shadow_analyze_flow\` (symbolName, filePath, repoPath) \u2014 Execution path.
1303
- 5. **Health Check**:
1304
- - \`shadow_analyze_debt\` (mode: "circular-deps", repoPath) \u2014 Any import cycles?
1305
- - \`shadow_analyze_debt\` (mode: "dead-code", limit: 50, repoPath) \u2014 Unused exports?
1306
- 6. **Cross-Repo Check** (if multi-repo):
1307
- - \`shadow_workspace_fuse\` (repoPaths, repoPath).
1308
- - \`shadow_search_symbol\` (query, limit: 50, repoPath).
1309
- 7. **Boundary Map**: \`shadow_recon_topography\` (repoPath) \u2014 Layer crossing check.
1310
- 8. **Log Risk**: \`shadow_ops_log\` (missionId, type: "discovery", content, symbolName, repoPath).
1311
-
1312
- ## \u{1F6E0} Precise Tooling
1313
-
1314
- | Impact Layer | Atomic Tool |
1315
- | :------------------- | :------------------------------------------------------------------------- |
1316
- | **Session Start** \u{1F680} | \`shadow_ops_context\` (repoPath) \u2014 **START HERE** for context |
1317
- | **Hologram** | \`shadow_recon_hologram\` (repoPath) \u2014 if you need standalone |
1318
- | **Blast Radius** | \`shadow_analyze_impact\` (symbolName, depth: 3) |
1319
- | **Dependents** | \`shadow_analyze_deps\` (filePath, direction: "imported_by") |
1320
- | **Dependencies** | \`shadow_analyze_deps\` (filePath, direction: "imports") |
1321
- | **Flow Path** | \`shadow_analyze_flow\` (symbolName, filePath) |
1322
- | **Circular Deps** | \`shadow_analyze_debt\` (mode: "circular-deps") |
1323
- | **Dead Code** | \`shadow_analyze_debt\` (mode: "dead-code", **confidenceThreshold: "high"**) |
1324
- | **File Discovery** | \`shadow_search_path\` (query, **ranked: true**) \u2014 gravity-sorted |
1325
- | **Workspace Fuse** | \`shadow_workspace_fuse\` (repoPaths, repoPath) |
1326
- | **Topography** | \`shadow_recon_topography\` |
1327
-
1328
- ## \u{1F4A1} Intelligence Options
1329
-
1330
- - **\`shadow_search_path\` with \`ranked: true\`**: Find related files sorted by gravity (high-import files first) with layer classification. Helps identify which affected files are architecturally critical.
1331
- - **\`shadow_analyze_debt\` confidence levels**: Use \`confidenceThreshold: "high"\` to focus on likely dead code, avoiding noise from test fixtures and migrations.
1332
-
1333
- _Note: **Start with \`shadow_ops_context\`** for instant gravity zones + architectural context. Use depth higher than 3 for impact analysis only if the symbol is a fundamental primitive (e.g., RepositoryFactory)._
1334
-
1335
- ## \u{1F6E0} Risk Classification
1336
-
1337
- - **Critical Risk**: Symbol in gravity zones (top 10) + >20 dependents + crosses layers
1338
- - **High Risk**: >10 dependents OR crosses layers (e.g., Test -> Logic)
1339
- - **Medium Risk**: 5-10 dependents within same layer
1340
- - **Low Risk**: <5 dependents, same layer, no circular deps
1341
- `,shadow_understand:'---\nname: understand\ndescription: Find the high-signal path to understanding complex logic through intent retrieval, topological placement, relational analysis, and mechanics inspection. Use when understanding architecture, analyzing complex code, tracing logic flow, or when the user asks about how something works, architectural patterns, or code comprehension.\n---\n\n# Architectural Understanding\n\nFind the high-signal path to understanding complex logic.\n\n## Workflow\n\n1. **Session Context (The Fast Lane)**: `shadow_ops_context` (repoPath) \u2014 **ONE CALL** returns hologram + chronicle(5) + briefing (relevance-ranked candidates).\n - Skip to step 3 if you have what you need from context alone.\n2. **Optional Expanded Context** (only if shadow_ops_context wasn\'t enough):\n - `shadow_recon_topography` (repoPath) \u2014 Detailed layer breakdown beyond hologram summary.\n - `shadow_recon_tree` (subPath: "src/services", maxDepth: 2, repoPath) \u2014 Visual file hierarchy.\n - `shadow_ops_briefing` (scope: "mission", missionId, altitude: "ground") \u2014 Full mission detail with raw logs, working set, collisions.\n3. **Relational Analysis (The Who)**:\n - `shadow_analyze_impact` (symbolName, filePath, depth: 3, repoPath) \u2014 Blast radius.\n - `shadow_analyze_deps` (filePath, direction: "imported_by", repoPath) \u2014 Who depends on this?\n - `shadow_search_concept` (query, repoPath) \u2014 Semantic search.\n - `shadow_analyze_mesh` (repoPath) \u2014 When the system is event-driven: map all HTTP routes, socket events, pubsub topics and their producers/consumers.\n - `shadow_analyze_type_graph` (filePath, repoPath) \u2014 When understanding a type system: interface/class inheritance chains.\n4. **Mechanics (The How)**:\n - **For Logic**: `shadow_analyze_flow` (symbolName, filePath, repoPath) \u2014 Trace execution.\n - **For Objects**: `shadow_inspect_file` (filePath, detailLevel: "signatures", repoPath) \u2014 All exports.\n - **For Symbol Deep Dive**: `shadow_inspect_symbol` (symbolName, filePath, context: "full", repoPath) \u2014 With deps.\n - **For Change History**: `shadow_analyze_explain_diff` (fromCommit, toCommit, repoPath) \u2014 Semantic narrative of what changed and why between commits.\n5. **Synthesis**: `shadow_ops_log` (missionId, type: "discovery", content, symbolName, repoPath).\n\n## Precise Tooling\n\n| Discovery Layer | Atomic Tool |\n| :----------------- | :--------------------------------------------------------------------------------------------------- |\n| **Session Start** | `shadow_ops_context` (repoPath) \u2014 **START HERE** |\n| **Hologram** | `shadow_recon_hologram` (repoPath) \u2014 if you need standalone hologram |\n| **History** | `shadow_ops_chronicle` (limit: 5) \u2014 if you need more than 5 from context |\n| **Layers** | `shadow_recon_topography` \u2014 detailed breakdown |\n| **Mission Detail** | `shadow_ops_briefing` (altitude: "ground") \u2014 full logs + working set |\n| **Blast Radius** | `shadow_analyze_impact` (symbolName, depth: 3) |\n| **Dependents** | `shadow_analyze_deps` (filePath, direction: "imported_by") |\n| **Flow Trace** | `shadow_analyze_flow` (symbolName, filePath) |\n| **Structure** | `shadow_inspect_file` (detailLevel: "signatures") |\n| **Deep Dive** | `shadow_inspect_symbol` (context: "full") |\n| **File Discovery** | `shadow_search_path` (query, **ranked: true**) \u2014 gravity-sorted results with layer classification |\n| **Event Mesh** | `shadow_analyze_mesh` (repoPath) \u2014 HTTP routes, socket events, pubsub topics + producers/consumers |\n| **Type Graph** | `shadow_analyze_type_graph` (filePath) \u2014 interface/class inheritance chains |\n| **Explain Diff** | `shadow_analyze_explain_diff` (fromCommit, toCommit) \u2014 semantic narrative of changes between commits |\n\n_Note: **ALWAYS start with `shadow_ops_context`** for instant architectural context + history + mission state in ONE call. Use `context: "definition"` for token-efficient single symbol inspection._\n\n## Intelligence Options\n\n- **`shadow_search_path` with `ranked: true`**: Results sorted by gravity (high-import files first) with layer classification (Entry/Logic/Data). Use when you need to find the most architecturally important files matching a pattern.\n- **`shadow_search_concept` with `compact: true`**: Omits code snippets for ~60% token savings. Use for broad exploration before deep dives.\n- **Briefing altitude levels**: Use `orbit` for quick status, `atmosphere` for strategy + crystals, `ground` for raw logs + collisions.\n- **`shadow_ops_crystallize`**: If a mission has excessive raw logs, crystallize them first for leaner briefings.\n',shadow_workspace:`---
1406
+ # Understand
1407
+
1408
+ Use this skill to build the shortest reliable path from "what is this?" to "I can explain or change it."
1409
+
1410
+ ## Start broad
1411
+
1412
+ 1. \`shadow_ops_context({ repoPath, compact: true })\`
1413
+ 2. Expand only as needed:
1414
+ - \`shadow_recon_tree({ repoPath, subPath?, maxDepth? })\`
1415
+ - \`shadow_recon_topography({ repoPath })\`
1416
+ - \`shadow_ops_briefing({ repoPath, scope: "mission", missionId, altitude: "ground" })\`
1417
+
1418
+ ## Relational analysis
1419
+
1420
+ - \`shadow_search_concept({ repoPath, query, compact: true })\`
1421
+ - \`shadow_search_symbol({ repoPath, query, matchMode? })\`
1422
+ - \`shadow_analyze_impact({ repoPath, symbolName, filePath?, depth: 3 })\`
1423
+ - \`shadow_analyze_deps({ repoPath, filePath, direction: "imported_by" })\`
1424
+ - \`shadow_analyze_type_graph({ repoPath, symbolName, filePath?, direction?, relationship? })\`
1425
+ - \`shadow_analyze_mesh({ repoPath, topic, type? })\` when you have a concrete route or event fragment
1426
+
1427
+ ## Mechanics
1428
+
1429
+ - \`shadow_inspect_file({ repoPath, filePath, detailLevel: "signatures" })\`
1430
+ - \`shadow_inspect_symbol({ repoPath, symbolName, filePath?, context: "definition" | "full" })\`
1431
+ - \`shadow_analyze_flow({ repoPath, filePath, symbolName? })\`
1432
+ - \`shadow_analyze_explain_diff({ repoPath, baseCommit?, headCommit?, staged? })\`
1433
+
1434
+ ## Closeout
1435
+
1436
+ - \`shadow_ops_log({ repoPath, missionId?, type: "discovery", content, symbolName?, filePath? })\`
1437
+
1438
+ ## Rules
1439
+
1440
+ - Start broad and narrow down; do not jump straight to full-symbol inspection unless you already know the target.
1441
+ - \`shadow_analyze_type_graph\` requires \`symbolName\`.
1442
+ - \`shadow_analyze_mesh\` requires \`topic\`.
1443
+ `,shadow_workspace:`---
1342
1444
  name: workspace
1343
1445
  description: Manage multi-repository workspaces and cross-repo mission links using the Shadow Engine. Use when working with multiple repositories, federated search across repos, linking missions across repos, or when the user asks about workspace management, multi-repo workflows, or cross-repository dependencies.
1344
1446
  ---
1345
1447
 
1346
- # Workspace Orchestration
1448
+ # Workspace
1347
1449
 
1348
1450
  Manage multi-repository workspaces and cross-repo mission links using the Shadow Engine.
1349
1451
 
1350
- ## \u{1F680} Workflow
1351
-
1352
- 1. **List Workspaces**: \`shadow_workspace_list\` (repoPath, repoPaths).
1353
- 2. **Federated Search**: \`shadow_workspace_fuse\` (repoPath, repoPaths).
1354
- 3. **Link Missions**: \`shadow_workspace_link\` (parentRepoPath, parentMissionId, childRepoPath, childMissionId, relationship, repoPath).
1355
- 4. **Verify Graph**: \`shadow_ops_graph\` (missionId, depth, repoPath).
1452
+ ## Core calls
1356
1453
 
1357
- ## \u{1F6E0} Precise Tooling
1454
+ - List active work across repos:
1455
+ - \`shadow_workspace_list({ repoPaths, status? })\`
1456
+ - Build a fused search index:
1457
+ - \`shadow_workspace_fuse({ repoPaths, name? })\`
1458
+ - Link missions across repos:
1459
+ - \`shadow_workspace_link({ parentRepoPath, parentMissionId, childRepoPath, childMissionId, relationship })\`
1460
+ - Visualize a repo's mission graph:
1461
+ - \`shadow_ops_graph({ repoPath, missionId?, depth?, format? })\`
1358
1462
 
1359
- | Action | Atomic Tool | Example |
1360
- | :------------ | :---------------------- | :----------------------------------------------- |
1361
- | **List** | \`shadow_workspace_list\` | \`{ repoPath, repoPaths: [...] }\` |
1362
- | **Fuse** | \`shadow_workspace_fuse\` | \`{ repoPath, repoPaths: [...] }\` |
1363
- | **Link** | \`shadow_workspace_link\` | \`{ parentMissionId: 1, childMissionId: 2, ... }\` |
1364
- | **Visualize** | \`shadow_ops_graph\` | \`{ missionId: 1, depth: 3, repoPath }\` |
1463
+ ## After fusion
1365
1464
 
1366
- _Note: Use fused search after \`shadow_workspace_fuse\` to look up concepts across all repositories simultaneously._
1465
+ - Use the normal \`shadow_search_*\` and \`shadow_analyze_*\` tools inside the participating repos.
1466
+ - For routes and events that cross repo boundaries, use:
1467
+ - \`shadow_analyze_mesh({ repoPath, topic, includeCrossRepo: true })\`
1367
1468
 
1368
- ## \u{1F6E0} Tooling Strategy
1469
+ ## Rules
1369
1470
 
1370
- Use **\`shadow_workspace_fuse\`** early in multi-repo sessions to unlock "X-Ray" vision across boundaries.
1371
- `};import*as nt from"@clack/prompts";function Wd(s){return[{name:"Claude Code",dir:Je.join(s,".claude","skills"),folderBased:!0,createIfMissing:!1},{name:"Cursor",dir:Je.join(s,".cursor","skills"),folderBased:!0,createIfMissing:!1},{name:"Gemini CLI",dir:Je.join(s,".gemini","skills"),folderBased:!0,createIfMissing:!0},{name:"Codex",dir:Je.join(s,".codex","skills"),folderBased:!0,createIfMissing:!1},{name:"Antigravity",dir:Je.join(s,".gemini","antigravity","global_workflows"),folderBased:!1,createIfMissing:!1}]}function Ys(s=!1){let e=Fd.homedir(),t=Wd(e),n=0;for(let i of t){if(!$e.existsSync(i.dir))if(i.createIfMissing)$e.mkdirSync(i.dir,{recursive:!0});else continue;if(i.folderBased)try{for(let r of $e.readdirSync(i.dir))r.startsWith("shadow_shadow_")&&$e.rmSync(Je.join(i.dir,r),{recursive:!0,force:!0})}catch{}for(let[r,o]of Object.entries(vc))if(i.folderBased){let a=Je.join(i.dir,r);$e.existsSync(a)||$e.mkdirSync(a,{recursive:!0});let c=Je.join(a,"skill.md");$e.existsSync(c)&&$e.unlinkSync(c);let l=Je.join(a,"SKILL.md");(s||!$e.existsSync(l))&&($e.writeFileSync(l,o),n++)}else{let a=Je.join(i.dir,`${r}.md`);(s||!$e.existsSync(a))&&($e.writeFileSync(a,o),n++)}}return n}async function Tc(){nt.intro("\u{1F311} Liquid Shadow: Skills Update");let s=nt.spinner();s.start("Deploying latest skill definitions...");let e=Ys(!0);s.stop("Done."),e>0?nt.note(`Updated ${e} skill files across all detected targets.`,"Manifest"):nt.note("No skill targets found (Claude Code, Cursor, Gemini CLI, Codex, Antigravity).","Manifest"),nt.outro("\u{1F311} Skills are up to date.")}import{pino as zd}from"pino";import*as de from"@clack/prompts";var it=zd({transport:{target:"pino-pretty",options:{colorize:!0}}}),Pt="liquid-shadow",Ks="liquid-shadow-mcp";function Ud(s){let e=(s||Ks).trim();return e.length>0?e:Ks}function jd(s){let e=[],t=/[^\s"']+|"([^"]*)"|'([^']*)'/g,n;for(;(n=t.exec(s))!==null;)e.push(n[1]??n[2]??n[0]??"");return e}function kc(s){if(!s)return[];let e=s.trim();if(!e)return[];if(e.startsWith("[")){let t;try{t=JSON.parse(e)}catch{throw new Error('--mcp-args JSON parsing failed. Use a valid JSON array like ["--flag","value"].')}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error("--mcp-args JSON must be an array of strings.");return t}return jd(e)}function Rc(s){return s.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Bd(s,e){let t=`[${e.map(n=>`"${Rc(n)}"`).join(", ")}]`;return`[mcp_servers.${Pt}]
1372
- command = "${Rc(s)}"
1373
- args = ${t}`}function Gd(s,e,t){let n=s.split(/\r?\n/),i=n.findIndex(c=>c.trim()===e);if(i===-1)return`${s.length===0||s.endsWith(`
1471
+ - \`shadow_workspace_list\` and \`shadow_workspace_fuse\` take \`repoPaths\`, not \`repoPath\`.
1472
+ - \`shadow_workspace_link\` uses explicit parent and child repo paths; there is no shared \`repoPath\` parameter.
1473
+ `};import*as ft from"@clack/prompts";function xm(s){return[{name:"Claude Code",dir:ot.join(s,".claude","skills"),folderBased:!0,createIfMissing:!1},{name:"Cursor",dir:ot.join(s,".cursor","skills"),folderBased:!0,createIfMissing:!1},{name:"Gemini CLI",dir:ot.join(s,".gemini","skills"),folderBased:!0,createIfMissing:!0},{name:"Codex",dir:ot.join(s,".codex","skills"),folderBased:!0,createIfMissing:!1},{name:"Antigravity",dir:ot.join(s,".gemini","antigravity","global_workflows"),folderBased:!1,createIfMissing:!1}]}function hr(s=!1){let e=Sm.homedir(),t=xm(e),n=0;for(let i of t){if(!Be.existsSync(i.dir))if(i.createIfMissing)Be.mkdirSync(i.dir,{recursive:!0});else continue;if(i.folderBased)try{for(let r of Be.readdirSync(i.dir))r.startsWith("shadow_shadow_")&&Be.rmSync(ot.join(i.dir,r),{recursive:!0,force:!0})}catch{}for(let[r,o]of Object.entries(rl))if(i.folderBased){let a=ot.join(i.dir,r);Be.existsSync(a)||Be.mkdirSync(a,{recursive:!0});let l=ot.join(a,"skill.md");Be.existsSync(l)&&Be.unlinkSync(l);let c=ot.join(a,"SKILL.md");(s||!Be.existsSync(c))&&(Be.writeFileSync(c,o),n++)}else{let a=ot.join(i.dir,`${r}.md`);(s||!Be.existsSync(a))&&(Be.writeFileSync(a,o),n++)}}return n}async function ol(){ft.intro("\u{1F311} Liquid Shadow: Skills Update");let s=ft.spinner();s.start("Deploying latest skill definitions...");let e=hr(!0);s.stop("Done."),e>0?ft.note(`Updated ${e} skill files across all detected targets.`,"Manifest"):ft.note("No skill targets found (Claude Code, Cursor, Gemini CLI, Codex, Antigravity).","Manifest"),ft.outro("\u{1F311} Skills are up to date.")}import{pino as vm}from"pino";import*as _e from"@clack/prompts";var ht=vm({transport:{target:"pino-pretty",options:{colorize:!0}}}),Yt="liquid-shadow",gr="liquid-shadow-mcp";function Rm(s){let e=(s||gr).trim();return e.length>0?e:gr}function Tm(s){let e=[],t=/[^\s"']+|"([^"]*)"|'([^']*)'/g,n;for(;(n=t.exec(s))!==null;)e.push(n[1]??n[2]??n[0]??"");return e}function cl(s){if(!s)return[];let e=s.trim();if(!e)return[];if(e.startsWith("[")){let t;try{t=JSON.parse(e)}catch{throw new Error('--mcp-args JSON parsing failed. Use a valid JSON array like ["--flag","value"].')}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error("--mcp-args JSON must be an array of strings.");return t}return Tm(e)}function al(s){return s.replaceAll("\\","\\\\").replaceAll('"','\\"')}function km(s,e){let t=`[${e.map(n=>`"${al(n)}"`).join(", ")}]`;return`[mcp_servers.${Yt}]
1474
+ command = "${al(s)}"
1475
+ args = ${t}`}function Cm(s,e,t){let n=s.split(/\r?\n/),i=n.findIndex(l=>l.trim()===e);if(i===-1)return`${s.length===0||s.endsWith(`
1374
1476
  `)?s:`${s}
1375
1477
  `}
1376
1478
  ${t}
1377
- `;let r=n.length;for(let c=i+1;c<n.length;c++)if(/^\s*\[[^\]]+\]\s*$/.test(n[c]||"")){r=c;break}let o=t.split(`
1479
+ `;let r=n.length;for(let l=i+1;l<n.length;l++)if(/^\s*\[[^\]]+\]\s*$/.test(n[l]||"")){r=l;break}let o=t.split(`
1378
1480
  `);return`${[...n.slice(0,i),...o,...n.slice(r)].join(`
1379
1481
  `).replace(/\n{3,}/g,`
1380
1482
 
1381
1483
  `).trimEnd()}
1382
- `}async function Cc(s=!1,e=!1,t=Ks,n=[]){de.intro("\u{1F311} Liquid Shadow: Tactical Onboarding");let i=Hd.homedir(),r=0,o=Ud(t),a=Array.isArray(n)?n:[],c=e||await de.confirm({message:"Deploy Autonomous Reasoning Skills? (Injects /onboard, /understand, etc.)",initialValue:!0});if(de.isCancel(c)){de.outro("Onboarding aborted.");return}let l=e||await de.confirm({message:"Connect to MCP Reasoning Engines? (Claude Code, Claude Desktop, Gemini CLI, Codex)",initialValue:!0});if(de.isCancel(l)){de.outro("Onboarding aborted.");return}if(!c&&!l){de.outro("No actions selected. Operational state unchanged.");return}let p=de.spinner();p.start("Establishing intelligence assets..."),c&&(r=Ys(!0)),l&&(qd(i,o,a,!0),Vd(i,o,a,!0)),p.stop("Intelligence layer established."),r>0?de.note(`Successfully deployed ${r} tactical skills.`,"Manifest"):de.note("No new skills deployed (up to date or scope skipped).","Manifest"),de.outro("\u{1F311} Liquid Shadow is operational.")}function qd(s,e,t,n){let i=[{name:"Claude Code",path:Zt.join(s,".claude.json"),extraFields:{type:"stdio"},createIfMissing:!1},{name:"Claude Desktop",path:Zt.join(s,"Library","Application Support","Claude","claude_desktop_config.json"),createIfMissing:!1},{name:"Gemini CLI",path:Zt.join(s,".gemini","settings.json"),createIfMissing:!0},{name:"Antigravity IDE",path:Zt.join(s,".gemini","antigravity","mcp_config.json"),createIfMissing:!1}];for(let r of i){if(!bt.existsSync(r.path))if(r.createIfMissing)bt.mkdirSync(Zt.dirname(r.path),{recursive:!0}),bt.writeFileSync(r.path,"{}");else{it.debug(`${r.name} config not found at ${r.path}, skipping.`);continue}try{let o=JSON.parse(bt.readFileSync(r.path,"utf8"));if(o.mcpServers||(o.mcpServers={}),o.mcpServers[Pt]){if(!n){it.info(`${r.name}: ${Pt} already configured.`);continue}it.info(`${r.name}: updating existing ${Pt} configuration.`)}o.mcpServers[Pt]={command:e,args:t,env:{},...r.extraFields??{}},bt.writeFileSync(r.path,JSON.stringify(o,null,2)),it.info(`Updated ${r.name} config at ${r.path}`)}catch(o){it.error(`Failed to update ${r.name} config at ${r.path}: ${o}`)}}}function Vd(s,e,t,n){let i=Zt.join(s,".codex","config.toml");if(!bt.existsSync(i)){it.debug(`Codex config not found at ${i}, skipping.`);return}try{let r=bt.readFileSync(i,"utf8"),o=`[mcp_servers.${Pt}]`,a=Bd(e,t);if(r.includes(o)&&!n){it.info(`Codex: ${Pt} already configured.`);return}let c=Gd(r,o,a);bt.writeFileSync(i,c),it.info(`Updated Codex config at ${i}`)}catch(r){it.error(`Failed to update Codex config at ${i}: ${r}`)}}St();import{readFileSync as Jd}from"node:fs";var en={name:"@precisionutilityguild/liquid-shadow",version:"0.0.0",license:"UNLICENSED",description:"Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem"};function Ic(){let s=JSON.parse(Jd(_e("package.json"),"utf8"));return{name:typeof s.name=="string"&&s.name.trim().length>0?s.name:en.name,version:typeof s.version=="string"&&s.version.trim().length>0?s.version:en.version,license:typeof s.license=="string"&&s.license.trim().length>0?s.license:en.license,description:typeof s.description=="string"&&s.description.trim().length>0?s.description:en.description}}function be(s){let e=process.cwd();return Vi(e,s.flags)}process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),Q().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),Q().then(()=>process.exit(1))});var Qs=en;try{Qs=Ic()}catch(s){console.error("Failed to parse package.json, using defaults",s)}var ie=Yd().name("liquid-shadow").version(Qs.version).description(Qs.description).scriptName("liquid-shadow");ie.command("index","Index the repository for AI analysis",{parameters:["[dir]"],flags:{output:{type:String,alias:"o",description:"Export to JSON file instead of indexing"},level:{type:String,alias:"l",description:"Detail level",default:"detailed"},subPath:{type:String,description:"Only process files within this subpath"},force:{type:Boolean,description:"Force re-indexing of all files",default:!1},deep:{type:Boolean,description:"Perform deep semantic indexing (headings + symbol embeddings)",default:!0}}}).on("index",async s=>{let e=be(s),t={...s.flags,dir:s.flags.dir??e.dir,level:s.flags.level??e.level,deep:s.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await pa(s.parameters.dir||e.dir,t)});ie.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=be(s);await Dr(s.parameters.dir||e.dir)});ie.command("dashboard","Operational intelligence dashboard (TUI)",{parameters:["[dir]"]}).on("dashboard",async s=>{let e=be(s);await cs(s.parameters.dir||e.dir)});ie.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=be(s);await Br(s.parameters.dir||e.dir)});ie.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=be(s);await da(s.parameters.dir||e.dir)});ie.command("tree","Visualize repository structure as a tree",{parameters:["[dir]"],flags:{subPath:{type:String,description:"Subpath to visualize"},depth:{type:String,alias:"d",description:"Max depth",default:"3"}}}).on("tree",async s=>{let e=be(s);await aa(s.parameters.dir||e.dir,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("recon","Repository reconnaissance and architecture analysis",{parameters:["<mode>","[dir]"],flags:{subPath:{type:String,description:"Subpath to focus on"}}}).on("recon",async s=>{let e=be(s);await Ca(s.parameters.mode,s.parameters.dir||e.dir,{...s.flags})});ie.command("trace","Trace execution flow for a given file/symbol",{parameters:["<file>","[symbolName]"],flags:{dir:{type:String,alias:"d",default:"."}}}).on("trace",async s=>{let e=be(s);await Sa(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});ie.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"],flags:{contextPivot:{type:Boolean,default:!1,description:"Opt in to suspend other-branch missions and resume current-branch missions"},mergeSentinel:{type:Boolean,default:!1,description:"Opt in to auto-complete missions from merged branches"}}}).on("sync",async s=>{let e=be(s);await Ta(s.parameters.dir||e.dir,{contextPivot:!!s.flags.contextPivot,mergeSentinel:!!s.flags.mergeSentinel})});ie.command("search-config","Search for configuration values",{parameters:["[key]"],flags:{dir:{type:String,alias:"d",default:"."},kind:{type:String,description:"Filter by config kind"}}}).on("search-config",async s=>{let e=be(s);await Ha(s.parameters.key,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("search-concept","Search for files by concept/intent (Semantic)",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-concept",async s=>{let e=be(s);await Oa(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("search-symbol","Search for specific code symbols",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-symbol",async s=>{let e=be(s);await Fa(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("search-fuzzy",'Fuzzy search for symbols (e.g., "usc" finds "UserServiceClient")',{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-fuzzy",async s=>{let e=be(s);await Wa(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});ie.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async s=>{await za([s.parameters.action,s.parameters.path])});ie.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async s=>{await Xa([s.parameters.action,...s.parameters.args])});ie.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async s=>{await bc([s.parameters.action,...s.parameters.args])});ie.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async s=>{await _c([s.parameters.mode,...s.parameters.args])});ie.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=be(s);await wc(s.parameters.dir||e.dir)});ie.command("chronicle","Generate a repository-wide narrative feed (ADRs/Epics)",{parameters:["[dir]"],flags:{format:{type:String,alias:"f",description:"Output format (markdown|json)",default:"markdown"},limit:{type:Number,alias:"l",description:"Limit number of entries",default:10},offset:{type:Number,description:"Pagination offset",default:0},since:{type:String,description:"Show entries since date (YYYY-MM-DD)"},until:{type:String,description:"Show entries until date (YYYY-MM-DD)"}}}).on("chronicle",async s=>{let e=be(s);await xc(s.parameters.dir||e.dir,{...s.flags,format:s.flags.format,limit:s.flags.limit?parseInt(String(s.flags.limit),10):void 0,offset:s.flags.offset?parseInt(String(s.flags.offset),10):void 0,since:s.flags.since?Math.floor(new Date(String(s.flags.since)).getTime()/1e3):void 0,until:s.flags.until?Math.floor(new Date(String(s.flags.until)).getTime()/1e3):void 0})});ie.command("init","Initialize Liquid Shadow skills and configuration",{flags:{force:{type:Boolean,alias:"f",description:"Force overwrite existing skills and MCP server entries",default:!1},yes:{type:Boolean,alias:"y",description:"Skip interactive confirmation (unsafe)",default:!1},mcpCommand:{type:String,description:"Override MCP command used in generated client configs",default:"liquid-shadow-mcp"},mcpArgs:{type:String,description:'Optional MCP args (JSON array recommended, e.g. ["--flag","value"] or quoted string)'}}}).on("init",async s=>{let e;try{e=kc(s.flags.mcpArgs)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Invalid --mcp-args: ${n}`),process.exit(1);return}await Cc(s.flags.force,s.flags.yes,s.flags.mcpCommand,e)});ie.command("skills","Manage Liquid Shadow reasoning skills",{parameters:["<action>"]}).on("skills",async s=>{let e=s.parameters.action;e==="update"?await Tc():(console.error(`Unknown skills action: ${e}. Available: update`),process.exit(1))});ie.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async s=>{await Sc(s.parameters.shell||"")});if(process.argv.length<=2){let s=Vi(process.cwd(),{});cs(s.dir)}else ie.parse();
1484
+ `}async function ll(s=!1,e=!1,t=gr,n=[]){_e.intro("\u{1F311} Liquid Shadow: Tactical Onboarding");let i=wm.homedir(),r=0,o=Rm(t),a=Array.isArray(n)?n:[],l=e||await _e.confirm({message:"Deploy Autonomous Reasoning Skills? (Injects /onboard, /understand, etc.)",initialValue:!0});if(_e.isCancel(l)){_e.outro("Onboarding aborted.");return}let c=e||await _e.confirm({message:"Connect to MCP Reasoning Engines? (Claude Code, Claude Desktop, Gemini CLI, Codex)",initialValue:!0});if(_e.isCancel(c)){_e.outro("Onboarding aborted.");return}if(!l&&!c){_e.outro("No actions selected. Operational state unchanged.");return}let p=_e.spinner();p.start("Establishing intelligence assets..."),l&&(r=hr(!0)),c&&(Im(i,o,a,!0),Lm(i,o,a,!0)),p.stop("Intelligence layer established."),r>0?_e.note(`Successfully deployed ${r} tactical skills.`,"Manifest"):_e.note("No new skills deployed (up to date or scope skipped).","Manifest"),_e.outro("\u{1F311} Liquid Shadow is operational.")}function Im(s,e,t,n){let i=[{name:"Claude Code",path:hn.join(s,".claude.json"),extraFields:{type:"stdio"},createIfMissing:!1},{name:"Claude Desktop",path:hn.join(s,"Library","Application Support","Claude","claude_desktop_config.json"),createIfMissing:!1},{name:"Gemini CLI",path:hn.join(s,".gemini","settings.json"),createIfMissing:!0},{name:"Antigravity IDE",path:hn.join(s,".gemini","antigravity","mcp_config.json"),createIfMissing:!1}];for(let r of i){if(!At.existsSync(r.path))if(r.createIfMissing)At.mkdirSync(hn.dirname(r.path),{recursive:!0}),At.writeFileSync(r.path,"{}");else{ht.debug(`${r.name} config not found at ${r.path}, skipping.`);continue}try{let o=JSON.parse(At.readFileSync(r.path,"utf8"));if(o.mcpServers||(o.mcpServers={}),o.mcpServers[Yt]){if(!n){ht.info(`${r.name}: ${Yt} already configured.`);continue}ht.info(`${r.name}: updating existing ${Yt} configuration.`)}o.mcpServers[Yt]={command:e,args:t,env:{},...r.extraFields??{}},At.writeFileSync(r.path,JSON.stringify(o,null,2)),ht.info(`Updated ${r.name} config at ${r.path}`)}catch(o){ht.error(`Failed to update ${r.name} config at ${r.path}: ${o}`)}}}function Lm(s,e,t,n){let i=hn.join(s,".codex","config.toml");if(!At.existsSync(i)){ht.debug(`Codex config not found at ${i}, skipping.`);return}try{let r=At.readFileSync(i,"utf8"),o=`[mcp_servers.${Yt}]`,a=km(e,t);if(r.includes(o)&&!n){ht.info(`Codex: ${Yt} already configured.`);return}let l=Cm(r,o,a);At.writeFileSync(i,l),ht.info(`Updated Codex config at ${i}`)}catch(r){ht.error(`Failed to update Codex config at ${i}: ${r}`)}}Dt();import{readFileSync as Mm}from"node:fs";var gn={name:"@precisionutilityguild/liquid-shadow",version:"0.0.0",license:"UNLICENSED",description:"Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem"};function pl(){let s=JSON.parse(Mm(Le("package.json"),"utf8"));return{name:typeof s.name=="string"&&s.name.trim().length>0?s.name:gn.name,version:typeof s.version=="string"&&s.version.trim().length>0?s.version:gn.version,license:typeof s.license=="string"&&s.license.trim().length>0?s.license:gn.license,description:typeof s.description=="string"&&s.description.trim().length>0?s.description:gn.description}}function ke(s){let e=process.cwd();return ds(e,s.flags)}process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),ne().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),ne().then(()=>process.exit(1))});var yr=gn;try{yr=pl()}catch(s){console.error("Failed to parse package.json, using defaults",s)}var le=$m().name("liquid-shadow").version(yr.version).description(yr.description).scriptName("liquid-shadow");le.command("index","Index the repository for AI analysis",{parameters:["[dir]"],flags:{output:{type:String,alias:"o",description:"Export to JSON file instead of indexing"},level:{type:String,alias:"l",description:"Detail level",default:"detailed"},subPath:{type:String,description:"Only process files within this subpath"},force:{type:Boolean,description:"Force re-indexing of all files",default:!1},deep:{type:Boolean,description:"Perform deep semantic indexing (headings + symbol embeddings)",default:!0}}}).on("index",async s=>{let e=ke(s),t={...s.flags,dir:s.flags.dir??e.dir,level:s.flags.level??e.level,deep:s.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await Fa(s.parameters.dir||e.dir,t)});le.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=ke(s);await po(s.parameters.dir||e.dir)});le.command("dashboard","Operational intelligence dashboard (TUI)",{parameters:["[dir]"]}).on("dashboard",async s=>{let e=ke(s);await ks(s.parameters.dir||e.dir)});le.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=ke(s);await _o(s.parameters.dir||e.dir)});le.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=ke(s);await Ha(s.parameters.dir||e.dir)});le.command("tree","Visualize repository structure as a tree",{parameters:["[dir]"],flags:{subPath:{type:String,description:"Subpath to visualize"},depth:{type:String,alias:"d",description:"Max depth",default:"3"}}}).on("tree",async s=>{let e=ke(s);await Pa(s.parameters.dir||e.dir,{...s.flags,dir:s.flags.dir??e.dir})});le.command("recon","Repository reconnaissance and architecture analysis",{parameters:["<mode>","[dir]"],flags:{subPath:{type:String,description:"Subpath to focus on"}}}).on("recon",async s=>{let e=ke(s);await sc(s.parameters.mode,s.parameters.dir||e.dir,{...s.flags})});le.command("trace","Trace execution flow for a given file/symbol",{parameters:["<file>","[symbolName]"],flags:{dir:{type:String,alias:"d",default:"."}}}).on("trace",async s=>{let e=ke(s);await Qa(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});le.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"],flags:{contextPivot:{type:Boolean,default:!1,description:"Opt in to suspend other-branch missions and resume current-branch missions"},mergeSentinel:{type:Boolean,default:!1,description:"Opt in to auto-complete missions from merged branches"}}}).on("sync",async s=>{let e=ke(s);await tc(s.parameters.dir||e.dir,{contextPivot:!!s.flags.contextPivot,mergeSentinel:!!s.flags.mergeSentinel})});le.command("search-config","Search for configuration values",{parameters:["[key]"],flags:{dir:{type:String,alias:"d",default:"."},kind:{type:String,description:"Filter by config kind"}}}).on("search-config",async s=>{let e=ke(s);await _c(s.parameters.key,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-concept","Search for files by concept/intent (Semantic)",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-concept",async s=>{let e=ke(s);await gc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-symbol","Search for specific code symbols",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-symbol",async s=>{let e=ke(s);await yc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-fuzzy",'Fuzzy search for symbols (e.g., "usc" finds "UserServiceClient")',{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-fuzzy",async s=>{let e=ke(s);await bc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async s=>{await Ec([s.parameters.action,s.parameters.path])});le.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async s=>{await Mc([s.parameters.action,...s.parameters.args])});le.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async s=>{await Xc([s.parameters.action,...s.parameters.args])});le.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async s=>{await el([s.parameters.mode,...s.parameters.args])});le.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=ke(s);await il(s.parameters.dir||e.dir)});le.command("chronicle","Generate a repository-wide narrative feed (ADRs/Epics)",{parameters:["[dir]"],flags:{format:{type:String,alias:"f",description:"Output format (markdown|json)",default:"markdown"},limit:{type:Number,alias:"l",description:"Limit number of entries",default:10},offset:{type:Number,description:"Pagination offset",default:0},since:{type:String,description:"Show entries since date (YYYY-MM-DD)"},until:{type:String,description:"Show entries until date (YYYY-MM-DD)"}}}).on("chronicle",async s=>{let e=ke(s);await sl(s.parameters.dir||e.dir,{...s.flags,format:s.flags.format,limit:s.flags.limit?parseInt(String(s.flags.limit),10):void 0,offset:s.flags.offset?parseInt(String(s.flags.offset),10):void 0,since:s.flags.since?Math.floor(new Date(String(s.flags.since)).getTime()/1e3):void 0,until:s.flags.until?Math.floor(new Date(String(s.flags.until)).getTime()/1e3):void 0})});le.command("init","Initialize Liquid Shadow skills and configuration",{flags:{force:{type:Boolean,alias:"f",description:"Force overwrite existing skills and MCP server entries",default:!1},yes:{type:Boolean,alias:"y",description:"Skip interactive confirmation (unsafe)",default:!1},mcpCommand:{type:String,description:"Override MCP command used in generated client configs",default:"liquid-shadow-mcp"},mcpArgs:{type:String,description:'Optional MCP args (JSON array recommended, e.g. ["--flag","value"] or quoted string)'}}}).on("init",async s=>{let e;try{e=cl(s.flags.mcpArgs)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Invalid --mcp-args: ${n}`),process.exit(1);return}await ll(s.flags.force,s.flags.yes,s.flags.mcpCommand,e)});le.command("skills","Manage Liquid Shadow reasoning skills",{parameters:["<action>"]}).on("skills",async s=>{let e=s.parameters.action;e==="update"?await ol():(console.error(`Unknown skills action: ${e}. Available: update`),process.exit(1))});le.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async s=>{await nl(s.parameters.shell||"")});if(process.argv.length<=2){let s=ds(process.cwd(),{});ks(s.dir)}else le.parse();