@precisionutilityguild/liquid-shadow 1.0.10 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,103 +1,83 @@
1
1
  #!/usr/bin/env node
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(`
2
+ var Bu=Object.create;var Jr=Object.defineProperty;var Gu=Object.getOwnPropertyDescriptor;var qu=Object.getOwnPropertyNames;var Ju=Object.getPrototypeOf,Ku=Object.prototype.hasOwnProperty;var oe=(s,e)=>()=>(s&&(e=s(s=0)),e);var Vu=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Kr=(s,e)=>{for(var t in e)Jr(s,t,{get:e[t],enumerable:!0})},Yu=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of qu(e))!Ku.call(s,i)&&i!==t&&Jr(s,i,{get:()=>e[i],enumerable:!(n=Gu(e,i))||n.enumerable});return s};var Qu=(s,e,t)=>(t=s!=null?Bu(Ju(s)):{},Yu(e||!s||!s.__esModule?Jr(t,"default",{value:s,enumerable:!0}):t,s));import Xu from"pino";var Zu,em,k,q=oe(()=>{"use strict";Zu={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},em=Xu({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:Zu[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),k=em});import{existsSync as sm}from"node:fs";import{dirname as Vr,join as Da,resolve as im}from"node:path";import{fileURLToPath as rm}from"node:url";function am(){let s=$a;for(;s!==Vr(s);){if(sm(Da(s,"package.json")))return s;s=Vr(s)}return im($a,"..","..")}function je(...s){return Da(am(),...s)}var om,$a,Kt=oe(()=>{"use strict";om=rm(import.meta.url),$a=Vr(om)});import wn from"fs";import ni from"path";import{fileURLToPath as lm}from"url";function um(){let s=dm;if(wn.readdirSync(s).some(n=>n.match(/^\d{3}_.*\.sql$/)))return s;let t=ni.resolve(s,"../../data/migrations");return wn.existsSync(t)&&wn.readdirSync(t).some(n=>n.match(/^\d{3}_.*\.sql$/))?t:s}function mm(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 $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(`
8
+ `)}function fm(s){mm(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function hm(s){return wn.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=wn.readFileSync(ni.join(s,t),"utf-8").split(/^-- DOWN$/m);return{version:i,name:r,up:a[0].trim(),down:a[1]?.trim()}})}function gm(s,e){Vt.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)})(),Vt.info({version:e.version},"Migration applied successfully")}function ym(s,e,t){let n=ni.join(e,"000_baseline.sql");if(!wn.existsSync(n)){Vt.warn("000_baseline.sql not found \u2014 falling back to incremental migrations");return}Vt.info("Fresh database detected \u2014 applying consolidated baseline schema");let i=wn.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)})(),Vt.info({stamped:t.length},"Baseline applied \u2014 incremental migrations stamped")}function Fa(s){let e=fm(s),t=um(),n=hm(t);if(e.size===0){ym(s,t,n);return}let i=n.filter(r=>!e.has(r.version));if(i.length===0){Vt.debug("No pending migrations");return}Vt.info({count:i.length},"Running pending migrations");for(let r of i)gm(s,r);Vt.info("All migrations complete")}var Vt,pm,dm,Wa=oe(()=>{"use strict";q();Vt=k.child({module:"migrations"}),pm=lm(import.meta.url),dm=ni.dirname(pm)});import bm from"better-sqlite3";import ja from"crypto";import Yr from"fs";import si from"path";import _m from"os";function ri(s){let e=_m.homedir(),t=si.join(e,".mcp-liquid-shadow"),n=si.join(t,"dbs");Yr.existsSync(n)||Yr.mkdirSync(n,{recursive:!0});let i=ja.createHash("sha256").update(s).digest("hex").substring(0,12),o=`${si.basename(s).replace(/[^a-zA-Z0-9-_]/g,"_")}_${i}.db`;return si.join(n,o)}function Sm(s,e){let t=e||ri(s);xt.debug({repoPath:s,dbPath:t},"Initializing database");let n=new bm(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),Fa(n),ii.set(s,t),Yt.set(t,n),xt.debug({repoPath:s,dbPath:t},"Database initialized successfully"),n}function Un(s){return ja.createHash("sha256").update(s,"utf8").digest("hex")}function za(s,e){return e?Un(s)!==e:!0}function ye(s){let e=ii.get(s)||ri(s),t=Yt.get(e);if(t){if(t.open)return t;Yt.delete(e)}let n=Sm(s);return Yt.set(e,n),n}function Re(s){let e=ri(s);if(!Yr.existsSync(e))return!1;try{let t=ye(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 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(`
11
+ `).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return xt.debug({repoPath:s,error:t},"Error checking index status"),!1}}function Qr(s,e){let t=ye(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)})(),xt.debug({repoPath:s,commitSha:e},"Repository marked as indexed")}function En(s){try{return ye(s).prepare(`
12
12
  SELECT value FROM index_metadata
13
13
  WHERE key = 'last_indexed_commit'
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
- SELECT * FROM files
16
- WHERE (path LIKE ? OR path = ?)
17
- ORDER BY path ASC
18
- `,`${i}%`,n)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
19
- SELECT files.*, files_fts.rank
20
- FROM files_fts
21
- JOIN files ON files.rowid = files_fts.rowid
22
- WHERE files_fts MATCH ?
23
- ORDER BY rank
24
- LIMIT ?
25
- `,e,t)}findByPathKeywords(e,t=10){let n=e.map(()=>"LOWER(path) LIKE ?").join(" OR ");return this.all(`
26
- SELECT * FROM files
27
- WHERE ${n}
28
- LIMIT ?
29
- `,...e.map(i=>`%${i}%`),t)}findContentFts(e,t=50){let n=this.buildContentFtsQuery(e);return n?this.all(`
14
+ `).get()?.value||null}catch(e){return xt.debug({repoPath:s,error:e},"Error getting last indexed commit"),null}}function Qt(s){try{let t=ye(s).prepare(`
15
+ SELECT key, value FROM index_metadata
16
+ WHERE key IN ('last_indexed_commit', 'last_indexed_at')
17
+ `).all(),n=new Map(t.map(o=>[o.key,o.value])),i=n.get("last_indexed_at"),r=i?Number(i):null;return{lastIndexedCommit:n.get("last_indexed_commit")??null,lastIndexedAt:Number.isFinite(r)?r:null}}catch(e){return xt.debug({repoPath:s,error:e},"Error getting index metadata"),{lastIndexedCommit:null,lastIndexedAt:null}}}function oi(s){let e=ii.get(s)||ri(s),t=Yt.get(e);t&&(t.open&&(xt.debug({repoPath:s,dbPath:e},"Closing database connection"),t.close()),Yt.delete(e)),ii.delete(s)}function Ha(){for(let[s,e]of Yt.entries())try{e.open&&(xt.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){xt.error({dbPath:s,err:t},"Error closing database execution")}Yt.clear()}var xt,Yt,ii,Ua,Ae=oe(()=>{"use strict";q();Wa();xt=k.child({module:"db"});Yt=new Map,ii=new Map;process.on("exit",()=>Ha());Ua=s=>{xt.debug({signal:s},"Received termination signal, closing databases"),Ha(),process.exit(0)};process.on("SIGINT",()=>Ua("SIGINT"));process.on("SIGTERM",()=>Ua("SIGTERM"))});import{existsSync as Ba}from"node:fs";import{cpus as wm}from"node:os";import{dirname as Em,join as Ga}from"node:path";import{fileURLToPath as xm}from"node:url";import{Worker as vm}from"node:worker_threads";function km(){if(Ja.endsWith(".ts")){let e=Ga(qa,"worker.ts");if(Ba(e))return e}let s=Ga(qa,"worker.js");return Ba(s)?s:je("dist/logic/domain/embeddings/worker.js")}function Gn(s){return Bn||(Bn=new vs(s)),Bn}async function qn(){Bn&&(await Bn.shutdown(),Bn=null)}var Ja,qa,vs,Bn,Ka=oe(()=>{"use strict";Kt();q();Ja=xm(import.meta.url),qa=Em(Ja);vs=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,wm().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{k.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,k.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,k.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=km();k.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 vm(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){k.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(a),k.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),k.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(d=>{k.error({err:d},"Failed to replace crashed worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&k.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,d)=>new Promise((p,u)=>{let f={id:`task_${++this.taskIdCounter}`,texts:l,resolve:h=>{if(r[d]=h,o++,n){let y=Math.min(o*t,e.length);n(y,e.length)}p()},reject:h=>{if(r[d]=new Array(l.length).fill(null),o++,k.warn({err:h,chunkIndex:d},"Chunk embedding failed"),n){let y=Math.min(o*t,e.length);n(y,e.length)}p()}};this.taskQueue.push(f),this.processQueue()}));await Promise.all(a);let c=[];for(let l of r)c.push(...l);return k.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}k.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,k.info("Embedding worker pool shutdown complete")}},Bn=null});var vt={};Kr(vt,{EmbeddingPriorityQueue:()=>Zr,EmbeddingWorkerPool:()=>vs,cosineSimilarity:()=>li,generateEmbedding:()=>to,generateEmbeddingsBatch:()=>no,getDefaultPool:()=>Gn,setUseWorkerThreads:()=>ci,shutdownDefaultPool:()=>qn});async function Rm(){return ks||(ks=await import("@xenova/transformers"),ks.env.cacheDir="./.cache",ks.env.allowLocalModels=!0),ks}function ci(s){eo=s,k.info({useWorkerThreads:s},"Worker thread mode updated")}function Va(s=!1){let e=(Rs||"").toLowerCase(),t={};return Rs&&(t.dtype=Rs),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 Tm(){k.info({model:ai,dtype:Rs},"Loading embedding model...");let{pipeline:s}=await Rm(),e=Va(!1);try{return await s("feature-extraction",ai,e)}catch(t){let n=t?.message||"";if(!(n.includes("/onnx/model_quantized.onnx")||n.includes("model_quantized.onnx")))throw t;return k.warn({model:ai,dtype:Rs},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",ai,Va(!0))}}async function Qa(){return Xr||(Xr=Tm()),Xr}async function to(s){try{let t=await(await Qa())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return k.error({err:e},"Failed to generate embedding"),null}}async function no(s,e=Ya,t){return s.length===0?[]:eo?Gn().generateEmbeddings(s,e,t):Xa(s,e,t)}async function Xa(s,e,t){let n=new Array(s.length).fill(null),i=await Qa();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,d]=c.dims;for(let p=0;p<l;p++){let u=p*d,m=u+d;n[r+p]=Array.from(c.data.slice(u,m))}}catch(c){k.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 d=a[l];if(!d||d.trim().length===0)continue;let p=await i(d,{pooling:"mean",normalize:!0});n[r+l]=Array.from(p.data)}catch{n[r+l]=null}}t&&t(o,s.length)}return k.debug({total:s.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function li(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 ai,Rs,ks,Ya,eo,Xr,Zr,Ge=oe(()=>{"use strict";q();Ka();ai=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",Rs=process.env.EMBEDDING_DTYPE??"fp32",ks=null;Ya=128,eo=!1;Xr=null;Zr=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=Ya,t){if(this.processing)return k.warn("Queue processing already in progress"),this.results;this.processing=!0;let n=this.queue.length;try{eo?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 Xa(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 Gn().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 Se,ft=oe(()=>{"use strict";Se=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)()}}});var pi,Za=oe(()=>{"use strict";ft();pi=class extends Se{claimFile(e,t){try{this.run(`
18
+ INSERT INTO file_claims (file_path, mission_id, claimed_at, updated_at)
19
+ VALUES (?, ?, unixepoch(), unixepoch())
20
+ `,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(`
30
21
  SELECT
31
- files.*,
32
- bm25(content_fts, 0.2, 1.0) AS bm25_rank
22
+ fc.file_path,
23
+ fc.mission_id,
24
+ fc.claimed_at,
25
+ fc.updated_at,
26
+ m.name AS mission_name,
27
+ m.status AS mission_status,
28
+ m.git_branch AS mission_branch
29
+ FROM file_claims fc
30
+ LEFT JOIN missions m ON m.id = fc.mission_id
31
+ WHERE fc.file_path = ?
32
+ `,e)}getClaimsForMission(e){return this.all(`
33
+ SELECT
34
+ fc.file_path,
35
+ fc.mission_id,
36
+ fc.claimed_at,
37
+ fc.updated_at,
38
+ m.name AS mission_name,
39
+ m.status AS mission_status,
40
+ m.git_branch AS mission_branch
41
+ FROM file_claims fc
42
+ LEFT JOIN missions m ON m.id = fc.mission_id
43
+ WHERE fc.mission_id = ?
44
+ ORDER BY fc.file_path ASC
45
+ `,e)}listClaims(){return this.all(`
46
+ SELECT
47
+ fc.file_path,
48
+ fc.mission_id,
49
+ fc.claimed_at,
50
+ fc.updated_at,
51
+ m.name AS mission_name,
52
+ m.status AS mission_status,
53
+ m.git_branch AS mission_branch
54
+ FROM file_claims fc
55
+ LEFT JOIN missions m ON m.id = fc.mission_id
56
+ ORDER BY fc.updated_at DESC, fc.file_path ASC
57
+ `)}getClaimsByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`
58
+ SELECT
59
+ fc.file_path,
60
+ fc.mission_id,
61
+ fc.claimed_at,
62
+ fc.updated_at,
63
+ m.name AS mission_name,
64
+ m.status AS mission_status,
65
+ m.git_branch AS mission_branch
66
+ FROM file_claims fc
67
+ LEFT JOIN missions m ON m.id = fc.mission_id
68
+ WHERE fc.file_path IN (${t})
69
+ ORDER BY fc.file_path ASC
70
+ `,...e)}}});var di,ec=oe(()=>{"use strict";ft();di=class extends Se{findByKey(e,t=20){return this.all(`
71
+ SELECT file_path, key, value, kind
72
+ FROM configs
73
+ WHERE key LIKE ? OR value LIKE ?
74
+ LIMIT ?
75
+ `,`%${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 ui,tc=oe(()=>{"use strict";ft();ui=class extends Se{search(e,t=10){return this.all(`
76
+ SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
33
77
  FROM content_fts
34
- JOIN files ON files.path = content_fts.file_path
35
78
  WHERE content_fts MATCH ?
36
- ORDER BY bm25_rank ASC
37
79
  LIMIT ?
38
- `,n,Math.max(1,Math.min(t,1e3))):[]}getContent(e){return this.get("SELECT content FROM file_content WHERE file_path = ?",e)?.content}findContentByToken(e,t=10){return this.all(`
39
- SELECT file_path
40
- FROM content_fts
41
- WHERE content_fts MATCH ?
42
- AND (file_path LIKE '%.ts' OR file_path LIKE '%.tsx' OR file_path LIKE '%.js' OR file_path LIKE '%.py' OR file_path LIKE '%.php')
43
- AND file_path NOT LIKE '%/test/%'
44
- AND file_path NOT LIKE '%.spec.%'
45
- LIMIT ?
46
- `,`"${e.replace(/[^a-zA-Z0-9_\/]/g," ")}"`,t).map(i=>i.file_path)}findSynapses(e){let t="SELECT * FROM event_synapses WHERE 1=1",n=[];if(e.type&&(t+=" AND type = ?",n.push(e.type)),e.name){let i=e.name;i.startsWith("/")&&(i=i.substring(1)),i.endsWith("/")&&(i=i.substring(0,i.length-1)),i.length>0&&(t+=" AND (name LIKE ? OR name LIKE ? OR name = ?)",n.push(`${i}%`),n.push(`%/${i}%`),n.push(e.name))}return e.direction&&(t+=" AND direction = ?",n.push(e.direction)),t+=` LIMIT ${e.limit||50}`,this.all(t,...n)}exists(e){return!!this.get("SELECT 1 FROM files WHERE path = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE files SET ${i} WHERE path = ?`,...r)}getStats(){let e=this.get(`
47
- SELECT
48
- COUNT(*) as total,
49
- SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
50
- FROM files
51
- `);return{total:e?.total||0,withSummary:e?.withSummary||0}}getGravityMap(e=[],t){let n={},i=`
52
- SELECT ws.file_path, m.name as mission_name, m.status
53
- FROM working_set ws
54
- JOIN missions m ON ws.mission_id = m.id
55
- WHERE (
56
- (m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
57
- OR m.id IN (${e.length>0?e.join(","):"-1"})
58
- )
59
- AND ws.file_path IS NOT NULL
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
- SELECT file_path, type, mission_id
62
- FROM intent_logs
63
- WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
64
- AND file_path IS NOT NULL
65
- ORDER BY created_at DESC
66
- LIMIT 100
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
- SELECT
69
- SUBSTR(path, LENGTH(?) + 2,
70
- INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
71
- ) as root,
72
- COUNT(*) as total_files,
73
- SUM(CASE
74
- WHEN path LIKE '%.ts' OR path LIKE '%.tsx'
75
- OR path LIKE '%.js' OR path LIKE '%.jsx'
76
- OR path LIKE '%.mjs' OR path LIKE '%.cjs'
77
- THEN 1 ELSE 0
78
- END) as ts_files
79
- FROM files
80
- WHERE path LIKE ? || '/%/%'
81
- GROUP BY root
82
- ORDER BY total_files DESC
83
- LIMIT ?
84
- `,e,e,e,t)}hasFilesPattern(e){return!!this.get("SELECT 1 FROM files WHERE path LIKE ? LIMIT 1",e)}findPackageJsonChildren(e){return this.all(`
85
- SELECT
86
- path,
87
- SUBSTR(path, LENGTH(?) + 2) as relPath
88
- FROM files
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 = ?"),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
- INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
92
- VALUES (?, ?, ?, ?, ?, ?, ?)
93
- ON CONFLICT(path) DO UPDATE SET
94
- mtime=excluded.mtime,
95
- last_scanned_at=excluded.last_scanned_at,
96
- classification=excluded.classification,
97
- summary=excluded.summary,
98
- embedding=excluded.embedding,
99
- content_hash=excluded.content_hash
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(`
80
+ `,e,t)}}});var mi,nc=oe(()=>{"use strict";ft();mi=class s extends Se{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
81
  SELECT * FROM exports
102
82
  WHERE file_path = ? AND start_line <= ? AND end_line >= ?
103
83
  ORDER BY (end_line - start_line) ASC -- Get innermost symbol
@@ -194,7 +174,7 @@ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDe
194
174
  SELECT * FROM exports
195
175
  WHERE lower(name) LIKE ?
196
176
  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,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(`
177
+ `,`%${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.%'")),c.push("e.file_path NOT LIKE '%/dist/%'"),c.push("e.file_path NOT LIKE '%/build/%'"),c.push("e.file_path NOT LIKE '%/.next/%'"),c.push("e.file_path NOT LIKE '%/.nuxt/%'"),c.push("e.file_path NOT LIKE '%/.cache/%'"),c.push("e.file_path NOT LIKE '%/coverage/%'"),c.push("e.file_path NOT LIKE '%/node_modules/%'"),c.push("e.file_path NOT LIKE '%/storage/runtime/%'"),c.push("e.file_path NOT LIKE '%/compiled_templates/%'"),c.push("e.file_path NOT LIKE '%/compiled_classes/%'"),c.push("e.file_path NOT LIKE '%.generated.%'"),c.push("e.file_path NOT LIKE '%.gen.%'");for(let f of o){let h=f.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");c.push(`e.file_path NOT LIKE '${h}'`)}let l=c.length>0?`AND ${c.join(" AND ")}`:"",u=this.all(`
198
178
  SELECT e.name, e.kind, e.file_path, e.start_line
199
179
  FROM exports e
200
180
  WHERE e.kind IN (
@@ -203,7 +183,7 @@ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDe
203
183
  'ArrowFunctionExpression', 'FunctionExpression'
204
184
  )
205
185
  AND e.parent_id IS NULL
206
- ${c}
186
+ ${l}
207
187
  AND NOT EXISTS (
208
188
  SELECT 1
209
189
  FROM imports i
@@ -215,7 +195,7 @@ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDe
215
195
  AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
216
196
  ORDER BY e.file_path, e.start_line
217
197
  LIMIT ?
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=`
198
+ `,t*2).filter(f=>!this.isFrameworkEntrypointExport(f)).map(f=>{let{confidence:h,reason:y}=this.scoreDeadExportConfidence(f);return{...f,confidence:h,reason:y}}),m=u;return a==="high"?m=u.filter(f=>f.confidence==="high"):a==="medium"&&(m=u.filter(f=>f.confidence==="high"||f.confidence==="medium")),m.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
199
  SELECT ws.symbol_id, m.name as mission_name, m.status
220
200
  FROM working_set ws
221
201
  JOIN missions m ON ws.mission_id = m.id
@@ -224,14 +204,14 @@ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDe
224
204
  OR m.id IN (${e.length>0?e.join(","):"-1"})
225
205
  )
226
206
  AND ws.symbol_id IS NOT NULL
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(`
207
+ `,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 d=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.symbol_id].score+=d;let p=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.symbol_id].reasons.push(`${p}: ${l.mission_name}`)}let a=Math.floor(Date.now()/1e3)-86400,c=this.all(`
228
208
  SELECT symbol_id, type, mission_id
229
209
  FROM intent_logs
230
210
  WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
231
211
  AND symbol_id IS NOT NULL
232
212
  ORDER BY created_at DESC
233
213
  LIMIT 200
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(`
214
+ `,a);for(let l of c){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let d=l.mission_id?e.includes(l.mission_id):!1,p=d?.1:.2;n[l.symbol_id].score<5&&(n[l.symbol_id].score+=p);let u=d?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.symbol_id].reasons.includes(u)&&n[l.symbol_id].reasons.length<5&&n[l.symbol_id].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
235
215
  SELECT kind, COUNT(*) as c
236
216
  FROM exports
237
217
  WHERE kind IS NOT NULL AND kind != ''
@@ -244,7 +224,7 @@ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDe
244
224
  OR name LIKE ?
245
225
  OR name LIKE ?
246
226
  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)),l=[];if(i==="both"||i==="outbound"){let c=`
227
+ `,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=`
248
228
  SELECT
249
229
  id,
250
230
  file_path,
@@ -257,7 +237,7 @@ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDe
257
237
  'outbound' AS direction
258
238
  FROM type_graph_edges
259
239
  WHERE source_symbol_name = ?
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=`
240
+ `,d=[e];n&&(l+=" AND file_path = ?",d.push(n)),r&&(l+=" AND relationship = ?",d.push(r)),l+=" ORDER BY file_path ASC, line_number ASC, target_symbol_name ASC LIMIT ?",d.push(a),c.push(...this.all(l,...d))}if(i==="both"||i==="inbound"){let l=`
261
241
  SELECT
262
242
  id,
263
243
  file_path,
@@ -270,7 +250,99 @@ var ml=Object.create;var ps=Object.defineProperty;var fl=Object.getOwnPropertyDe
270
250
  'inbound' AS direction
271
251
  FROM type_graph_edges
272
252
  WHERE target_symbol_name = ?
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=`
253
+ `,d=[e];r&&(l+=" AND relationship = ?",d.push(r)),l+=" ORDER BY file_path ASC, line_number ASC, source_symbol_name ASC LIMIT ?",d.push(a),c.push(...this.all(l,...d))}return c.slice(0,a)}findTypeGraphEdgesBySymbolId(e,t={}){let n=this.findById(e);return n?this.findTypeGraphEdges(n.name,{...t,filePath:n.file_path}):[]}}});function Am(s,e){if(!s)return!1;let t=s.trim();return!t||Cm.has(t.toLowerCase())||e.has(t)?!1:/^[A-Za-z_$][A-Za-z0-9_$.]*$/.test(t)}function Im(s){return s.split(/[,|&]/).map(e=>e.trim()).filter(Boolean)}function Pm(s){let e=s.replace(/^[({[]+/,"").replace(/[)}\]]+$/,"").replace(/^readonly\s+/,"").trim();return e&&e.match(/^([A-Za-z_$][A-Za-z0-9_$.]*)/)?.[1]||null}function Lm(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 Nm(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 so(s,e){let t=[];for(let n of Im(s)){let i=Pm(n);i&&Am(i,e)&&t.push(i)}return t}function sc(s){if(!s)return[];let e=s.replace(/\s+/g," ").trim();if(!e)return[];let t=Lm(e),n=Nm(t),i=[],r=new Set,o=(l,d,p)=>{let u=`${l}:${d}`;r.has(u)||(r.add(u),i.push({relationship:l,targetName:d,...p?{metadata:p}:{}}))},a=e.match(/\bextends\s+(.+?)(?=\bimplements\b|\{|=|$)/);if(a?.[1]){let l=so(a[1],n);for(let d of l)o("extends",d,a[1].trim())}let c=e.match(/\bimplements\s+(.+?)(?=\{|=|$)/);if(c?.[1]){let l=so(c[1],n);for(let d of l)o("implements",d,c[1].trim())}for(let l of t){let d=/([A-Za-z_$][A-Za-z0-9_$]*)\s+extends\s+([^,>]+)/g,p=null;for(;(p=d.exec(l))!==null;){let u=p[2]?.trim();if(!u)continue;let m=so(u,n);for(let f of m)o("constrained_by",f,u)}}return i}var Cm,ic=oe(()=>{"use strict";Cm=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 Mm from"path";var fi,rc=oe(()=>{"use strict";ic();ft();fi=class extends Se{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=Mm.resolve(e,t),i=n.endsWith("/")?n:n+"/";return this.all(`
254
+ SELECT * FROM files
255
+ WHERE (path LIKE ? OR path = ?)
256
+ ORDER BY path ASC
257
+ `,`${i}%`,n)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
258
+ SELECT files.*, files_fts.rank
259
+ FROM files_fts
260
+ JOIN files ON files.rowid = files_fts.rowid
261
+ WHERE files_fts MATCH ?
262
+ ORDER BY rank
263
+ LIMIT ?
264
+ `,e,t)}findByPathKeywords(e,t=10){let n=e.map(()=>"LOWER(path) LIKE ?").join(" OR ");return this.all(`
265
+ SELECT * FROM files
266
+ WHERE ${n}
267
+ LIMIT ?
268
+ `,...e.map(i=>`%${i}%`),t)}findContentFts(e,t=50){let n=this.buildContentFtsQuery(e);return n?this.all(`
269
+ SELECT
270
+ files.*,
271
+ bm25(content_fts, 0.2, 1.0) AS bm25_rank
272
+ FROM content_fts
273
+ JOIN files ON files.path = content_fts.file_path
274
+ WHERE content_fts MATCH ?
275
+ ORDER BY bm25_rank ASC
276
+ LIMIT ?
277
+ `,n,Math.max(1,Math.min(t,1e3))):[]}getContent(e){return this.get("SELECT content FROM file_content WHERE file_path = ?",e)?.content}findContentByToken(e,t=10){return this.all(`
278
+ SELECT file_path
279
+ FROM content_fts
280
+ WHERE content_fts MATCH ?
281
+ AND (file_path LIKE '%.ts' OR file_path LIKE '%.tsx' OR file_path LIKE '%.js' OR file_path LIKE '%.py' OR file_path LIKE '%.php')
282
+ AND file_path NOT LIKE '%/test/%'
283
+ AND file_path NOT LIKE '%.spec.%'
284
+ LIMIT ?
285
+ `,`"${e.replace(/[^a-zA-Z0-9_/]/g," ")}"`,t).map(i=>i.file_path)}findSynapses(e){let t="SELECT * FROM event_synapses WHERE 1=1",n=[];if(e.type&&(t+=" AND type = ?",n.push(e.type)),e.name){let i=e.name;i.startsWith("/")&&(i=i.substring(1)),i.endsWith("/")&&(i=i.substring(0,i.length-1)),i.length>0&&(t+=" AND (name LIKE ? OR name LIKE ? OR name = ?)",n.push(`${i}%`),n.push(`%/${i}%`),n.push(e.name))}return e.direction&&(t+=" AND direction = ?",n.push(e.direction)),t+=` LIMIT ${e.limit||50}`,this.all(t,...n)}exists(e){return!!this.get("SELECT 1 FROM files WHERE path = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE files SET ${i} WHERE path = ?`,...r)}getStats(){let e=this.get(`
286
+ SELECT
287
+ COUNT(*) as total,
288
+ SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
289
+ FROM files
290
+ `);return{total:e?.total||0,withSummary:e?.withSummary||0}}getGravityMap(e=[],t){let n={},i=`
291
+ SELECT ws.file_path, m.name as mission_name, m.status
292
+ FROM working_set ws
293
+ JOIN missions m ON ws.mission_id = m.id
294
+ WHERE (
295
+ (m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
296
+ OR m.id IN (${e.length>0?e.join(","):"-1"})
297
+ )
298
+ AND ws.file_path IS NOT NULL
299
+ `,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 d=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.file_path].score+=d;let p=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.file_path].reasons.push(`${p}: ${l.mission_name}`)}let a=Math.floor(Date.now()/1e3)-86400,c=this.all(`
300
+ SELECT file_path, type, mission_id
301
+ FROM intent_logs
302
+ WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
303
+ AND file_path IS NOT NULL
304
+ ORDER BY created_at DESC
305
+ LIMIT 100
306
+ `,a);for(let l of c){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let d=l.mission_id?e.includes(l.mission_id):!1,p=d?.1:.2;n[l.file_path].score<5&&(n[l.file_path].score+=p);let u=d?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.file_path].reasons.includes(u)&&n[l.file_path].reasons.length<5&&n[l.file_path].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
307
+ SELECT
308
+ SUBSTR(path, LENGTH(?) + 2,
309
+ INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
310
+ ) as root,
311
+ COUNT(*) as total_files,
312
+ SUM(CASE
313
+ WHEN path LIKE '%.ts' OR path LIKE '%.tsx'
314
+ OR path LIKE '%.js' OR path LIKE '%.jsx'
315
+ OR path LIKE '%.mjs' OR path LIKE '%.cjs'
316
+ THEN 1 ELSE 0
317
+ END) as ts_files
318
+ FROM files
319
+ WHERE path LIKE ? || '/%/%'
320
+ GROUP BY root
321
+ ORDER BY total_files DESC
322
+ LIMIT ?
323
+ `,e,e,e,t)}hasFilesPattern(e){return!!this.get("SELECT 1 FROM files WHERE path LIKE ? LIMIT 1",e)}findPackageJsonChildren(e){return this.all(`
324
+ SELECT
325
+ path,
326
+ SUBSTR(path, LENGTH(?) + 2) as relPath
327
+ FROM files
328
+ WHERE path LIKE ? || '/%/package.json'
329
+ `,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 = ?"),d=this.db.prepare("DELETE FROM type_graph_edges WHERE file_path = ?"),p=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),u=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),f=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),h=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),y=this.db.prepare("INSERT INTO type_graph_edges (file_path, source_symbol_id, source_symbol_name, target_symbol_name, relationship, line_number, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)"),b=this.db.prepare(`
330
+ INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
331
+ VALUES (?, ?, ?, ?, ?, ?, ?)
332
+ ON CONFLICT(path) DO UPDATE SET
333
+ mtime=excluded.mtime,
334
+ last_scanned_at=excluded.last_scanned_at,
335
+ classification=excluded.classification,
336
+ summary=excluded.summary,
337
+ embedding=excluded.embedding,
338
+ content_hash=excluded.content_hash
339
+ `),g=this.db.transaction(A=>{for(let x of A){let{meta:E,exports:I,imports:N,configs:P,events:C,content:W,classification:j,summary:K,embedding:U,contentHash:H}=x;r.run(E.path),o.run(E.path),a.run(E.path),c.run(E.path),l.run(E.path),d.run(E.path);let M=H??(W&&n?n(W):null);if(b.run(E.path,E.mtime,Date.now(),j||"Unknown",K||"",U?JSON.stringify(U):null,M),I){let D=(O,Y,z)=>{for(let v of Y){let _=v.embedding?JSON.stringify(v.embedding):null,R=p.run(O,v.name,v.kind,v.signature,v.doc||"",v.line,v.endLine||v.line,v.classification||"Other",v.capabilities||"[]",z,_),T=Number(R.lastInsertRowid);if(Number.isFinite(T)){let $=sc(v.signature);for(let F of $)F.targetName!==v.name&&y.run(O,T,v.name,F.targetName,F.relationship,v.line,F.metadata||null)}v.members&&v.members.length>0&&D(O,v.members,R.lastInsertRowid)}};D(E.path,I,null)}if(N)for(let D of N){let O=D.resolved_path!==void 0?D.resolved_path:i?.(D.module,E.path,t)??"";u.run(E.path,D.module,D.name,O)}if(P)for(let D of P)m.run(E.path,D.key,D.value,D.kind);if(W!==void 0&&f.run(E.path,W),C)for(let D of C)h.run(E.path,D.type,D.name,D.direction,D.line,D.snippet)}}),w=500;for(let A=0;A<e.length;A+=w)g(e.slice(A,A+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 hi,oc=oe(()=>{"use strict";ft();hi=class extends Se{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(`
340
+ INSERT INTO hologram_snapshot (section, data, updated_at)
341
+ VALUES (?, ?, unixepoch())
342
+ ON CONFLICT(section) DO UPDATE SET
343
+ data = excluded.data,
344
+ updated_at = excluded.updated_at
345
+ `,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 ac,cc=oe(()=>{"use strict";ac=`
274
346
  WITH RECURSIVE dependency_chain AS (
275
347
  -- Base case: Direct dependents of the target symbol
276
348
  -- Meaning: Files that import the file where the symbol is defined
@@ -321,7 +393,7 @@ SELECT DISTINCT
321
393
  dc.imported_symbols
322
394
  FROM dependency_chain dc
323
395
  ORDER BY dc.depth, dc.consumer_path;
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(`
396
+ `});var gi,lc=oe(()=>{"use strict";cc();ft();gi=class extends Se{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
397
  SELECT * FROM imports
326
398
  WHERE resolved_path IS NOT NULL AND resolved_path != ''
327
399
  `)}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,119 +419,28 @@ ORDER BY dc.depth, dc.consumer_path;
347
419
  SELECT COUNT(*) as count FROM imports
348
420
  WHERE resolved_path IN (${n})
349
421
  AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
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
- CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
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
- CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
354
- created_at ASC`,this.all(t,...n)}findRecentCompleted(e=3){return this.all(`
355
- SELECT * FROM missions
356
- WHERE status = 'completed'
357
- ORDER BY updated_at DESC, id DESC
422
+ `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(ac,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});var yi,pc=oe(()=>{"use strict";q();ft();yi=class s extends Se{findByMission(e,t=50){return this.all(`
423
+ SELECT
424
+ id, mission_id, symbol_id, file_path, type, content, confidence,
425
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
426
+ created_at
427
+ FROM intent_logs
428
+ WHERE mission_id = ?
429
+ ORDER BY created_at DESC
358
430
  LIMIT ?
359
- `,e)}create(e){return this.insert(`
360
- INSERT INTO missions (name, goal, strategy_graph, status, git_branch, commit_sha, parent_id, verification_context, outcome_contract)
431
+ `,e,t)}findRecentDecisionActivity(e=10){return this.all(`
432
+ SELECT
433
+ id, mission_id, symbol_id, file_path, type, content, confidence,
434
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
435
+ created_at
436
+ FROM intent_logs
437
+ WHERE type IN ('decision', 'system', 'fix', 'heritage', 'adr')
438
+ ORDER BY created_at DESC
439
+ LIMIT ?
440
+ `,e)}create(e){let t=this.insert(`
441
+ INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
361
442
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
362
- `,e.name,e.goal,e.strategy_graph,e.status,e.git_branch,e.commit_sha,e.parent_id,e.verification_context,e.outcome_contract)}addArtifact(e,t,n,i){this.run("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,t,n,i?JSON.stringify(i):null)}getArtifacts(e){return this.all("SELECT * FROM mission_artifacts WHERE mission_id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE missions SET ${i}, updated_at = unixepoch() WHERE id = ?`,...r)}updateStatus(e,t,n){n?this.run("UPDATE missions SET status = ?, updated_at = unixepoch(), commit_sha = ? WHERE id = ?",t,n,e):this.run("UPDATE missions SET status = ?, updated_at = unixepoch() WHERE id = ?",t,e)}getWorkingSet(e){let t=this.all(`
363
- SELECT file_path, type, source_priority, created_at
364
- FROM (
365
- SELECT
366
- ws.file_path,
367
- COALESCE(ws.type, 'file') AS type,
368
- 0 AS source_priority,
369
- ws.created_at
370
- FROM working_set ws
371
- WHERE ws.mission_id = ?
372
-
373
- UNION ALL
374
-
375
- SELECT
376
- il.file_path,
377
- 'intent' AS type,
378
- 1 AS source_priority,
379
- il.created_at
380
- FROM intent_logs il
381
- WHERE il.mission_id = ?
382
- AND il.file_path IS NOT NULL
383
-
384
- UNION ALL
385
-
386
- SELECT
387
- e.file_path,
388
- 'symbol' AS type,
389
- 2 AS source_priority,
390
- il.created_at
391
- FROM intent_logs il
392
- JOIN exports e ON e.id = il.symbol_id
393
- WHERE il.mission_id = ?
394
- AND e.file_path IS NOT NULL
395
- )
396
- WHERE file_path IS NOT NULL
397
- ORDER BY source_priority ASC, created_at DESC, file_path ASC
398
- `,e,e,e),n=new Map;for(let i of t)!i.file_path||n.has(i.file_path)||n.set(i.file_path,{file_path:i.file_path,type:i.type||"file"});return[...n.values()]}clearWorkingSet(e){this.run("DELETE FROM working_set WHERE mission_id = ?",e)}addToWorkingSet(e,t,n="file"){this.run("INSERT OR IGNORE INTO files (path, mtime, last_scanned_at) VALUES (?, unixepoch(), unixepoch())",t),this.run("INSERT INTO working_set (mission_id, file_path, type) VALUES (?, ?, ?)",e,t,n)}findColdMissions(e,t=10){return this.all(`
399
- SELECT m.id, COUNT(il.id) as log_count
400
- FROM missions m
401
- LEFT JOIN intent_logs il ON il.mission_id = m.id
402
- WHERE m.updated_at < ?
403
- AND m.status != 'distilled'
404
- GROUP BY m.id
405
- HAVING log_count > ?
406
- `,e,t).map(i=>i.id)}getStats(){let e=this.get(`
407
- SELECT
408
- COUNT(*) as total,
409
- SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
410
- SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
411
- FROM missions
412
- `);return{total:e?.total||0,completed:e?.completed||0,active:e?.active||0}}getAnalytics(){let e=this.getStats(),t=e.total>0?Math.round(e.completed/e.total*100):0,n=this.get(`
413
- SELECT AVG(updated_at - created_at) AS avg_duration
414
- FROM missions
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),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
- SET status = 'suspended', updated_at = unixepoch()
418
- WHERE git_branch = ? AND status IN ('in-progress', 'verifying')`,e)}resumeByBranch(e){return this.run(`UPDATE missions
419
- SET status = 'in-progress', updated_at = unixepoch()
420
- WHERE git_branch = ? AND status = 'suspended'`,e)}findMergedMissions(e,t){if(t.length===0)return[];let n=t.filter(r=>r!==e);if(n.length===0)return[];let i=n.map(()=>"?").join(",");return this.all(`SELECT * FROM missions
421
- WHERE status IN ('in-progress', 'planned', 'verifying', 'suspended')
422
- AND git_branch IN (${i})`,...n)}findByCommitShas(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.all(`SELECT * FROM missions WHERE commit_sha IN (${t})`,...e)}findByParentId(e){return this.all("SELECT * FROM missions WHERE parent_id = ?",e)}hasChildren(e){return!!this.get("SELECT 1 FROM missions WHERE parent_id = ? LIMIT 1",e)}hasNoSteps(e){if(!e.strategy_graph)return!0;try{let t=JSON.parse(e.strategy_graph),n=t?.steps??t;return!Array.isArray(n)||n.length===0}catch{return!0}}findParentOnlyIds(e){return e.filter(t=>t.parent_id!=null||!this.hasChildren(t.id)?!1:this.hasNoSteps(t)).map(t=>t.id)}createLink(e,t,n,i,r){this.db.exec(`
423
- CREATE TABLE IF NOT EXISTS cross_repo_links (
424
- id INTEGER PRIMARY KEY AUTOINCREMENT,
425
- mission_id INTEGER NOT NULL,
426
- linked_repo_path TEXT NOT NULL,
427
- linked_mission_id INTEGER NOT NULL,
428
- relationship TEXT,
429
- direction TEXT,
430
- created_at REAL DEFAULT (unixepoch()),
431
- FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
432
- );
433
- CREATE INDEX IF NOT EXISTS idx_cross_repo_mission ON cross_repo_links(mission_id);
434
- `),this.run(`
435
- INSERT INTO cross_repo_links (mission_id, linked_repo_path, linked_mission_id, relationship, direction)
436
- VALUES (?, ?, ?, ?, ?)
437
- `,e,t,n,i,r)}getLinks(e){try{return this.all(`
438
- SELECT linked_repo_path, linked_mission_id, relationship, direction
439
- FROM cross_repo_links
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=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
- SELECT
443
- id, mission_id, symbol_id, file_path, type, content, confidence,
444
- symbol_name, signature, commit_sha, is_crystallized, crystal_id,
445
- created_at
446
- FROM intent_logs
447
- WHERE mission_id = ?
448
- ORDER BY created_at DESC
449
- LIMIT ?
450
- `,e,t)}findRecentDecisionActivity(e=10){return this.all(`
451
- SELECT
452
- id, mission_id, symbol_id, file_path, type, content, confidence,
453
- symbol_name, signature, commit_sha, is_crystallized, crystal_id,
454
- created_at
455
- FROM intent_logs
456
- WHERE type IN ('decision', 'system', 'fix', 'heritage', 'adr')
457
- ORDER BY created_at DESC
458
- LIMIT ?
459
- `,e)}create(e){let t=this.insert(`
460
- INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
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=>{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(`
443
+ `,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=>{k.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(()=>(Ge(),vt)),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(()=>(Ge(),vt)),r=this.findWithEmbeddings();if(r.length>5e3)return k.warn({count:r.length},"Intent log count exceeds brute-force vector scan limit (5000). Skipping semantic recall."),[];let o=[];for(let a of r)if(!(n&&a.symbol_id===n))try{let c=JSON.parse(a.embedding),l=i(e,c);l>.25&&o.push({id:a.id,mission_id:a.mission_id,type:a.type,content:a.content,symbol_name:a.symbol_name,file_path:a.file_path,similarity:l,created_at:a.created_at})}catch{}return o.sort((a,c)=>c.similarity-a.similarity).slice(0,t)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${i} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
463
444
  SELECT id, file_path, symbol_name, signature
464
445
  FROM intent_logs
465
446
  WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
@@ -516,7 +497,7 @@ ORDER BY dc.depth, dc.consumer_path;
516
497
  VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
517
498
  SET is_crystallized = 1, crystal_id = ?
518
499
  WHERE mission_id = ? AND is_crystallized = 0 AND id != ?
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
500
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,i,e,i),this.generateAndStoreEmbedding(i,{type:"crystal",content:t}).catch(r=>{k.debug({err:r,intentLogId:i},"Failed to refresh crystal embedding")}),i})}findRawBySymbol(e){return this.all(`SELECT * FROM intent_logs
520
501
  WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0
521
502
  AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
522
503
  ORDER BY created_at ASC`,e)}findCrystallizableBySymbol(e){return this.all(`SELECT
@@ -532,7 +513,7 @@ ORDER BY dc.depth, dc.consumer_path;
532
513
  VALUES (NULL, ?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
533
514
  SET is_crystallized = 1, crystal_id = ?
534
515
  WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0 AND id != ?
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
516
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,i,e,i),this.generateAndStoreEmbedding(i,{type:"crystal",content:t}).catch(r=>{k.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
536
517
  FROM intent_logs
537
518
  WHERE mission_id IN (${t})
538
519
  AND type NOT IN ('system', 'adr', 'lapsed')
@@ -546,452 +527,371 @@ ORDER BY dc.depth, dc.consumer_path;
546
527
  FROM intent_logs
547
528
  WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
548
529
  AND created_at > ?
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(`
551
- SELECT file_path, key, value, kind
552
- FROM configs
553
- WHERE key LIKE ? OR value LIKE ?
554
- LIMIT ?
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(`
556
- SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
557
- FROM content_fts
558
- WHERE content_fts MATCH ?
530
+ 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(()=>(Ge(),vt)),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 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)
531
+ 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(()=>(Ge(),vt)),i=[...s.EMBEDDABLE_TYPES].map(d=>`'${d}'`).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(d=>s.buildEmbeddingText(d)),a=await n(o,e,t),c=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),l=0;return this.transaction(()=>{for(let d=0;d<r.length;d++)a[d]&&(c.run(JSON.stringify(a[d]),r[d].id),l++)}),k.info({total:r.length,embedded:l},"Intent log embedding backfill complete"),l}}});var bi,dc=oe(()=>{"use strict";ft();bi=class extends Se{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
532
+ CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
533
+ 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
534
+ CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
535
+ created_at ASC`,this.all(t,...n)}findRecentCompleted(e=3){return this.all(`
536
+ SELECT * FROM missions
537
+ WHERE status = 'completed'
538
+ ORDER BY updated_at DESC, id DESC
559
539
  LIMIT ?
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 (
562
- SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
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(`
564
- INSERT INTO hologram_snapshot (section, data, updated_at)
565
- VALUES (?, ?, unixepoch())
566
- ON CONFLICT(section) DO UPDATE SET
567
- data = excluded.data,
568
- updated_at = excluded.updated_at
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
628
- # Liquid Shadow: Auto-refresh index after merge/pull
629
- # Generated by liquid-shadow
630
-
631
- REPO_PATH="$(git rev-parse --show-toplevel)"
632
-
633
- # Run liquid-shadow sync in background to avoid blocking git operations
634
- nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
635
-
636
- exit 0
637
- `,"post-checkout":`#!/bin/sh
638
- # Liquid Shadow: Auto-refresh index after branch checkout
639
- # Generated by liquid-shadow
640
-
641
- # Only run on branch checkouts, not file checkouts
642
- # $3 is 1 for branch checkout, 0 for file checkout
643
- [ "$3" = "1" ] || exit 0
644
-
645
- # Skip no-op checkouts where HEAD does not change
646
- [ "$1" = "$2" ] && exit 0
647
-
648
- REPO_PATH="$(git rev-parse --show-toplevel)"
649
- LOG_DIR="$HOME/.mcp-liquid-shadow/logs"
650
- LOG_FILE="$LOG_DIR/post-checkout.log"
651
-
652
- mkdir -p "$LOG_DIR"
653
-
654
- # Run incremental index in background (default mode preserves fast-path)
655
- nohup "${s}" "${e}" index "$REPO_PATH" >> "$LOG_FILE" 2>&1 &
656
-
657
- exit 0
658
- `,"post-commit":`#!/bin/sh
659
- # Liquid Shadow: Trigger symbol shift detection after commit
660
- # Generated by liquid-shadow
661
-
662
- REPO_PATH="$(git rev-parse --show-toplevel)"
663
-
664
- # Run liquid-shadow sync in background
665
- nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
666
-
667
- exit 0
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`
692
- (function_definition name: (name) @name) @func
693
- (class_declaration name: (name) @name) @class
694
- (interface_declaration name: (name) @name) @interface
695
- (trait_declaration name: (name) @name) @trait
696
- (method_declaration name: (name) @name) @method
697
- (namespace_use_declaration (namespace_use_clause (qualified_name) @name)) @import
698
- `;case".py":return`
699
- (function_definition name: (identifier) @name) @func
700
- (class_definition name: (identifier) @name) @class
701
- (import_statement name: (dotted_name) @name) @import
702
- (import_from_statement module_name: (dotted_name) @name) @import
703
- `;case".go":return`
704
- (function_declaration name: (identifier) @name) @func
705
- (method_declaration name: (identifier) @name) @func
706
- (type_declaration (type_spec name: (identifier) @name)) @type
707
- (import_spec path: (interpreted_string_literal) @name) @import
708
- `;case".rs":return`
709
- (function_item name: (identifier) @name) @func
710
- (struct_item name: (_type_identifier) @name) @struct
711
- (enum_item name: (_type_identifier) @name) @enum
712
- (trait_item name: (_type_identifier) @name) @trait
713
- (type_item name: (_type_identifier) @name) @type
714
- (use_declaration argument: (_) @name) @import
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)}%)
742
- `+"\u2500".repeat(40)+`
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(`
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(`
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}
757
- class TraceContext {
758
- ${u}
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+=`
762
- \u269B\uFE0F Hologram: Refreshed architectural map (${h.length} hotspots).`,o.repaired>0&&(m+=`
763
- \u2728 Nano-Repair: Fixed ${o.repaired} links.`),m+=`
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
767
-
768
- `;return o.length===0&&a.length===0?u+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
769
- `:(o.length>0&&(u+=`## \u274C Structural Violations
770
- `,o.forEach(d=>u+=`- ${d}
771
- `),u+=`
772
- `),a.length>0&&(u+=`## \u26A0\uFE0F Architectural Warnings
773
- `,a.forEach(d=>u+=`- ${d}
774
- `),u+=`
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)}
777
- `),console.log(`Detected Pattern: **${r.pattern}** (Confidence: ${r.patternConfidence.toFixed(0)}%)`),r.insights.length>0&&(console.log(`
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(`
783
- `).trim();return a>0&&(u=`...
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}".
786
-
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?`
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)
789
-
790
- Showing ${w.length} of ${d} file(s) (offset: ${n}, limit: ${t})${U}
791
-
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(`
793
- `)+`
794
-
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?`
796
- > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"";return{content:[{type:"text",text:`# Resolved paths: "${e}"
797
-
798
- Showing ${m.length} of ${d} file(s) (offset: ${n}, limit: ${t})${b}
799
-
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?`
802
- > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",U=o?`
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}"
806
-
807
- Showing ${R.length} of ${k} file(s) above the ${Math.round(d*100)}% evidence floor (offset: ${n}, limit: ${t})${N}${U}${H}${C}
808
-
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}
812
-
813
- `+(W.snippet?`**Matched Snippet**:
814
- \`\`\`typescript
815
- ${W.snippet}
816
- \`\`\`
817
-
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&&($+=`
822
-
823
- ### Folded Lower-Relevance Matches (${S.length})
824
- _Expanded blocks omitted to stay within token budget._
825
- `+S.join(`
826
- `))}else $=M+A.map(W=>W.text).join(`
827
- `);if(E.length>0){let W=`
828
-
829
- ---
830
- ## Intent Vectors (${E.length} matching decision(s))
831
-
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}
834
- `}).join(`
835
- `),J=`
836
-
837
- ---
838
- ## Intent Vectors (${E.length} matching decision(s))
839
-
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}"
843
-
844
- \u26A0\uFE0F No semantic matches cleared the ${Math.round(d*100)}% evidence floor (${k.withSummary}/${k.total} summaries indexed).
845
-
846
- Found ${w.length} file(s) with matching paths:
847
-
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(`
850
- `);return{content:[{type:"text",text:`# Semantic Concept Search: "${e}"
851
-
852
- No semantic matches cleared the evidence floor (${Math.round(d*100)}% required for ${u.profile} queries).
853
-
854
- Low-confidence candidates were suppressed instead of being presented as relevant matches:
855
- ${N?`
856
- ${N}
857
-
858
- `:`
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}"
860
-
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(`
862
- `);return{content:[{type:"text",text:`No symbols found matching all terms: "${e}"
863
-
864
- **Partial matches:**
865
- ${L}
866
-
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(`
868
- `);return{content:[{type:"text",text:`No symbols found matching: "${e}"
869
-
870
- **Did you mean?**
871
- ${B}
872
-
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}"
874
-
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}"
878
-
879
- Showing ${U.length} matching symbol(s)${N?` (use offset=${n+t} for more)`:""}:
880
-
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+=`
886
- \`\`\`typescript
887
- ${C.snippet}
888
- \`\`\`
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.
893
-
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)
895
-
896
- \u26A0\uFE0F **${y} likely orphaned setting(s)** (no in-repo code references detected in code-backed config)
897
-
898
- Found ${m.length} match(es):
899
-
900
- `:`# Configuration Search: "${a}" (with Usage Analysis)
901
-
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(`
910
-
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}"
912
-
913
- Found ${m.length} match(es):
914
-
915
- `+f.map(g=>`## ${g.file} (${g.kind})
916
- **${g.key}**: \`${g.value}\``).join(`
917
-
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
919
-
920
- `;return y+=`**Summary**: ${g} config(s) found, ${f} likely orphaned, ${b} external/runtime-only
921
-
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+=`
925
-
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+=`
929
-
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+=`
933
-
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.
935
-
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=`
941
-
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(`
949
- `);return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
950
-
951
- Suggestions:
952
- ${L}
953
-
954
- Next steps:
955
- \u2022 Search semantically: shadow_search_concept({ query: "${i}" })
956
- \u2022 Verify repository is indexed: shadow_sync_index({ repoPath: "${e}" })`}]}}return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
540
+ `,e)}create(e){return this.insert(`
541
+ INSERT INTO missions (name, goal, strategy_graph, status, git_branch, commit_sha, parent_id, verification_context, outcome_contract)
542
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
543
+ `,e.name,e.goal,e.strategy_graph,e.status,e.git_branch,e.commit_sha,e.parent_id,e.verification_context,e.outcome_contract)}addArtifact(e,t,n,i){this.run("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,t,n,i?JSON.stringify(i):null)}getArtifacts(e){return this.all("SELECT * FROM mission_artifacts WHERE mission_id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE missions SET ${i}, updated_at = unixepoch() WHERE id = ?`,...r)}updateStatus(e,t,n){n?this.run("UPDATE missions SET status = ?, updated_at = unixepoch(), commit_sha = ? WHERE id = ?",t,n,e):this.run("UPDATE missions SET status = ?, updated_at = unixepoch() WHERE id = ?",t,e)}getWorkingSet(e){let t=this.all(`
544
+ SELECT file_path, type, source_priority, created_at
545
+ FROM (
546
+ SELECT
547
+ ws.file_path,
548
+ COALESCE(ws.type, 'file') AS type,
549
+ 0 AS source_priority,
550
+ ws.created_at
551
+ FROM working_set ws
552
+ WHERE ws.mission_id = ?
957
553
 
958
- Next steps:
959
- \u2022 Search for it: shadow_search_concept({ query: "${i}" })
960
- \u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${i}", filePath: "..." })
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+`
554
+ UNION ALL
963
555
 
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
965
- \u{1F4CA} Semantic Fold Applied (context: "definition")
556
+ SELECT
557
+ il.file_path,
558
+ 'intent' AS type,
559
+ 1 AS source_priority,
560
+ il.created_at
561
+ FROM intent_logs il
562
+ WHERE il.mission_id = ?
563
+ AND il.file_path IS NOT NULL
966
564
 
967
- Original file: ${f.totalOriginalLines} lines
968
- Folded view: ${f.foldedToLines} lines
969
- Target Symbol: ${l.name}
970
- \u{1F4A1} Need more context?
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(`
974
- `)+`
565
+ UNION ALL
975
566
 
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(`
567
+ SELECT
568
+ e.file_path,
569
+ 'symbol' AS type,
570
+ 2 AS source_priority,
571
+ il.created_at
572
+ FROM intent_logs il
573
+ JOIN exports e ON e.id = il.symbol_id
574
+ WHERE il.mission_id = ?
575
+ AND e.file_path IS NOT NULL
576
+ )
577
+ WHERE file_path IS NOT NULL
578
+ ORDER BY source_priority ASC, created_at DESC, file_path ASC
579
+ `,e,e,e),n=new Map;for(let i of t)!i.file_path||n.has(i.file_path)||n.set(i.file_path,{file_path:i.file_path,type:i.type||"file"});return[...n.values()]}clearWorkingSet(e){this.run("DELETE FROM working_set WHERE mission_id = ?",e)}addToWorkingSet(e,t,n="file"){this.run("INSERT OR IGNORE INTO files (path, mtime, last_scanned_at) VALUES (?, unixepoch(), unixepoch())",t),this.run("INSERT INTO working_set (mission_id, file_path, type) VALUES (?, ?, ?)",e,t,n)}findColdMissions(e,t=10){return this.all(`
580
+ SELECT m.id, COUNT(il.id) as log_count
581
+ FROM missions m
582
+ LEFT JOIN intent_logs il ON il.mission_id = m.id
583
+ WHERE m.updated_at < ?
584
+ AND m.status != 'distilled'
585
+ GROUP BY m.id
586
+ HAVING log_count > ?
587
+ `,e,t).map(i=>i.id)}getStats(){let e=this.get(`
588
+ SELECT
589
+ COUNT(*) as total,
590
+ SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
591
+ SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
592
+ FROM missions
593
+ `);return{total:e?.total||0,completed:e?.completed||0,active:e?.active||0}}getAnalytics(){let e=this.getStats(),t=e.total>0?Math.round(e.completed/e.total*100):0,n=this.get(`
594
+ SELECT AVG(updated_at - created_at) AS avg_duration
595
+ FROM missions
596
+ WHERE status = 'completed' AND updated_at > created_at
597
+ `),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,d=c?.n??0,p=`${l} completed in last 7 days, ${d} in last 30 days.`;if(i!=null){let u=Math.round(i/60);p+=` Avg mission duration: ${u} min.`}return{completionRate:t,averageDurationSeconds:i,completedLast7Days:l,completedLast30Days:d,velocityNote:p}}suspendByBranch(e){return this.run(`UPDATE missions
598
+ SET status = 'suspended', updated_at = unixepoch()
599
+ WHERE git_branch = ? AND status IN ('in-progress', 'verifying')`,e)}resumeByBranch(e){return this.run(`UPDATE missions
600
+ SET status = 'in-progress', updated_at = unixepoch()
601
+ WHERE git_branch = ? AND status = 'suspended'`,e)}findMergedMissions(e,t){if(t.length===0)return[];let n=t.filter(r=>r!==e);if(n.length===0)return[];let i=n.map(()=>"?").join(",");return this.all(`SELECT * FROM missions
602
+ WHERE status IN ('in-progress', 'planned', 'verifying', 'suspended')
603
+ AND git_branch IN (${i})`,...n)}findByCommitShas(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.all(`SELECT * FROM missions WHERE commit_sha IN (${t})`,...e)}findByParentId(e){return this.all("SELECT * FROM missions WHERE parent_id = ?",e)}hasChildren(e){return!!this.get("SELECT 1 FROM missions WHERE parent_id = ? LIMIT 1",e)}hasNoSteps(e){if(!e.strategy_graph)return!0;try{let t=JSON.parse(e.strategy_graph),n=t?.steps??t;return!Array.isArray(n)||n.length===0}catch{return!0}}findParentOnlyIds(e){return e.filter(t=>t.parent_id!=null||!this.hasChildren(t.id)?!1:this.hasNoSteps(t)).map(t=>t.id)}createLink(e,t,n,i,r){return this.ensureCrossRepoLinksSchema(),this.run(`
604
+ INSERT OR IGNORE INTO cross_repo_links (mission_id, linked_repo_path, linked_mission_id, relationship, direction)
605
+ VALUES (?, ?, ?, ?, ?)
606
+ `,e,t,n,i,r)}getLink(e,t,n,i){return this.ensureCrossRepoLinksSchema(),this.get(`
607
+ SELECT relationship, direction
608
+ FROM cross_repo_links
609
+ WHERE mission_id = ?
610
+ AND linked_repo_path = ?
611
+ AND linked_mission_id = ?
612
+ AND direction = ?
613
+ LIMIT 1
614
+ `,e,t,n,i)}upsertLink(e,t,n,i,r){return this.ensureCrossRepoLinksSchema(),this.run(`
615
+ INSERT INTO cross_repo_links (
616
+ mission_id,
617
+ linked_repo_path,
618
+ linked_mission_id,
619
+ relationship,
620
+ direction
621
+ )
622
+ VALUES (?, ?, ?, ?, ?)
623
+ ON CONFLICT(mission_id, linked_repo_path, linked_mission_id, direction)
624
+ DO UPDATE SET relationship = excluded.relationship
625
+ `,e,t,n,i,r)}hasLink(e,t,n,i){return this.ensureCrossRepoLinksSchema(),!!this.get(`
626
+ SELECT id
627
+ FROM cross_repo_links
628
+ WHERE mission_id = ?
629
+ AND linked_repo_path = ?
630
+ AND linked_mission_id = ?
631
+ AND direction = ?
632
+ LIMIT 1
633
+ `,e,t,n,i)}deleteLink(e,t,n,i){return this.ensureCrossRepoLinksSchema(),this.run(`
634
+ DELETE FROM cross_repo_links
635
+ WHERE mission_id = ?
636
+ AND linked_repo_path = ?
637
+ AND linked_mission_id = ?
638
+ AND direction = ?
639
+ `,e,t,n,i)}ensureCrossRepoLinksSchema(){this.db.exec(`
640
+ CREATE TABLE IF NOT EXISTS cross_repo_links (
641
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
642
+ mission_id INTEGER NOT NULL,
643
+ linked_repo_path TEXT NOT NULL,
644
+ linked_mission_id INTEGER NOT NULL,
645
+ relationship TEXT,
646
+ direction TEXT,
647
+ created_at REAL DEFAULT (unixepoch()),
648
+ FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
649
+ );
650
+ CREATE INDEX IF NOT EXISTS idx_cross_repo_mission ON cross_repo_links(mission_id);
651
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_cross_repo_unique
652
+ ON cross_repo_links(mission_id, linked_repo_path, linked_mission_id, direction);
653
+ `)}getLinks(e){try{return this.all(`
654
+ SELECT linked_repo_path, linked_mission_id, relationship, direction
655
+ FROM cross_repo_links
656
+ WHERE mission_id = ?
657
+ `,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(()=>(Ge(),vt)).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(()=>(Ge(),vt)),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 c of o)try{let l=JSON.parse(c.embedding),d=n(e,l);d>.3&&a.push({...c,similarity:d})}catch{}return a.sort((c,l)=>l.similarity-c.similarity).slice(0,t?.limit??5)}}});var uc,_i,mc=oe(()=>{"use strict";ft();uc=500,_i=class extends Se{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
658
+ 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)<=uc||this.run(`DELETE FROM search_history WHERE id NOT IN (
659
+ SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
660
+ )`,uc)}}});var L,V=oe(()=>{"use strict";Ae();Za();ec();tc();nc();rc();oc();lc();pc();dc();mc();L=class s{static repositoryCache=new Map;static getInstance(e){let t=s.repositoryCache.get(e);if(t){let r=ye(e),o=t.files?.database,c=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram||!t.claims;if(o===r&&r.open&&!c)return t;s.repositoryCache.delete(e)}let n=ye(e),i={files:new fi(n),exports:new mi(n),imports:new gi(n),missions:new bi(n),intentLogs:new yi(n),configs:new di(n),content:new ui(n),searchHistory:new _i(n),hologram:new hi(n),claims:new pi(n)};return s.repositoryCache.set(e,i),i}static closeInstance(e){s.repositoryCache.delete(e),oi(e)}static clearCache(e){s.repositoryCache.delete(e)}}});var Ii,Pi,Jc,Li,Kc,Vc,Yc,Qc,Xc,Zc,el,tl,nl,sl,Is,Ni,il,rl,mo=oe(()=>{"use strict";Ii=[/\/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],Pi=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],Jc=[/\/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],Kc=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],Vc=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],Yc=[/\/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],Qc=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],Xc=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],Zc=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],el=[/\/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],tl=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],nl=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],sl=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],Is=[/\.(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)$/],Ni=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],il=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],rl=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var Mi,al,$i,cl,fo=oe(()=>{"use strict";Mi=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],al=[/\/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],$i=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],cl=["laravel","symfony","slim","cakephp","codeigniter"]});var Di,pl,Oi,dl,ho=oe(()=>{"use strict";Di=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],pl=[/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],Oi=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],dl=["django.urls","django.http","flask","fastapi","chalice","tornado"]});import ml from"path";function vn(s,e,t){let n=[],i="Unknown",r=0;t||(t=Sf(s,e));let{inDegree:o,outDegree:a}=t,c=(u,m,f,h)=>{for(let y of u)if(y.test(s))return n.push(`${h}: ${y.source}`),i=m,r+=f,!0;return!1},l=!1;if(l||(l=c(Ii,"Entry",45,"Next.js entry")),l||(l=c(Kc,"Entry",40,"MCP handler")),l||(l=c(Yc,"Entry",40,"CLI command")),l||(l=c(Is,"Data",45,"Data layer/Repository")),l||(l=c(el,"Data",35,"State management")),l||(l=c(Jc,"Logic",40,"React component")),l||(l=c(Li,"Logic",35,"Logic pattern")),l||(l=c(Qc,"Logic",35,"Parser/AST")),l||(l=c(Xc,"Logic",35,"Core module")),l||(l=c(Zc,"Logic",30,"UI layer")),l||(l=c(sl,"Types",35,"Type definition")),l||(l=c(Di,"Entry",40,"Python Entry")),l||(l=c(Oi,"Data",40,"Python Data")),l||(l=c(pl,"Logic",35,"Python Logic")),l||(l=c(Mi,"Entry",40,"PHP Entry")),l||(l=c($i,"Data",40,"PHP Data")),l||(l=c(al,"Logic",35,"PHP Logic")),l||(l=c(tl,"Logic",35,"Hook/Context")),!l){for(let u of Vc)if(u.test(s)){n.push(`MCP utility: ${u.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,l=!0;break}}l||c(nl,"Data",35,"Schema definition")&&(l=!0),l||(c(Is,"Data",30,"Path matches data pattern")||c(Ni,"Utility",25,"Path matches utility pattern")||c(Pi,"Entry",30,"Path matches entry pattern"))&&(l=!0);for(let u of go)if(u.test(s)){n.push(`Test file: ${u.source}`),i="Test",r=50,l=!0;break}l||c(yo,"Infrastructure",40,"Infrastructure")&&(l=!0);for(let u of _f)u.test(s)&&(n.push(`Monorepo component: ${u.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let p=e.imports.getImportsForFile(s).map(u=>u.module_specifier.toLowerCase());for(let u of rl)if(p.some(m=>m.includes(u))){n.push(`Imports JS data library: ${u}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let u of dl)if(p.some(m=>m.includes(u))){n.push(`Imports Python framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let u of cl)if(p.some(m=>m.includes(u))){n.push(`Imports PHP framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let u of il)if(p.some(m=>m.includes(u))){n.push(`Imports JS framework: ${u}`),(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 u=o/(o+a);u>.3&&u<.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 Sf(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(f=>({path:f})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let f of t){let h=vn(f.path,s);n.set(f.path,h),i[h.layer].push({path:f.path,classification:h})}let r={Entry:Zt(i.Entry,e),Logic:Zt(i.Logic,e),Data:Zt(i.Data,e),Utility:Zt(i.Utility,e),Infrastructure:Zt(i.Infrastructure,e),Test:Zt(i.Test,e),Types:Zt(i.Types,e),Unknown:Zt(i.Unknown,e)},o={};t.forEach(f=>{let h=ml.extname(f.path).toLowerCase();h&&(o[h]=(o[h]||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(([f,h])=>{let y=a[f];y&&(c[y]=(c[y]||0)+h)});let l=Object.entries(c).sort((f,h)=>h[1]-f[1]),d=l.length>0?l[0][0]:"Unknown",{pattern:p,patternConfidence:u,insights:m}=wf(r,t.length,s);return{pattern:p,patternConfidence:u,layers:r,insights:m,primaryStack:d}}function Zt(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:ml.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function wf(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,d=s.Unknown.count/e*100;o>5&&a>10&&c>5&&d<40?(i="Layered",r=60+Math.min(30,(100-d)/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`)):d>60&&(i="Monolithic",r=40+d/4,n.push(`Limited architectural structure: ${d.toFixed(1)}% files with unclear layer assignment`));let p=t.configs.countByKind("Service");return p>3&&(i="Microservices",r=55+p*5,n.push(`Detected ${p} 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 go,yo,_f,en=oe(()=>{"use strict";mo();fo();ho();go=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],yo=[/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],_f=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});function Uh(s){try{return JSON.stringify(s)}catch{return String(s)}}function Nn(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 Uh(s)}function He(s){if(s instanceof Error){let e;return"cause"in s&&s.cause!==void 0&&(e=Nn(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:Nn(s)}:{errorName:typeof s,errorMessage:Nn(s)}}var Hs=oe(()=>{"use strict"});var dp={};Kr(dp,{HologramService:()=>be});var yt,be,bt=oe(()=>{"use strict";V();Hs();q();en();yt=k.child({module:"hologram"}),be=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=L.getInstance(e)}updateTopography(e){yt.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)),yt.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=kt(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){yt.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)),yt.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){yt.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)),yt.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){yt.debug({repoPath:this.repoPath,section:n.section,...He(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 yt.debug({repoPath:this.repoPath,section:e,...He(n)},"Skipping malformed hologram section"),null}}computeGravityZones(){yt.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=vn(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 d=o.find(u=>u.kind!=="TsTypeAliasDeclaration"&&u.kind!=="TsInterfaceDeclaration")||o[0],p=`${i}::${d.name}`;t.set(p,{symbol:d.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 yt.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),yt.info({repoPath:this.repoPath},"Hologram cleared")}}});var Tp=Vu((Ak,jo)=>{var cr=process||{},kp=cr.argv||[],ar=cr.env||{},Tg=!(ar.NO_COLOR||kp.includes("--no-color"))&&(!!ar.FORCE_COLOR||kp.includes("--color")||cr.platform==="win32"||(cr.stdout||{}).isTTY&&ar.TERM!=="dumb"||!!ar.CI),Cg=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+Ag(i,e,t,r)+e:s+i+e},Ag=(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)},Rp=(s=Tg)=>{let e=s?Cg:()=>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")}};jo.exports=Rp();jo.exports.createColors=Rp});var bd={};Kr(bd,{GraphExporterService:()=>ra});var yd,ra,_d=oe(()=>{"use strict";V();q();yd=k.child({module:"graph-exporter"}),ra=class{constructor(e){this.repoPath=e;this.repos=L.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;yd.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 l=this.repos.missions.findById(e);if(!l)return[];let d={count:0,max:i},p=this.buildFocusedTree(l,t,n,d);return p?[p]:[]}let o=this.repos.missions.findAll().filter(l=>!l.parent_id);t||(o=o.filter(l=>l.status!=="completed"));let a={count:0,max:i},c=[];for(let l of o){if(a.count>=i)break;let d=this.buildNode(l,t,n,1,a,"descendant");d&&c.push(d)}return c}buildFocusedTree(e,t,n,i){let r=this.getMissionLineage(e),o=r.length>i.max?r.slice(r.length-i.max):r,a=null,c=null;for(let l=0;l<o.length&&!(i.count>=i.max);l++){let d=o[l],p=l===o.length-1,u=p?"focus":"ancestor",m=this.createMissionNode(d,u,p,p);i.count+=1,a?c&&c.children.push(m):a=m,c=m}return!a||!c?null:(this.attachChildren(c,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),c=n?a:a.filter(l=>l.status!=="completed");for(let l of c){if(o.count>=o.max)break;let d=this.buildNode(l,n,i,r+1,o,"descendant");d&&e.children.push(d)}}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){yd.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(`
661
+ `)}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 c of e.steps){let l=`S${e.id}_${c.id}`,d=c.status||"pending",p=this.getStatusIcon(d),u=this.getStatusClass(d),m=`${p} ${c.description}`;if(t.push(` ${l}["${this.escapeMermaid(m)}"]:::${u}`),t.push(` ${i} -.-> ${l}`),c.dependencies&&c.dependencies.length>0)for(let f of c.dependencies){let h=`S${e.id}_${f}`;t.push(` ${h} --> ${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 a_}from"clerc";q();import Pa from"fs";import La from"js-yaml";import tm from"path";var Na={ignore:[],include:[],maxDepth:10},nm=[{name:".liquid-shadow.yaml",parse:s=>La.load(s)??{}},{name:".liquid-shadow.yml",parse:s=>La.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 Ot(s){for(let{name:e,parse:t}of nm){let n=tm.join(s,e);if(Pa.existsSync(n))try{let i=Pa.readFileSync(n,"utf8"),r=t(i);return k.debug({repoPath:s,configFile:e},"Loaded repository configuration"),{...Na,...r}}catch(i){k.error({repoPath:s,file:e,err:i},"Failed to parse configuration file")}}return Na}function Ma(s,e){let n=Ot(s).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}Kt();import{readFileSync as cm}from"node:fs";var Hn={name:"@precisionutilityguild/liquid-shadow",version:"0.0.0",license:"UNLICENSED",description:"Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem"};function Oa(){let s=JSON.parse(cm(je("package.json"),"utf8"));return{name:typeof s.name=="string"&&s.name.trim().length>0?s.name:Hn.name,version:typeof s.version=="string"&&s.version.trim().length>0?s.version:Hn.version,license:typeof s.license=="string"&&s.license.trim().length>0?s.license:Hn.license,description:typeof s.description=="string"&&s.description.trim().length>0?s.description:Hn.description}}Ae();Ge();q();async function ne(s){k.debug("Performing graceful shutdown...");try{await qn()}catch(e){k.error({err:e},"Error shutting down worker pool")}try{s&&oi(s)}catch(e){k.error({err:e},"Error closing database")}k.debug("Shutdown complete")}import ls from"path";V();import jl from"fs";import $s from"path";import Mf from"fs";import $f from"os";import wo from"p-limit";import Wi from"path";var Si=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],fc=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/tsconfig*.json","**/jsconfig*.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],qe={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},ze={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},io={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},wi={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};Ae();V();import $m from"fs";import Dm from"path";import gc from"js-yaml";function hc(s){let e=Dm.basename(s),t=$m.readFileSync(s,"utf8"),n=[];if(e.endsWith(".prisma"))return{...jm(t,s),content:t};if(e.endsWith(".graphql")||e.endsWith(".gql"))return{...zm(t,s),content:t};let i="Configuration";return e==="lerna.json"?{...Um(t,s),content:t}:e==="turbo.json"?{...Bm(t,s),content:t}:e==="pnpm-workspace.yaml"?{...Gm(t,s),content:t}:(e.includes("Dockerfile")?(i="Infrastructure (Docker) ",Om(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(i="Infrastructure (YAML) ",Fm(t,n)):e.startsWith(".env")?(i="Configuration (Env) ",Wm(t,n)):e==="package.json"&&(i="Project Manifest",Hm(t,n)),{configs:n,classification:i,content:t})}function Om(s,e){let t=s.split(`
662
+ `);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 Fm(s,e){try{let t=gc.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 d="Env",p=/^[a-z0-9_-]+$/i.test(l),u=l.includes("://");o.toLowerCase().includes("service")&&(p||u)&&(d="Service"),o.toLowerCase().includes("image")&&(d="Image"),o.toLowerCase().includes("port")&&(d="Port"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&u&&(d="Service"),e.push({key:c,value:l.length>200?l.substring(0,197)+"...":l,kind:d})}}};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 Wm(s,e){let t=s.split(`
663
+ `);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 jm(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 zm(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 Hm(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 Um(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 Bm(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 Gm(s,e){let t=[],n="Monorepo (pnpm) ";try{let i=gc.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}}Ge();import{execFileSync as yc}from"child_process";import Ze from"fs";import Xt from"path";var bc=Ze.existsSync("/usr/bin/git")?"/usr/bin/git":"git";function ro(s,e){return yc(bc,e,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}function qm(s){let e=Xt.join(s,".git");if(!Ze.existsSync(e))return null;if(Ze.statSync(e).isDirectory())return e;try{let n=Ze.readFileSync(e,"utf8").match(/^gitdir:\s*(.+)\s*$/m);return n?.[1]?Xt.resolve(s,n[1].trim()):null}catch{return null}}function Jm(s,e){let t=Xt.join(s,"packed-refs");if(!Ze.existsSync(t))return null;try{for(let n of Ze.readFileSync(t,"utf8").split(`
664
+ `)){if(!n||n.startsWith("#")||n.startsWith("^"))continue;let[i,r]=n.trim().split(" ");if(r===e&&i)return i}}catch{return null}return null}function _c(s){try{let e=qm(s);if(!e)return{branch:null,commit:null};let t=Xt.join(e,"HEAD");if(!Ze.existsSync(t))return{branch:null,commit:null};let n=Ze.readFileSync(t,"utf8").trim();if(n.startsWith("ref: ")){let i=n.slice(5).trim(),r=Xt.join(e,i),o=Ze.existsSync(r)?Ze.readFileSync(r,"utf8").trim():Jm(e,i);return{branch:i.startsWith("refs/heads/")?i.slice(11):i,commit:o}}return{branch:null,commit:n||null}}catch{return{branch:null,commit:null}}}function ae(s){try{if(!Ze.existsSync(Xt.join(s,".git")))return null;let{branch:e,commit:t}=_c(s);return e?e.replace(/[/\\:*"<>|?]/g,"-"):t?t.slice(0,7):null}catch{return null}}function Ne(s){try{return Ze.existsSync(Xt.join(s,".git"))?_c(s).commit:null}catch{return null}}function Ei(s,e=50){try{let t=ro(s,["rev-list",`--max-count=${e}`,"HEAD"]);return t?t.split(`
665
+ `):[]}catch{return[]}}function Sc(s,e,t){try{return yc(bc,["merge-tree","--write-tree",e,t],{cwd:s,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}function Jn(s,e){try{if(!Ze.existsSync(Xt.join(s,".git")))return!0;let t=Ne(s);return t?!!(e&&e!==t):!0}catch{return!0}}function wc(s,e){let t=new Set;try{let n=ro(s,["diff","--name-only",e]);n&&n.split(`
666
+ `).filter(Boolean).forEach(r=>t.add(r));let i=ro(s,["status","--porcelain"]);i&&i.split(`
667
+ `).filter(Boolean).forEach(r=>{let o=r.trim().split(/\s+/);o.length>=2&&t.add(o[o.length-1])})}catch{}return t}q();import Oc from"fs";import Fc from"path";import*as oo from"@swc/core";function Ec(s){if(!s||typeof s!="object")return!1;let e=s;return typeof e.parse=="function"&&typeof e.parseSync=="function"}function Km(){if(Ec(oo))return oo;let s=oo;if(Ec(s.default))return s.default;throw new Error("SWC runtime unavailable: couldn't resolve parse/parseSync from @swc/core exports")}var xc=Km();function Ts(s,e,t){return xc.parse(s,e,t)}function xi(s,e,t){return xc.parseSync(s,e,t)}function vi(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 Kn(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 vc(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 ht(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 kc(s){if(!s)return"";let t=s.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
668
+ `)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function Rc(s){let e=s.split(`
669
+ `),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function ce(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 ki(s,e){return e.slice(0,s).toString("utf8").length}function Tc(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 Cc(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 et(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 Ac(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 Vm(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 Ic(s,e,t,n,i,r,o,a,c){let l=c??(p=>ki(p,t)),d=[];for(let p of s){if(p.type==="ExportDeclaration"){let u=p.declaration,m=u.type,f="";m==="VariableDeclaration"?f=u.declarations.map(A=>A.id.value).join("",""):f=u.id?.value||u.identifier?.value||"anonymous";let h=l(p.span.start-e),y=l(p.span.end-e),b=ht(h,r,n),g=a(p.span),w=[];if(p.type==="ExportDeclaration"&&(m==="ClassDeclaration"||m==="ClassExpression")){let A=u.body||[];for(let x of A)if(x.type==="ClassMethod"||x.type==="ClassProperty"){let E=x.key.value;if(!E)continue;let I=l(x.span.start-e),N=l(x.span.end-e),P=a(x.span),C=ht(I,r,n);w.push({name:E,kind:x.type,signature:et(P,x.type),line:ce(I,i),endLine:ce(N,i),doc:C,classification:x.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(m==="FunctionDeclaration"&&u.body?.type==="BlockStatement")w=ao(u.body.stmts,e,t,n,i,r,a,l);else if(m==="VariableDeclaration"){for(let A of u.declarations)if(A.init&&(A.init.type==="ArrowFunctionExpression"||A.init.type==="FunctionExpression")&&A.init.body?.type==="BlockStatement"){w=ao(A.init.body.stmts,e,t,n,i,r,a,l);break}}d.push({name:f,kind:m,signature:et(g,m),line:ce(h,i),endLine:ce(y,i),doc:b,classification:vi(o,f,m),capabilities:JSON.stringify(Kn(g)),members:w})}if(p.type==="ExportNamedDeclaration"){for(let u of p.specifiers)if(u.type==="ExportSpecifier"){let m=u.orig.value,f=u.exported?.value||m,y=Vm(s,m)||p.span,b=l(y.start-e),g=l(y.end-e),w=ht(b,r,n);d.push({name:f,kind:"ExportSpecifier",signature:`export { ${m} }`,line:ce(b,i),endLine:ce(g,i),doc:w,classification:"Export mapping",capabilities:"[]"})}}if(p.type==="ExportDefaultDeclaration"){let u=l(p.span.start-e),m=l(p.span.end-e),f=ht(u,r,n),h=a(p.span),y=[];if(p.decl.type==="ClassExpression"||p.decl.type==="ClassDeclaration"){let b=p.decl.body||[];for(let g of b)if(g.type==="ClassMethod"||g.type==="ClassProperty"){let w=g.key.value;if(!w)continue;let A=l(g.span.start-e),x=l(g.span.end-e),E=a(g.span),I=ht(A,r,n);y.push({name:w,kind:g.type,signature:et(E,g.type),line:ce(A,i),endLine:ce(x,i),doc:I,classification:g.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(p.decl.type==="FunctionExpression"||p.decl.type==="FunctionDeclaration"||p.decl.type==="ArrowFunctionExpression")&&p.decl.body?.type==="BlockStatement"&&(y=ao(p.decl.body.stmts,e,t,n,i,r,a,l));d.push({name:"default",kind:"DefaultExport",signature:et(h,"DefaultExport"),line:ce(u,i),endLine:ce(m,i),doc:f,classification:"Default Export",capabilities:JSON.stringify(Kn(h)),members:y})}if(p.type==="ExportDefaultExpression"){let u=l(p.span.start-e),m=l(p.span.end-e),f=ht(u,r,n),h=a(p.span),y=p.expression,b=y?.type==="Identifier"?y.value:y?.identifier?.value||y?.id?.value||void 0;d.push({name:"default",kind:"DefaultExport",signature:et(h,"DefaultExport"),line:ce(u,i),endLine:ce(m,i),doc:f,classification:"Default Export",capabilities:JSON.stringify(Kn(h)),members:[],defaultTarget:b})}if(p.type==="ExportAllDeclaration"){let u=l(p.span.start-e),m=l(p.span.end-e),f=p.source.value,h=ht(u,r,n);d.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${f}"`,line:ce(u,i),endLine:ce(m,i),doc:h,classification:"Re-export",capabilities:"[]"})}}return d}function ao(s,e,t,n,i,r,o,a){let c=[];for(let l of s){if(l.type==="VariableDeclaration")for(let d of l.declarations){let p=[],u=f=>{if(f.type==="Identifier")p.push({name:f.value,span:f.span});else if(f.type==="ArrayPattern")for(let h of f.elements)h&&u(h);else if(f.type==="ObjectPattern")for(let h of f.properties)h.type==="AssignmentPatternProperty"?p.push({name:h.key.value,span:h.span}):h.type==="KeyValuePatternProperty"&&u(h.value)};u(d.id);let m=d.init&&(d.init.type==="ArrowFunctionExpression"||d.init.type==="FunctionExpression");for(let f of p){let h=m?d.init.span||d.span||f.span:d.span||f.span,y=m?d.init.type:"VariableDeclaration",b=m?"Internal Function":"Internal Variable",g=a(h.start-e),w=a(h.end-e),A=o(h),x=ht(g,r,n);c.push({name:f.name,kind:y,signature:et(A,y),line:ce(g,i),endLine:ce(w,i),doc:x,classification:b,capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let d=l.identifier?.value||l.ident?.value||"anonymous",p=a(l.span.start-e),u=a(l.span.end-e),m=o(l.span),f=ht(p,r,n);c.push({name:d,kind:"FunctionDeclaration",signature:et(m,"FunctionDeclaration"),line:ce(p,i),endLine:ce(u,i),doc:f,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let d of l.argument.properties){let p="",u=d.span||d.key?.span||d.ident?.span;if(d.type==="KeyValueProperty"){let m=d.key;p=m?.value||m?.raw||(m?.type==="Identifier"?m.value:"")}else d.type==="MethodProperty"?p=d.key?.value||d.key?.raw||"":d.type==="ShorthandProperty"?p=d.ident?.value||"":d.type==="Identifier"&&(p=d.value||"");if(p&&u){let m=a(u.start-e),f=a(u.end-e),h=o(u),y=ht(m,r,n);c.push({name:p,kind:"ReturnProperty",signature:et(h,"ReturnProperty"),line:ce(m,i),endLine:ce(f,i),doc:y,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let d=l.expression;if(d.callee.type==="MemberExpression"&&(d.callee.property?.value==="on"||d.callee.property?.value==="once")){let p=d.arguments[0]?.expression?.value,u=d.arguments[1]?.expression;if(p&&u&&(u.type==="ArrowFunctionExpression"||u.type==="FunctionExpression")){let m=a(u.span.start-e),f=a(u.span.end-e),h=o(u.span);c.push({name:`on:${p}`,kind:u.type,signature:et(h,u.type),line:ce(m,i),endLine:ce(f,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(d.callee.type==="Identifier"&&d.callee.value==="addRoute"&&d.arguments.length>=3){let p=d.arguments[2].expression;if(p.type==="StringLiteral"){let u=p.value,m=a(d.span.start-e),f=a(d.span.end-e),h=o(d.span);c.push({name:u,kind:"HTTP Route",signature:et(h,"HTTP Route"),line:ce(m,i),endLine:ce(f,i),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:u})})}}}}return c}function Pc(s,e,t,n,i,r){let o=r??(l=>ki(l,t)),a=[];function c(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let d=Ym(l);if(d){let p=o(l.span.start-e);a.push({...d,line:ce(p,n),snippet:i(l.span)})}}for(let d of Object.keys(l)){if(d==="span")continue;let p=l[d];Array.isArray(p)?p.forEach(c):typeof p=="object"&&c(p)}}}return s.forEach(c),a}function Ym(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}import co from"path";Kt();q();import Qm from"fs";import Nc from"path";import{fileURLToPath as Xm}from"url";import*as xn from"web-tree-sitter";var cw=Nc.dirname(Xm(import.meta.url)),Lc=k.child({module:"parser:tree-sitter"}),Ri=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=xn.Parser||xn;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=je("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!Qm.existsSync(t))return Lc.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await xn.Language.load(t);return this.languages.set(e,n),n}catch(n){return Lc.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`
670
+ (function_definition name: (name) @name) @func
671
+ (class_declaration name: (name) @name) @class
672
+ (interface_declaration name: (name) @name) @interface
673
+ (trait_declaration name: (name) @name) @trait
674
+ (method_declaration name: (name) @name) @method
675
+ (namespace_use_declaration (namespace_use_clause (qualified_name) @name)) @import
676
+ `;case".py":return`
677
+ (function_definition name: (identifier) @name) @func
678
+ (class_definition name: (identifier) @name) @class
679
+ (import_statement name: (dotted_name) @name) @import
680
+ (import_from_statement module_name: (dotted_name) @name) @import
681
+ `;case".go":return`
682
+ (function_declaration name: (identifier) @name) @func
683
+ (method_declaration name: (identifier) @name) @func
684
+ (type_declaration (type_spec name: (identifier) @name)) @type
685
+ (import_spec path: (interpreted_string_literal) @name) @import
686
+ `;case".rs":return`
687
+ (function_item name: (identifier) @name) @func
688
+ (struct_item name: (_type_identifier) @name) @struct
689
+ (enum_item name: (_type_identifier) @name) @enum
690
+ (trait_item name: (_type_identifier) @name) @trait
691
+ (type_item name: (_type_identifier) @name) @type
692
+ (use_declaration argument: (_) @name) @import
693
+ `;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=Nc.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(`
694
+ `),a=this.getQueries(n);if(!a)return[];let l=new xn.Query(i,a).matches(r.rootNode),d=[];for(let p of l){let u=p.captures.find(h=>h.name==="name")?.node,m=p.captures[0].node,f=p.captures[0].name;if(u){let h=m.startPosition.row+1,y=m.endPosition.row+1,b=o[m.startPosition.row].trim();d.push({name:u.text,kind:this.mapKind(f,n),classification:this.mapClassification(f),signature:b,line:h,endLine:y,doc:"",capabilities:"{}"})}}return d}};function Cs(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(f=>r[f]).filter(Boolean).join(" and "),c={Component:(f,h)=>{let y=h.find(g=>g.kind==="FunctionDeclaration"||g.kind==="ClassDeclaration")?.name,b=y?`React component: ${y}`:"React UI component";return f?`${b} with ${f}`:b},Hook:(f,h)=>{let y=h.find(g=>g.name.startsWith("use"))?.name,b=y?`Custom React hook: ${y}`:"Custom React hook";return f?`${b} for ${f}`:b},Service:(f,h)=>{let b=`Service layer: ${h[0]?.name||"Service"}`;return f?`${b} handling ${f}`:b},Repository:(f,h)=>`Data repository: ${h[0]?.name||"Repository"} for ${f||"data access"}`,"Type Definition":(f,h)=>`Type definitions: ${h.slice(0,3).map(b=>b.name).join("")}${h.length>3?"...":""}`,Model:(f,h)=>`Data model: ${h[0]?.name||"Model"}`,"HTTP Route":(f,h)=>{let y=h.filter(b=>b.classification==="Service Boundary");return y.length>0?`API endpoints: ${y.slice(0,3).map(b=>b.name).join("")}`:"API route handler"},"Micro IR (PHP)":(f,h)=>{let y=h.some(g=>g.classification==="Service Boundary"),b=h.find(g=>g.kind==="ClassDeclaration")?.name;return y?"PHP controller with API routes":b?`PHP class: ${b}`:"PHP module"},"Micro IR (Python)":(f,h)=>{let y=h.some(g=>g.classification==="Service Boundary"),b=h.find(g=>g.kind==="ClassDeclaration")?.name;return y?"Python API handler with routes":b?`Python class: ${b}`:"Python module"},"Micro IR (Go/TS) ":(f,h)=>{let y=h.some(g=>g.kind==="TypeDeclaration"),b=h.filter(g=>g.kind==="FunctionDeclaration");return y&&b.length>0?`Go package: types and ${b.length} function(s)`:y?"Go package: type definitions":b.length>0?`Go package: ${b[0].name} and ${b.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(f,h)=>{let y=h.find(w=>w.kind==="TraitDeclaration")?.name,b=h.find(w=>w.kind==="StructDeclaration")?.name,g=h.filter(w=>w.kind==="FunctionDeclaration");return y?f.includes("Rust trait")?`Rust module: trait ${y}`:`Rust module: ${y}`:b?`Rust module: struct ${b}`:g.length>0?`Rust module: ${g.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(f=>f.kind==="FunctionDeclaration"),d=n.filter(f=>f.kind==="ClassDeclaration"),p=n.filter(f=>f.kind==="TsInterfaceDeclaration"||f.kind==="TsTypeAliasDeclaration"),u=[];if(d.length>0&&u.push(`Class: ${d[0].name}`),l.length>0){let f=l.slice(0,2).map(h=>h.name).join("");u.push(`Functions: ${f}`)}p.length>0&&u.push(`Types: ${p.length}`);let m=u.length>0?u.join(" | "):`Module with ${n.length} export(s)`;return o?`${m} \u2014 ${o}`:m}var Ti=class{parse(e,t=!1){let n=[],i=[],r=e.split(`
695
+ `),o="",a="",c=0,l=0,d=-1,p=-1,u=[],m=[],f=!1,h=t?"api":"",y="",b=/^namespace\s+([a-zA-Z0-9_\\]+);/,g=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,w=/^interface\s+([a-zA-Z0-9_]+)/,A=/^trait\s+([a-zA-Z0-9_]+)/,x=/^enum\s+([a-zA-Z0-9_]+)(?:\s*:\s*(string|int))?\s*/,E=/^((?:(?:public|protected|private|static)\s+)*)function\s+([a-zA-Z0-9_]+)\s*\(/,I=/^(public|protected|private)\s+(static\s+)?(readonly\s+)?(?:(\?\s*)?([a-zA-Z0-9_\\|]+)\s+)?\$([a-zA-Z0-9_]+)/,N=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,P=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,C=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,W=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/,j=/\$this->(hasMany|hasOne|belongsTo|belongsToMany|morphTo|morphMany|morphOne|morphToMany|morphedByMany)\s*\(\s*([a-zA-Z0-9_\\]+)(?:::class)?/,K=/^->(hasMany|hasOne|belongsTo|belongsToMany|morphTo|morphMany|morphOne|morphToMany|morphedByMany)\s*\(\s*([a-zA-Z0-9_\\]+)(?:::class)?/,U=/(public|protected|private)\s+(readonly\s+)?(?:(\?\s*)?([a-zA-Z0-9_\\|]+)\s+)?\$([a-zA-Z0-9_]+)/g,H=/(?:protected|public)\s+\$(fillable|casts|guarded|hidden|appends|with)\s*=/;function M(v){try{let _=JSON.parse(v||"{}");if(_&&typeof _=="object"&&!Array.isArray(_))return _}catch{}return{}}function D(v,_){let R=[],T=v,$=0,F=0;for(;T<r.length;){let B=r[T].trim();R.push(B),$+=(B.match(/\[/g)||[]).length-(B.match(/]/g)||[]).length,F+=(B.match(/\(/g)||[]).length-(B.match(/\)/g)||[]).length;let X=B.includes(_),he=$<=0&&F<=0;if(X&&he)break;T+=1}return{text:R.join(" "),endIndex:T}}function O(v,_){let R=_.replace(/^[^=]+=\s*/,"").replace(/;$/,"").trim();if(v==="casts"){let B={},X=/['"]([^'"]+)['"]\s*=>\s*['"]([^'"]+)['"]/g,he=null;for(;he=X.exec(R);)B[he[1]]=he[2];return B}let T=[],$=/['"]([^'"]+)['"]/g,F=null;for(;F=$.exec(R);)T.push(F[1]);return T}function Y(v,_){for(let R=_;R>=0;R-=1){let T=v[R]?.trim()||"";if(T)return T}return""}function z(v,_,R,T){if(!o)return;let $=_.split("\\").pop()||_;i.push({type:"eloquent_relation",name:$,direction:"produce",line:R,snippet:T,method:v,url:`${o}->${$}`})}for(let v=0;v<r.length;v++){let _=r[v].trim();if(!_)continue;let R=(_.match(/{/g)||[]).length,T=(_.match(/}/g)||[]).length,$=l;if(l+=R-T,a&&l<=p){let Z=n.find(J=>J.name===a&&J.line===c);Z&&(Z.endLine=v+1),a="",p=-1}if(o&&l<=d){let Z=n.find(J=>J.name===o&&(J.kind==="ClassDeclaration"||J.kind==="TraitDeclaration"||J.kind==="InterfaceDeclaration"||J.kind==="EnumDeclaration"));Z&&(Z.endLine=v+1),o="",d=-1}let F=_.match(W);if(F&&(h=F[1]),_.includes("});")&&(h=""),_.startsWith("/**")){f=!0,m=[];continue}if(f){_.endsWith("*/")?f=!1:m.push(_.replace(/^\*\s?/,""));continue}let B=_.match(P);if(B){u.push(B[1]);continue}let X=_.match(b);if(X){y=X[1]||"",u=[],m=[];continue}let he=_.match(g);if(he){o=he[1],d=l-R;let Z={attributes:u};y&&(Z.namespace=y),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:v+1,endLine:v+1,doc:m.join(`
696
+ `).trim(),capabilities:JSON.stringify(Z),members:[]}),u=[],m=[];continue}let Ce=_.match(w);if(Ce){let Z=Ce[1];o=Z,d=l-R,n.push({name:Z,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${Z}`,line:v+1,endLine:v+1,doc:m.join(`
697
+ `).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let it=_.match(A);if(it){let Z=it[1];o=Z,d=l-R,n.push({name:Z,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${Z}`,line:v+1,endLine:v+1,doc:m.join(`
698
+ `).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let _e=_.match(x);if(_e){let Z=_e[1],J=_e[2]||null;o=Z,d=l-R;let xe={attributes:u,backedType:J};y&&(xe.namespace=y),n.push({name:Z,kind:"EnumDeclaration",classification:"Enum",signature:J?`enum ${Z}: ${J}`:`enum ${Z}`,line:v+1,endLine:v+1,doc:m.join(`
699
+ `).trim(),capabilities:JSON.stringify(xe),members:[]}),u=[],m=[];continue}let rt=_.match(E);if(rt){let Z=(rt[1]||"").trim(),J=rt[2],xe=!!o,Fe=/\bprivate\b/.test(Z)?"private":/\bprotected\b/.test(Z)?"protected":"public",ie=/\bstatic\b/.test(Z),at=D(v,")"),We=at.text.match(/\)\s*:\s*([?a-zA-Z0-9_\\|]+)/),xs=We?We[1]:null,Ur=R>0&&T>=R;a=J,c=v+1,p=l-R;let ka=!1,Br={};for(let ct of u)ct.toLowerCase().includes("route")&&(ka=!0,Br={type:"route",method:"GET",path:"/"});let Ra=m.join(`
700
+ `).trim();if(ka){let ct=Br.path||"/";n.push({name:ct,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${J}`,line:v+1,endLine:v+1,doc:Ra,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${J}`:J,...Br})}),i.push({type:"api_route",name:ct,direction:"consume",line:v+1,snippet:_})}let Ta={name:J,kind:xe?"MethodDeclaration":"FunctionDeclaration",classification:xe?"Method":"Function",signature:`${xe?o+":: ":""}${J}`,line:v+1,endLine:v+1,doc:Ra,capabilities:JSON.stringify(xe?{attributes:u,visibility:Fe,static:ie,returnType:xs}:{attributes:u,returnType:xs})};n.push(Ta);let Gr=xe?_.match(j):null;if(Gr&&z(Gr[1],Gr[2],v+1,_),xe&&J==="__construct"){let ct=null;for(;ct=U.exec(at.text);){let Ca=ct[1],Aa=!!ct[2],qr=ct[4]?`${ct[3]?"?":""}${ct[4]}`:null,Ia=ct[5],Uu=`${Ca} ${Aa?"readonly ":""}${qr?`${qr} `:""}$${Ia}`.trim();n.push({name:Ia,kind:"PropertyDeclaration",classification:"Property",signature:Uu,line:v+1,endLine:v+1,doc:"",capabilities:JSON.stringify({visibility:Ca,static:!1,readonly:Aa,type:qr}),members:[]})}U.lastIndex=0}Ur&&(Ta.endLine=v+1,a="",p=-1),u=[],m=[];continue}let ot=!1,Me=!1,te=v,pe=o&&!a?_.match(I):null;if(pe){ot=!0;let Z=pe[1],J=!!pe[2],xe=!!pe[3],Fe=pe[5]?`${pe[4]?"?":""}${pe[5]}`:null,ie=pe[6],at=`${Z} ${J?"static ":""}${xe?"readonly ":""}${Fe?`${Fe} `:""}$${ie}`.trim();n.push({name:ie,kind:"PropertyDeclaration",classification:"Property",signature:at,line:v+1,endLine:v+1,doc:m.join(`
701
+ `).trim(),capabilities:JSON.stringify({visibility:Z,static:J,readonly:xe,type:Fe}),members:[]})}let Et=o&&!a?_.match(H):null;if(Et){Me=!0;let Z=Et[1],J=D(v,";");te=J.endIndex;let xe=O(Z,J.text),Fe=[...n].reverse().find(ie=>ie.name===o&&ie.kind==="ClassDeclaration");if(Fe){let ie=M(Fe.capabilities);(!ie.modelConfig||typeof ie.modelConfig!="object"||Array.isArray(ie.modelConfig))&&(ie.modelConfig={}),ie.modelConfig[Z]=xe,Fe.capabilities=JSON.stringify(ie)}}if(ot||Me){Me&&te>v&&(v=te),u=[],m=[];continue}let ut=_.match(N);if(ut){let Z=ut[1]||"",J=ut[2]||Z.split("\\").pop()||"";n.push({name:J,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${Z}`,line:v+1,endLine:v+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:Z})}),u=[],m=[];continue}let mt=_.match(C);if(mt){let Z=mt[1].toUpperCase(),J=mt[2];if(_.includes("Route::")||_.includes("router->")||_.includes("action")||_.includes(",")&&!_.includes("view(")){if(h){let We=h.startsWith("/")?h:`/${h}`,xs=J.startsWith("/")?J:`/${J}`;J=(We+xs).replace(/\/+/g,"/")}let Fe=null,ie=_.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(ie)Fe=`${ie[1]}@${ie[2]}`;else if(_.includes("::class")){let We=_.match(/([a-zA-Z0-9_]+)::class/);We&&(Fe=We[1])}let at=_;!_.endsWith(");")&&v+1<r.length&&(at+=" "+r[v+1].trim(),!at.endsWith(");")&&v+2<r.length&&(at+=" "+r[v+2].trim())),n.push({name:J,kind:"HTTP Route",classification:"Service Boundary",signature:at,line:v+1,endLine:v+1,doc:"",capabilities:JSON.stringify({type:"route",method:Z,path:J,handler:Fe})}),i.push({type:"api_route",name:J,direction:"consume",line:v+1,snippet:at,method:Z,url:J}),m=[];continue}}let Dt=o&&a?_.match(j):null,_n=o&&a?_.match(K):null;if(Dt)z(Dt[1],Dt[2],v+1,_);else if(_n){let Z=Y(r,v-1);/\$this\b/.test(Z)&&z(_n[1],_n[2],v+1,_)}let Es=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,Sn=_.match(Es);if(Sn){let Z=(Sn[1]||Sn[3]).toUpperCase(),J=(Sn[2]||Sn[4]).trim();(J.startsWith("'")&&J.endsWith("'")||J.startsWith('"')&&J.endsWith('"'))&&(J=J.substring(1,J.length-1)),i.push({type:"api_route",name:J,direction:"produce",line:v+1,snippet:_,method:Z,url:J})}!_.startsWith("#[")&&!_.startsWith("//")&&!_.startsWith("*")&&!f&&(u=[],m=[])}return{nodes:n,events:i}}};var Ci=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],i=e.split(`
702
+ `),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_.]+))/,d=/^@(.*)/;function p(w){return w.trim().split(/[.(]/)[0]?.trim()||w}function u(w){let A=w.decorators.map(E=>p(E.raw)),x={decorators:w.decorators,decoratorNames:A};return w.async===!0&&(x.async=!0),w.accessor&&(x.accessor=w.accessor),w.contextmanager===!0&&(x.contextmanager=!0),JSON.stringify(x)}function m(w,A){return(w.match(new RegExp(`\\${A}`,"g"))||[]).length}function f(w){let A=[],x=w,E=0,I=0,N=0,P=!1;do{let C=i[x].trim();if(A.push(C),E+=m(C,"(")-m(C,")"),I+=m(C,"[")-m(C,"]"),N+=m(C,"{")-m(C,"}"),P=C.endsWith("\\"),x+1>=i.length||E<=0&&I<=0&&N<=0&&!P)break;x+=1}while(!0);return{text:A.join(" "),endIndex:x}}let h=!1,y="",b=[],g=[];for(let w=0;w<i.length;w++){let A=i[w],x=A.trim();if(!x||x.startsWith("#"))continue;let E=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,I=x.match(E);if(I&&(this.currentRoutePrefix=I[2]),h){if(x.endsWith(y)||x.includes(y)){h=!1;let T=x.replace(y,"").trim();T&&b.push(T);let $=r[r.length-1];$.node&&($.node.doc=b.join(`
703
+ `).trim()),b=[]}else b.push(x);continue}let N=A.search(/\S/),P=A.trim(),C=P.match(/^(['"]{3})/);if(C){let T=C[1],$=r[r.length-1];if($.node&&!$.node.doc){if(P.substring(3).includes(T)){let F=P.replace(new RegExp(T,"g"),"").trim();$.node.doc=F}else{h=!0,y=T;let F=P.substring(3).trim();F&&b.push(F)}continue}}for(;r.length>1&&r[r.length-1].indent>=N;)r.pop();let W=r[r.length-1],j=W.type==="root"&&N===0;if(j&&/^__all__\s*=/.test(P)){let T=f(w),$=[],F=/['"]([^'"]+)['"]/g,B=null;for(;B=F.exec(T.text);)$.push(B[1]);let X={name:"__all__",kind:"ModuleExports",classification:"ExportList",signature:"__all__ = [...]",line:w+1,endLine:T.endIndex+1,doc:"",capabilities:JSON.stringify({exports:$}),members:[]};g.push(X),t.push(X),w=T.endIndex,o=[];continue}let U=/^([A-Z][A-Z0-9_]*)(?:\s*:\s*[^=]+)?\s*=/,H=j?P.match(U):null;if(H){let T=f(w),$=T.text.length>120?`${T.text.slice(0,117)}...`:T.text,F={name:H[1],kind:"VariableDeclaration",classification:"Constant",signature:$,line:w+1,endLine:T.endIndex+1,doc:"",capabilities:"{}",members:[]};g.push(F),t.push(F),w=T.endIndex,o=[];continue}let M=P.match(d);if(M){o.push({raw:M[1].trim(),line:w+1});continue}let D=P.match(a);if(D){let T=D[1],$={name:T,kind:"ClassDeclaration",classification:"Class",signature:`class ${T}`,line:w+1,endLine:w+1,doc:"",capabilities:u({decorators:o}),members:[]};g.push($),W.node?(W.node.members||(W.node.members=[]),W.node.members.push($)):t.push($),r.push({indent:N,name:T,type:"class",node:$}),o=[];continue}let O=P.match(c);if(O){let T=!!O[1],$=O[1]||O[2],F=W.type==="class",B=o.some(te=>/(?:^|\.)contextmanager$/.test(te.raw.trim())),X;o.some(te=>te.raw.trim()==="property")&&(X="getter");for(let te of o){let pe=te.raw.trim().match(/^[a-zA-Z_][a-zA-Z0-9_]*\.(setter|deleter)$/);if(pe){X=pe[1];break}}let he=!1,Ce={};for(let te of o)if(te.raw.match(/(?:app|router)\.(get|post|put|delete|patch|websocket)/)){he=!0;let Et=["get","post","put","delete","patch","websocket"].find(Dt=>te.raw.toLowerCase().includes(`.${Dt}`))?.toUpperCase()||"GET",ut=te.raw.match(/['"]([^'"]+)['"]/),mt=ut?ut[1]:"/";if(this.currentRoutePrefix){let Dt=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,_n=mt.startsWith("/")?mt:`/${mt}`;mt=Dt+_n}Ce={type:"route",method:Et,path:mt}}if(he){let te=Ce.path||"",pe=Ce.method==="WEBSOCKET",Et={name:te||$,kind:pe?"WebSocket Route":"HTTP Route",classification:"Service Boundary",signature:`Function: ${$}`,line:w+1,endLine:w+1,doc:"",capabilities:JSON.stringify({handler:F?`${W.name}.${$}`:$,async:T,...Ce})};g.push(Et),t.push(Et),n.push({type:pe?"websocket_route":"api_route",name:te,direction:"consume",line:w+1,snippet:P})}for(let te of o){let pe=te.raw.match(/(?:^|\.)receiver\s*\(\s*([a-zA-Z0-9_.]+)/);pe&&n.push({type:"signal",name:pe[1].split(".").pop()||pe[1],direction:"consume",line:te.line,snippet:`@${te.raw}`})}let it=o.some(te=>te.raw==="staticmethod"),_e=o.some(te=>te.raw==="classmethod"),rt=`${T?"async ":""}${F?(it?"@staticmethod ":_e?"@classmethod ":"")+W.name+".":""}${$}`,ot=!!X,Me={name:$,kind:ot?"PropertyDeclaration":T&&F?"AsyncMethodDeclaration":T?"AsyncFunctionDeclaration":F?"MethodDeclaration":"FunctionDeclaration",classification:ot?"Property":F?it||_e?"Static Method":"Method":"Function",signature:rt,line:w+1,endLine:w+1,doc:"",capabilities:u({decorators:o,async:T,accessor:X,contextmanager:B}),members:[]};g.push(Me),W.node?(W.node.members||(W.node.members=[]),W.node.members.push(Me)):t.push(Me),r.push({indent:N,name:$,type:"function",node:Me}),o=[];continue}let Y=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,z=P.match(Y);if(z){let T=z[1].replace(/^\^/,""),$={name:T,kind:"HTTP Route",classification:"Service Boundary",signature:P.trim(),line:w+1,endLine:w+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:T})};g.push($),t.push($),n.push({type:"api_route",name:T,direction:"consume",line:w+1,snippet:P});continue}let v=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,_=P.match(v);if(_){let T=_[1].toUpperCase(),$=_[2].trim();($.startsWith("'")&&$.endsWith("'")||$.startsWith('"')&&$.endsWith('"'))&&($=$.substring(1,$.length-1)),n.push({type:"api_route",name:$,direction:"produce",line:w+1,snippet:P,method:T,url:$})}let R=P.match(l);if(R){let T=R[1]||R[2],$={name:T,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${T}`,line:w+1,endLine:w+1,doc:"",capabilities:JSON.stringify({type:"import",module:T})};g.push($),t.push($),o=[];continue}o=[],W.node&&(W.node.endLine=w+1)}return{nodes:g,events:n}}};function Zm(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 Mc=[{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 ef(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 Ai=class{phpParser=new Ti;pythonParser=new Ci;treeSitterParser=new Ri;supports(e){return Mc.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=co.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"),d=this.phpParser.parse(t,l);i=d.nodes,r=d.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) ",d=i.filter(f=>f.classification!=="Dependency"),p=i.filter(f=>f.classification==="Dependency"),u=ef(n,i),m=Cs({classification:l,capabilities:u,exports:d.map(f=>({name:f.name,kind:f.kind,classification:f.classification})),fileName:co.basename(e)});return{exports:d,imports:p.map(f=>({module:f.name,name:f.name,kind:f.kind,classification:f.classification})),events:r,classification:l,summary:m||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Mc.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(`
704
+ `);for(let l of o.rules){l.regex.lastIndex=0;let d;for(;(d=l.regex.exec(t))!==null;){let p=l.onMatch(d),u=t.substring(0,d.index).split(`
705
+ `).length,m=Zm(a,u-1);i.push({name:p.name||"anonymous",kind:p.kind||"Unknown",classification:p.classification||"Other",signature:p.signature||d[0],line:u,endLine:m,doc:"",capabilities:JSON.stringify(p.meta||{})})}}let c=Cs({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:i.map(l=>({name:l.name,kind:l.kind,classification:l.classification})),fileName:co.basename(e)});return{exports:i,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:c||"Module",parseStatus:i.length>0?"success":"partial"}}};function $c(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&Ee(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&Ee(n,e);for(let 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 Ee(s,e){if(s){if(s.type==="TsTypeAnnotation"){Ee(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&Dc(s.typeName,e),s.typeParams&&Ee(s.typeParams,e)),s.type==="TsArrayType"&&Ee(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>Ee(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>Ee(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>Ee(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>Ee(t.typeAnnotation,e)),s.typeAnnotation&&Ee(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&Ee(t.constraint,e),t.default&&Ee(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>Ee(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&Ee(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(Ee(s.objectType,e),Ee(s.indexType,e)),s.type==="TsConditionalType"&&(Ee(s.checkType,e),Ee(s.extendsType,e),Ee(s.trueType,e),Ee(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&Ee(t.typeAnnotation,e)})}}function Dc(s,e){s.type==="TsQualifiedName"?(s.left&&Dc(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}var lo=new Ai;async function As(s){let e=Fc.extname(s);if(lo.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=await Oc.promises.readFile(s,"utf-8");return{...await lo.parse(s,r),content:r}}catch(r){return k.error({filePath:s,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:r.message}}let t;try{t=await Oc.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=Rc(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=xi(n,c)}catch{a=xi(n,{...c,isModule:!1})}else a=xi(n,c);let l=a.span.start,d=Tc(t),p=vc(n),u=x=>Cc(x,l,t),m=Ac(a.body),f=$c(a.body);f.length>0&&k.debug({filePath:s,count:f.length},"Extracted type references"),f.forEach(x=>{m.push({module:"__type_reference__",name:x})});let h=Ic(a.body,l,t,n,i,p,s,u,d),y=Pc(a.body,l,t,i,u,d),b=vi(s,"","Module"),w=p.length>0&&n.slice(0,p[0].start).trim().length===0?p[0].text:h.find(x=>x.doc)?.doc||"",A=kc(w);if(!A&&h.length>0){let x=Kn(n);A=Cs({classification:b,capabilities:x,exports:h.map(E=>({name:E.name,kind:E.kind,classification:E.classification})),fileName:Fc.basename(s)})}return{exports:h,imports:m,events:y,classification:b,summary:A,content:n,parseStatus:"success"}}catch(r){k.warn({filePath:s,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=await lo.parse(s,n);return{...o,content:n,classification:o.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return k.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}`}}}}Kt();q();import{existsSync as tf}from"node:fs";import{cpus as nf}from"node:os";import{dirname as sf,join as rf}from"node:path";import{fileURLToPath as of}from"node:url";import{Worker as af}from"node:worker_threads";var Wc=of(import.meta.url),cf=sf(Wc),lf=Wc.endsWith(".ts");function pf(){if(lf)return null;let s=rf(cf,"worker.js");return tf(s)?s:je("dist/logic/parser/worker.js")}var po=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,nf().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{k.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,k.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=pf();if(!e)throw new Error("Parser worker pool not available in development mode (tsx). Use main-thread fallback.");k.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 af(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),k.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),k.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(d=>{k.error({err:d},"Failed to replace crashed parser worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&k.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}k.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,k.info("Parser worker pool shutdown complete")}},Vn=null;function jc(s){return Vn||(Vn=new po(s)),Vn}async function zc(){Vn&&(await Vn.shutdown(),Vn=null)}Ae();Kt();import{spawn as df}from"node:child_process";import{existsSync as Hc}from"node:fs";import uo from"node:os";import{dirname as uf,resolve as mf}from"node:path";import{fileURLToPath as ff}from"node:url";var Uc=ff(import.meta.url),hf=uf(Uc),gf=uo.constants.priority.PRIORITY_LOWEST??uo.constants.priority.PRIORITY_LOW;function yf(){if(Uc.endsWith(".ts"))return null;let s=mf(hf,"../../entry/ember/index.js");if(Hc(s))return s;let e=je("dist/entry/ember/index.js");return Hc(e)?e:null}function Bc(s){try{let t=ye(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 bf(s,e){let t=ye(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 Gc(s){let{pid:e}=Bc(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 qc(s){let e=yf();if(!e)return;let t=df(process.execPath,[e,s],{detached:!0,stdio:"ignore",env:{...process.env,EMBER_MODE:"1"}});if(t.pid!=null){try{uo.setPriority(t.pid,gf)}catch{}t.unref(),bf(s,t.pid)}}function Yn(s){let{status:e,progress:t}=Bc(s);return{status:e,progress:t}}V();en();q();mo();fo();ho();import{execSync as fl}from"child_process";var Fi=k.child({module:"heritage-analyzer"}),Qn=class{repos;repoPath;constructor(e){this.repos=L.getInstance(e),this.repoPath=e}analyzeHeritage(e=20){try{Fi.info({limit:e},"Analyzing repository heritage...");let t=fl(`git log -n ${e} --pretty=format:"%H|%at|%an|%s"`,{cwd:this.repoPath,encoding:"utf-8"});if(!t)return;let n=t.split(`
706
+ `).filter(Boolean);for(let i of n){let[r,o,a,c]=i.split("|"),l=this.analyzeCommitImpact(r);if(l.significant){let d=Array.from(l.layers).join(", "),p=`Heritage: ${c} (by ${a}). Touched ${l.fileCount} files across [${d}].`;this.repos.intentLogs.importHeritage(p,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=fl(`git diff-tree --no-commit-id --name-only -r ${e}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
707
+ `).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 go.some(n=>n.test(t))?"Test":Pi.some(n=>n.test(t))||Ii.some(n=>n.test(t))?"Entry":Is.some(n=>n.test(t))?"Data":Ni.some(n=>n.test(t))?"Utility":Di.some(n=>n.test(t))?"Entry":Oi.some(n=>n.test(t))?"Data":Mi.some(n=>n.test(t))?"Entry":$i.some(n=>n.test(t))?"Data":yo.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"}};var bo=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastToolName=null;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];lastOutputTokens=null;totalOutputTokens=0;lastEstimatedCostUsd=null;totalEstimatedCostUsd=0;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 t=>{this.queryCount+=1;let n=performance.now()-e;if(this.lastQueryLatencyMs=n,this.lastToolName=t?.toolName??this.lastToolName,this.recentLatencies.push(n),this.recentLatencies.length>100){let i=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-i+n}else this.recentLatencySumMs+=n,this.recentLatencyCount=this.recentLatencies.length;typeof t?.outputTokens=="number"&&(this.lastOutputTokens=t.outputTokens,this.totalOutputTokens+=t.outputTokens),typeof t?.estimatedCostUsd=="number"&&(this.lastEstimatedCostUsd=t.estimatedCostUsd,this.totalEstimatedCostUsd=Number((this.totalEstimatedCostUsd+t.estimatedCostUsd).toFixed(6)))}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((i,r)=>i+r,0)/e:null,n=this.queryCount>0?this.totalOutputTokens/this.queryCount:null;return{index:{runs:this.indexRuns,cacheHits:this.indexCacheHits,lastDurationMs:this.lastIndexDurationMs,lastCompletedAt:this.lastIndexCompletedAt,lastRunPhases:[...this.lastRunPhases]},query:{count:this.queryCount,lastToolName:this.lastToolName,lastLatencyMs:this.lastQueryLatencyMs,recentLatencySumMs:this.recentLatencySumMs,recentLatencyCount:e,avgLatencyMs:t,lastOutputTokens:this.lastOutputTokens,avgOutputTokens:n,totalOutputTokens:this.totalOutputTokens,lastEstimatedCostUsd:this.lastEstimatedCostUsd,totalEstimatedCostUsd:this.totalEstimatedCostUsd,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.lastToolName=null,this.lastQueryLatencyMs=null,this.recentLatencySumMs=0,this.recentLatencyCount=0,this.recentLatencies=[],this.lastOutputTokens=null,this.totalOutputTokens=0,this.lastEstimatedCostUsd=null,this.totalEstimatedCostUsd=0,this.searchHistoryFailureCount=0}},tn=new bo;function hl(){tn.recordIndexStart()}function _o(){tn.recordIndexCacheHit()}function gl(s){tn.recordIndexEnd(s)}function Ps(s,e){tn.recordIndexPhase(s,e)}function yl(){tn.clearIndexPhases()}function nn(){return tn.recordQueryStart()}function Ft(){tn.recordSearchHistoryFailure()}function Xn(){return tn.getSnapshot()}V();q();import{execSync as bl}from"child_process";var kn=k.child({module:"nano-repair"}),$e=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:i}=L.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};kn.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}),kn.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}),kn.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&&kn.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=bl("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"),kn.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=bl(`git branch --merged "${i}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
708
+ `).map(d=>d.trim().replace(/^\* /,"")).filter(d=>d&&d!==i)}catch{}if(c.length>0){let l=this.missions.findMergedMissions(i,c);for(let d of l)this.missions.updateStatus(d.id,"completed"),kn.info({missionId:d.id,branch:d.git_branch},"Merge Sentinel: Auto-completed mission"),a++}}return(r>0||o>0||a>0)&&kn.info({suspended:r,resumed:o,completed:a},"Git-Native Lifecycle Sync complete"),{suspended:r,resumed:o,completed:a,contextPivotEnabled:t,mergeSentinelEnabled:n}}};import es from"fs";import tt from"path";import{createMatchPath as If,loadConfig as Pf}from"tsconfig-paths";import Ls from"fs";import sn from"path";var rn=class extends Error{constructor(t,n,i){super(n);this.code=t;this.cause=i;this.name="FileSystemError"}};function _l(s){let e;try{e=Ls.statSync(s).isDirectory()?s:sn.dirname(s)}catch(t){throw t.code==="ENOENT"?new rn("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new rn("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new rn("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==sn.dirname(e);){let t=sn.join(e,"tsconfig.json");if(Ls.existsSync(t))return e;e=sn.dirname(e)}return null}function Sl(s){let e;try{e=Ls.statSync(s).isDirectory()?s:sn.dirname(s)}catch(t){throw t.code==="ENOENT"?new rn("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new rn("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new rn("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==sn.dirname(e);){let t=sn.join(e,"package.json");if(Ls.existsSync(t))try{if(JSON.parse(Ls.readFileSync(t,"utf8")).workspaces)return e}catch{}e=sn.dirname(e)}return null}import gt from"fs";import wl from"path";var Ef=[".ts",".tsx",".d.ts",".js",".jsx"];function Je(s){let e=wl.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(gt.existsSync(r)&&gt.statSync(r).isFile())return r}if(gt.existsSync(s)&&gt.statSync(s).isFile())return s}if(gt.existsSync(s)&&gt.statSync(s).isFile())return s;for(let t of Ef){let n=s+t;if(gt.existsSync(n)&&gt.statSync(n).isFile())return n}if(gt.existsSync(s)&&gt.statSync(s).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=wl.join(s,"index"+t);if(gt.existsSync(n))return n}return""}import Rn from"fs";import Zn from"path";function El(s,e){let t=new Map,n=e.workspaces||[];for(let i of n){let r=i.replace("/*",""),o=Zn.join(s,r);if(!Rn.existsSync(o))continue;let a=Rn.readdirSync(o);for(let c of a){let l=Zn.join(o,c,"package.json");if(Rn.existsSync(l))try{let d=JSON.parse(Rn.readFileSync(l,"utf8"));d.name&&t.set(d.name,{name:d.name,path:Zn.dirname(l),main:d.main||"dist/index.js"})}catch{}}}return t}function xl(s){let e=new Map;try{let t=JSON.parse(Rn.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=Zn.dirname(s),c=Zn.resolve(a,o),l=Zn.join(c,"package.json");if(Rn.existsSync(l))try{let d=JSON.parse(Rn.readFileSync(l,"utf8"));e.set(i,{name:i,path:c,main:d.main||"dist/index.js"})}catch{}}}catch{}return e}import{builtinModules as xf,createRequire as vf}from"node:module";import kf from"fs";import on from"path";var vl=new Set(xf.map(s=>s.replace(/^node:/,"")));function Rf(s){let e=s.replace(/^node:/,""),t=e.split("/")[0]||e;return vl.has(e)||vl.has(t)}function Tf(s){return/^@[^/]+\/[^/]+/.test(s)}function kl(s){return!!(s.startsWith("#")||s.startsWith("@/")||s.startsWith("~/")||s.startsWith("@")&&!Tf(s))}function Cf(s,e){try{return vf(e).resolve(s)}catch{return null}}function Af(s,e,t){if(!e||e.size===0)return null;for(let[n,i]of e.entries()){if(n.includes("*")){let r="^"+n.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",o=new RegExp(r),a=s.match(o);if(!a)continue;let c=a[1],l=i.replace("*",c),d=on.resolve(t,l);return Je(d)}if(n===s){let r=on.resolve(t,i);return Je(r)}}return null}function So(s,e,t){if(s.startsWith(".")){let i=on.dirname(e),r=on.resolve(i,s),o=Je(r);return o?{resolved:!0,kind:"relative",resolvedPath:o,actionable:!1}:{resolved:!1,kind:"relative",error:`File not found at relative path: ${r}`,suggestion:"Check if the file exists and has a supported extension (.ts, .tsx, .js, .jsx)",actionable:!0}}if(Rf(s))return{resolved:!0,kind:"builtin",resolvedPath:s,actionable:!1};let n=Ns(e);if(n){if(n.matchPath){let r=n.matchPath(s);if(r){let o=Je(r);return o?{resolved:!0,kind:"alias",resolvedPath:o,actionable:!1}:{resolved:!1,kind:"alias",error:`Path alias matched to '${r}' but file does not exist`,suggestion:"Check if the target file exists or if the alias mapping in tsconfig.json is correct",actionable:!0}}}if(!s.startsWith("@")&&!s.startsWith("#")){let r=on.resolve(n.baseUrl,s),o=Je(r);if(o)return{resolved:!0,kind:"workspace-package",resolvedPath:o,actionable:!1}}if(s.startsWith("#")){let r=Af(s,n.imports,n.baseUrl);if(r)return{resolved:!0,kind:"alias",resolvedPath:r,actionable:!1}}let i=n.workspacePackages.get(s);if(i){let r=on.join(i.path,"src/index.ts");if(kf.existsSync(r))return{resolved:!0,kind:"workspace-package",resolvedPath:r,actionable:!1};let o=on.join(i.path,i.main),a=Je(o);return a?{resolved:!0,kind:"workspace-package",resolvedPath:a,actionable:!1}:{resolved:!1,kind:"workspace-package",error:`Workspace package '${s}' found at ${i.path} but entry point not found`,suggestion:`Check main field in ${on.join(i.path,"package.json")}`,actionable:!0}}}else if(kl(s))return{resolved:!1,kind:"alias",error:"No tsconfig.json found for alias-style import",suggestion:'Ensure tsconfig.json exists and defines the expected "paths" aliases',actionable:!0};if(!s.startsWith("/")&&!s.startsWith(".")){let i=Cf(s,e);if(i)return{resolved:!0,kind:"external-package",resolvedPath:i,actionable:!1}}return s.startsWith("#")?{resolved:!1,kind:"alias",error:`Package import alias '${s}' not found in package.json "imports"`,suggestion:'Check package.json "imports" configuration for this alias',actionable:!0}:kl(s)?{resolved:!1,kind:"alias",error:`Path alias '${s}' not found in tsconfig.json paths`,suggestion:'Check tsconfig.json "paths" configuration',actionable:!0}:{resolved:!1,kind:"missing",error:`Module '${s}' could not be resolved`,suggestion:"Install dependency or check import path",actionable:!0}}var Tn=new Map;function Rl(s){if(!s){Tn.clear();return}let e=tt.resolve(s);for(let t of Tn.keys())(t===e||t.startsWith(`${e}${tt.sep}`))&&Tn.delete(t)}function Ns(s){let e=_l(s);if(!e)return null;if(Tn.has(e))return Tn.get(e)||null;let t=Pf(e);if(t.resultType==="failed")return Tn.set(e,null),null;let n=t,i=n.absoluteBaseUrl;!i&&n.paths&&Object.keys(n.paths).length>0&&(i=n.configFileAbsolutePath?tt.dirname(n.configFileAbsolutePath):e);let r=If(i,n.paths,n.mainFields,n.addMatchAll),o=Sl(e),a=new Map;if(o){let p=tt.join(o,"package.json");if(es.existsSync(p))try{let u=JSON.parse(es.readFileSync(p,"utf8"));a=El(o,u)}catch{}}let c=tt.join(e,"package.json");es.existsSync(c)&&xl(c).forEach((u,m)=>a.set(m,u));let l={baseUrl:i||"",paths:n.paths,matchPath:r,workspacePackages:a,imports:new Map},d=tt.join(e,"package.json");if(es.existsSync(d))try{let p=JSON.parse(es.readFileSync(d,"utf8"));if(p.imports){for(let[u,m]of Object.entries(p.imports))if(typeof m=="string"||typeof m=="object"&&m!==null){let f=m;Array.isArray(m)&&(f=m[0]),typeof f=="object"&&(f=f.default||f.node),typeof f=="string"&&l.imports.set(u,f)}}}catch{}return Tn.set(e,l),l}function Cn(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=Cn(i,e,t);if(r)return r}}if(s.startsWith(".")){let i=tt.dirname(e),r=tt.resolve(i,s);return Je(r)}let n=Ns(e);if(n){let i=n.matchPath(s);if(i)return Je(i);if(!s.startsWith("@")||s.startsWith("@/")){let o=tt.resolve(n.baseUrl,s),a=Je(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),d=s.match(l);if(d){let p=d[1],u=a.replace("*",p),m=tt.resolve(n.baseUrl,u);return Je(m)}}else if(o===s){let c=tt.resolve(n.baseUrl,a);return Je(c)}let r=n.workspacePackages.get(s);if(r){let o=tt.join(r.path,"src/index.ts");if(es.existsSync(o))return o;let a=tt.join(r.path,r.main),c=Je(a);if(c)return c}}return""}import Lf from"fast-glob";import Tl from"fs";import Nf from"ignore";import Cl from"path";async function Al(s,e=[]){let t=Nf(),n=Cl.join(s,".gitignore");return Tl.existsSync(n)&&t.add(Tl.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await Lf(fc,{cwd:s,absolute:!0,ignore:Si,stats:!0})).filter(o=>{let a=Cl.relative(s,o.path);return!t.ignores(a)}).map(o=>({path:o.path,mtime:o.stats.mtimeMs}))}q();var Df=$f.cpus().length||4,Of=wi.DEFAULT_CONCURRENCY;function Nl(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&&Nl(t.members,e));return e}function Il(s){if(typeof s!="number"||!Number.isFinite(s))return null;let e=Math.trunc(s);return e>0?e:null}function Ml(s){let e=typeof s?.content=="string"&&s.content.length>0?s.content.split(`
709
+ `).length:0,t=Nl(s?.exports),n=0,i=0,r=0,o=0;for(let a of t){let c=Il(a?.line??a?.start_line),l=Il(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 Ff(s){let e=Ml(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 Pl(s){let e=Ml(s);return e.valid*2+e.multiLine*2-e.eofCollapsed*3-e.invalid*4}function Ll(s){let e=Wi.basename(s);return e==="package.json"||/^tsconfig(?:\.[^.]+)*\.json$/i.test(e)||/^jsconfig(?:\.[^.]+)*\.json$/i.test(e)}async function Q(s,e=Of,t=!1,n=!0,i){let r=L.getInstance(s),o=r.files.database,a=Ot(s),c=a.concurrency??e;if(hl(),!t&&Re(s)){let g=En(s),w=Ne(s);if(g&&!Jn(s,g))return _o(),k.debug({repoPath:s,commit:w},"Index is current, skipping re-index (fast-path)"),o}Rl(s),Ns(s);let l=r.files.findAll(),d=new Map(l.map(g=>[g.path,{mtime:g.mtime,hash:g.content_hash}])),p=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let u=await Al(s,a.ignore),m=new Map(u.map(g=>[g.path,g.mtime])),f=l.filter(g=>!m.has(g.path)).map(g=>g.path),h=l.length===0,y=[];if(t||h)y.push(...u);else{let g=u.filter(E=>{let I=d.get(E.path);return!I||I.mtime!==E.mtime}),w=wo(c*4),A=g.map(E=>w(async()=>{let I=d.get(E.path);if(!I||!I.hash)return E;try{let N=await Mf.promises.readFile(E.path,"utf8");return za(N,I.hash)?E:(r.files.updateMtime(E.path,E.mtime),null)}catch{return null}})),x=await Promise.all(A);y.push(...x.filter(E=>E!==null))}if(!t&&(f.some(Ll)||y.some(g=>Ll(g.path)))&&(k.info({repoPath:s},"Resolver-affecting config changed; reparsing all indexable files"),y.length=0,y.push(...u)),f.length===0&&y.length===0){_o();let g=Ne(s);return Qr(s,g||void 0),o}if(h?k.info({totalFiles:u.length},"Starting initial repository indexing..."):k.info({toDelete:f.length,toProcess:y.length},"Syncing repository updates..."),f.length>0&&r.files.deletePaths(f),y.length>0){yl(),n?(ci(!0),Gn().initialize().catch(()=>{})):ci(!1);let g=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,w=[],A=[];for(let M of y)g.test(Wi.basename(M.path))?w.push(M):A.push(M);let x=0,E=y.length,I=!1,N=jc();try{await N.initialize(),I=!0,k.info({workers:N.workerCount},"Parser worker pool active")}catch(M){k.warn({err:M},"Parser worker pool failed to initialize, falling back to main-thread parsing"),I=!1}let P=async(M,D)=>{let O=D;if(I&&Ff(D))try{let v=await As(M.path);Pl(v)>Pl(D)&&(k.warn({filePath:M.path},"Detected suspicious worker parse ranges; using main-thread parse output"),O=v)}catch(v){k.warn({filePath:M.path,err:v instanceof Error?v.message:String(v)},"Main-thread parse retry failed after suspicious worker parse")}let Y=O.imports?.map(v=>({...v,resolved_path:Cn(v.module,M.path,s)})),z=O.content?Un(O.content):null;return x++,(x%50===0||x===E)&&k.info({completed:x,total:E},"Parsing files..."),i?.({phase:"parse",current:x,total:E,message:`Parsing ${Wi.basename(M.path)}`}),{meta:M,...O,imports:Y,embedding:null,kind:"code",contentHash:z}},C;if(I)C=w.map(M=>N.parseFile(M.path).then(D=>P(M,D),D=>(x++,k.error({path:M.path,error:D},"Worker parse failed"),{meta:M,exports:[],imports:[],content:"",kind:"error"})));else{let M=h?Math.max(c,Math.min(Df-1,16)):c,D=wo(M);C=w.map(O=>D(async()=>{try{let Y=await As(O.path);return P(O,Y)}catch(Y){return x++,k.error({path:O.path,error:Y},"Failed to parse file"),{meta:O,exports:[],imports:[],content:"",kind:"error"}}}))}let W=wo(c),j=A.map(M=>W(async()=>{try{let D=hc(M.path),O=D.content?Un(D.content):null;return x++,(x%50===0||x===E)&&k.info({completed:x,total:E},"Parsing configs..."),i?.({phase:"parse",current:x,total:E,message:`Parsing config ${Wi.basename(M.path)}`}),{meta:M,...D,embedding:null,kind:"config",contentHash:O}}catch(D){return x++,k.error({path:M.path,error:D},"Failed to parse config"),{meta:M,exports:[],imports:[],content:"",kind:"error"}}}));k.info({total:E,codeFiles:w.length,configFiles:A.length,useParserPool:I},"Phase 1: Parsing all files...");let K=Date.now(),U=(await Promise.all([...C,...j])).filter(Boolean),H=Date.now()-K;if(Ps("parse",H),k.info({count:U.length,time:`${(H/1e3).toFixed(1)}s`},"Phase 1 complete"),I&&zc().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let M=[];U.forEach((R,T)=>{"summary"in R&&R.summary&&M.push({fileIdx:T,text:R.summary})}),k.info("Phase 2+3: Generating file-summary embeddings + persisting in parallel..."),i?.({phase:"embed",current:0,total:U.length,message:"Generating embeddings..."});let D=Date.now(),O=(async()=>{let R=[];return M.length>0&&(k.info({count:M.length}," \u2192 Generating file summary embeddings..."),R=await no(M.map(T=>T.text),256),k.info({count:M.length}," \u2713 File summaries complete")),R})();i?.({phase:"persist",current:0,total:U.length,message:"Saving to database..."});let Y=Date.now();r.files.batchSaveIndexResults(U,s,Un,Cn);let z=Date.now()-Y;Ps("persist",z),k.info({time:`${(z/1e3).toFixed(1)}s`},"Structural persist complete");let v=await O,_=Date.now()-D;if(Ps("embed",_),k.info({time:`${(_/1e3).toFixed(1)}s`},"File-summary embeddings complete"),v.length>0){let R=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),T=o.transaction(F=>{for(let B of F)R.run(B.embedding?JSON.stringify(B.embedding):null,B.path)}),$=M.map((F,B)=>({path:U[F.fileIdx].meta.path,embedding:v[B]}));T($),k.info({count:$.length},"File embedding column updated")}}else{i?.({phase:"persist",current:0,total:U.length,message:"Saving to database..."});let M=Date.now();r.files.batchSaveIndexResults(U,s,Un,Cn),Ps("persist",Date.now()-M)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(h||y.length>0){let g=Ne(s);Qr(s,g||void 0)}if(n&&!Gc(s)&&qc(s),(y.length>0||f.length>0)&&new $e(s).detectAndRepairShifts(),h||n)try{new Qn(s).analyzeHeritage(50)}catch(g){k.warn({err:g.message},"Heritage sync deferred")}return gl(Date.now()-p),i?.({phase:"complete",current:y.length,total:y.length,message:"Indexing complete"}),o}V();import $l from"path";function Dl(s){let e=s.replace(/\\/g,"/").toLowerCase();return e.includes("/test/")||e.includes("/tests/")||e.includes("/__tests__/")||e.endsWith(".spec.ts")||e.endsWith(".spec.tsx")||e.endsWith(".spec.js")||e.endsWith(".spec.jsx")||e.endsWith(".test.ts")||e.endsWith(".test.tsx")||e.endsWith(".test.js")||e.endsWith(".test.jsx")}var an=class{constructor(e){this.repoPath=e}getMappedTestsForSymbol(e,t,n=10){let i=L.getInstance(this.repoPath),r=Math.max(1,Math.min(n,50)),o=i.imports.findProxies(e).map(p=>p.file_path),a=Array.from(new Set([e,...o])),c=new Map,l=i.imports.findVerifiedDependents(a,t);for(let p of l)Dl(p.file_path)&&(c.has(p.file_path)||c.set(p.file_path,{absolutePath:p.file_path,file:$l.relative(this.repoPath,p.file_path),via:"import",confidence:"high"}));let d=i.files.findContentByToken(t,r*3);for(let p of d)Dl(p)&&(c.has(p)||c.set(p,{absolutePath:p,file:$l.relative(this.repoPath,p),via:"content",confidence:"medium"}));return Array.from(c.values()).sort((p,u)=>p.confidence!==u.confidence?p.confidence==="high"?-1:1:p.file.localeCompare(u.file)).slice(0,r)}};Ae();import vo from"fs";import nt from"path";q();import Eo from"fs";import ve from"path";var ji=k.child({module:"path-resolver"}),Ms=class{repoPath;constructor(e){this.repoPath=ve.isAbsolute(e)?ve.normalize(e):ve.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw ji.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(ve.isAbsolute(e)?t=ve.normalize(e):t=ve.join(this.repoPath,e),t=ve.normalize(t),!this.isWithinRoot(t))throw ji.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 Eo.existsSync(t)?t:(ji.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return ji.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=ve.resolve(e),n=ve.resolve(this.repoPath),i=ve.relative(n,t);if(i.startsWith("..")||ve.isAbsolute(i))return!1;if(Eo.existsSync(t)){let o=Eo.realpathSync(t),a=ve.relative(n,o);if(a.startsWith("..")||ve.isAbsolute(a))return!1}return!0}catch{return!1}}getRelative(e){let t=ve.normalize(e);return ve.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return ve.normalize(e)}static isPathWithinRoot(e,t){let n=ve.resolve(e),i=ve.resolve(t),r=ve.relative(n,i);return r===""||!r.startsWith("..")&&!ve.isAbsolute(r)}};function Ol(s){return new Ms(s)}var Wf=/[\x00-\x1f\x7f]/g,jf=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function xo(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(Wf,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function ts(s,e=4096){if(typeof s!="string")return"";let t=s.replace(jf,"").trim();return t.length>e?t.slice(0,e):t}function zf(s){let e=nt.isAbsolute(s)?nt.normalize(s):nt.resolve(process.cwd(),s),t=nt.parse(e).root;for(;e!==t;){if(vo.existsSync(nt.join(e,".liquid-shadow.db"))||vo.existsSync(nt.join(e,".git"))||vo.existsSync(nt.join(e,"package.json")))return e;let n=nt.dirname(e);if(n===e)break;e=n}return null}function de(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=xo(e)),t&&(t=xo(t));let n;if(e)nt.isAbsolute(e)||(e=nt.resolve(process.cwd(),e)),n=e;else if(t){let o=nt.resolve(process.cwd(),t);n=zf(nt.dirname(o))||process.cwd()}else n=process.cwd();n=nt.normalize(n);let i=Ol(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}var Fl={low:0,medium:1,high:2};function zi(s,e){return Fl[s]>Fl[e]?e:s}function Hf(s){return s==="high"?"medium":"low"}function Uf(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bf(s,e){if(!e||e.length<3)return!1;try{let t=jl.readFileSync(s,"utf8"),n=Uf(e);return[new RegExp(`\\bextends\\s+${n}\\b`),new RegExp(`\\bimplements\\s+[^\\n{;]*\\b${n}\\b`),new RegExp(`\\bnew\\s+${n}\\s*\\(`),new RegExp(`\\b${n}\\s*<`),new RegExp(`[:(,]\\s*${n}\\b`)].some(o=>o.test(t))?!0:(t.match(new RegExp(`\\b${n}\\b`,"g"))??[]).length>2}catch{return!1}}function Gf(s,e,t,n,i){let r=n,o=i,a=s.toLowerCase().replace(/\\/g,"/");return(a.includes("/__generated__/")||a.includes("/generated/")||a.includes("/.generated/")||a.includes("/dist/")||a.includes("/build/")||a.includes("/vendor/")||a.includes("/coverage/")||a.includes(".generated.")||a.includes(".gen."))&&(r=zi(r,"low"),o+="; generated artifact"),(/(^|\/)(src\/)?app\/.*\/(route|page|layout|loading|error|not-found|default|template)\.(t|j)sx?$/.test(a)||/(^|\/)(src\/)?middleware\.(t|j)sx?$/.test(a)||a.includes("/routes/")||a.includes("/controllers/"))&&(r=zi(r,"medium"),o+="; framework convention entrypoint"),(a.includes("/registry/")||a.includes("/registries/")||a.includes("/plugins/")||a.includes("/providers/")||a.includes("/bootstrap/")||/register|resolver|plugin|provider|adapter/i.test(e))&&(r=zi(r,"medium"),o+="; dynamic discovery surface"),t==="ClassDeclaration"&&Bf(s,e)&&(r=zi(r,"medium"),o+="; same-file references detected"),{confidence:r,reason:o}}function qf(s){let e=new Map;for(let t of s)t.resolved_path&&(e.has(t.file_path)||e.set(t.file_path,new Set),e.has(t.resolved_path)||e.set(t.resolved_path,new Set),e.get(t.file_path).add(t.resolved_path));return e}function Jf(s){let e=0,t=[],n=new Set,i=new Map,r=new Map,o=[],a=c=>{i.set(c,e),r.set(c,e),e++,t.push(c),n.add(c);for(let l of s.get(c)||[])i.has(l)?n.has(l)&&r.set(c,Math.min(r.get(c),i.get(l))):(a(l),r.set(c,Math.min(r.get(c),r.get(l))));if(r.get(c)===i.get(c)){let l=[];for(;t.length>0;){let d=t.pop();if(n.delete(d),l.push(d),d===c)break}o.push(l)}};for(let c of s.keys())i.has(c)||a(c);return o}function Kf(s,e,t){let n=t.get(s);if(n===void 0){try{n=jl.readFileSync(s,"utf8")}catch{n=""}t.set(s,n)}if(!n)return!1;let i=e.module_specifier.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`import\\s+type\\s+.*from\\s+['"]${i}['"]`,"i"),o=new RegExp(`import\\s+\\{.*type\\s+.*\\}.*from\\s+['"]${i}['"]`,"s");if(r.test(n)||o.test(n))return!0;let a=e.imported_symbols.split(",").map(c=>c.trim());for(let c of a){if(!c||c==="*")continue;let l=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\(\\s*\\)\\s*=>\\s*${l}`).test(n))return!0}return!1}function Vf(s){let e=new Map;for(let t of s){if(!t.resolved_path)continue;let n=`${t.file_path}|${t.resolved_path}`;e.has(n)||e.set(n,[]),e.get(n).push(t)}return e}function Wl(s,e){let t=new Map,n=new Map;for(let a of s)a.resolved_path&&(t.has(a.file_path)||t.set(a.file_path,new Set),n.has(a.file_path)||n.set(a.file_path,new Set),t.has(a.resolved_path)||t.set(a.resolved_path,new Set),n.has(a.resolved_path)||n.set(a.resolved_path,new Set),t.get(a.file_path).add(a.resolved_path),n.get(a.resolved_path).add(a.file_path));let r=Array.from(new Set([...t.keys(),...n.keys()])).map(a=>{let c=t.get(a)?.size||0,l=n.get(a)?.size||0,d=l+c===0?0:c/(l+c);return{file:$s.relative(e,a),afferent:l,efferent:c,instability:Number(d.toFixed(3))}}),o=r.length===0?0:Number((r.reduce((a,c)=>a+c.instability,0)/r.length).toFixed(3));return{module_count:r.length,average_instability:o,top_efferent:[...r].sort((a,c)=>c.efferent-a.efferent).slice(0,10),top_afferent:[...r].sort((a,c)=>c.afferent-a.afferent).slice(0,10),most_unstable:[...r].filter(a=>a.afferent+a.efferent>0).sort((a,c)=>c.instability-a.instability||c.efferent-a.efferent).slice(0,10)}}async function zl(s){let{repoPath:e}=de(s),{mode:t,limit:n=50,includeTests:i=!1,includeMigrations:r=!1,includeFixtures:o=!1,excludePatterns:a=[],confidenceThreshold:c="all"}=s;await Q(e);let{exports:l,imports:d}=L.getInstance(e);if(t==="dead-code"){let p=l.findDeadExports({limit:n,includeTests:i,includeMigrations:r,includeFixtures:o,excludePatterns:a,confidenceThreshold:c}),u=new an(e),m=d.getAllResolved(),f=Wl(m,e),h=p.map(x=>{let E=u.getMappedTestsForSymbol(x.file_path,x.name,6),I=Gf(x.file_path,x.name,x.kind,x.confidence,x.reason),N=I.confidence,P=I.reason;return E.length>0&&(N=Hf(N),P+="; covered by tests"),{name:x.name,kind:x.kind,file:$s.relative(e,x.file_path),line:x.start_line,confidence:N,reason:P,testCoverage:{mappedTestCount:E.length,mappedTests:E.map(C=>C.file),coverageHint:E.length>0?"covered":"uncovered"}}}),y={high:{},medium:{},low:{}};for(let x of h)y[x.confidence][x.file]||(y[x.confidence][x.file]=[]),y[x.confidence][x.file].push({name:x.name,kind:x.kind,line:x.line,reason:x.reason,testCoverage:x.testCoverage});let b=[],g=Object.values(y.high).flat().length,w=Object.values(y.medium).flat().length,A=Object.values(y.low).flat().length;return b.push(`# Dead Export Analysis
710
+ `),b.push(`Returned ${h.length} potentially unused exports (scan limit: ${n}).`),b.push(`- **High confidence** (likely dead): ${g}`),b.push(`- **Medium confidence** (possibly intentional): ${w}`),b.push(`- **Low confidence** (likely intentional): ${A}
711
+ `),g>0&&(b.push(`## High Confidence (Likely Dead)
712
+ `),b.push(JSON.stringify(y.high,null,2))),w>0&&c!=="high"&&(b.push(`
713
+ ## Medium Confidence (Possibly Intentional)
714
+ `),b.push(JSON.stringify(y.medium,null,2))),A>0&&c==="all"&&(b.push(`
715
+ ## Low Confidence (Likely Intentional)
716
+ `),b.push(JSON.stringify(y.low,null,2))),b.push(`
717
+ ## Structural Risk Metrics
718
+ `),b.push(JSON.stringify(f,null,2)),{content:[{type:"text",text:b.join(`
719
+ `)}]}}else if(t==="circular-deps"){let p=typeof n=="number"?n:20,u=d.getAllResolved(),m=qf(u),f=Jf(m),h=Vf(u),y=new Map,b=Wl(u,e),w=f.filter(A=>{if(A.length>1)return!0;let x=A[0];return(m.get(x)||new Set).has(x)}).map(A=>{let x=new Set(A),E=[];for(let N of A)for(let P of m.get(N)||[])x.has(P)&&E.push({from:N,to:P});let I=E.filter(({from:N,to:P})=>{let C=h.get(`${N}|${P}`)||[];return C.length===0?!0:!C.every(W=>Kf(N,W,y))});return{component:A,internalEdges:E,unsafeEdges:I}}).filter(A=>A.unsafeEdges.length>0).sort((A,x)=>x.component.length-A.component.length||x.unsafeEdges.length-A.unsafeEdges.length).slice(0,p).map((A,x)=>({id:x+1,size:A.component.length,files:A.component.map(E=>$s.relative(e,E)).sort(),internal_edge_count:A.internalEdges.length,unsafe_edge_count:A.unsafeEdges.length,unsafe_edges:A.unsafeEdges.slice(0,10).map(E=>`${$s.relative(e,E.from)} -> ${$s.relative(e,E.to)}`)}));return{content:[{type:"text",text:`# Circular Dependency Analysis
720
+
721
+ Returned ${w.length} circular dependency group(s) (scan limit: ${p}).
722
+
723
+ ## SCC Groups
724
+ ${JSON.stringify(w,null,2)}
725
+
726
+ ## Structural Risk Metrics
727
+ ${JSON.stringify(b,null,2)}`}]}}return{isError:!0,content:[{type:"text",text:"Invalid mode"}]}}V();import Hi from"path";function Yf(s){return/^@[^/]+\/[^/]+/.test(s)}function Qf(s){return!!(s.startsWith("#")||s.startsWith("@/")||s.startsWith("~/")||s.startsWith("@")&&!Yf(s))}function Xf(s,e){if(!e)return null;let t=Hi.relative(s,e);return!t||t.startsWith("..")||Hi.isAbsolute(t)?null:t}function Zf(s,e,t){return s.startsWith("node:")?"builtin":s.startsWith(".")?"relative":Qf(s)?"alias":e.startsWith(t+Hi.sep)?"workspace-package":"external-package"}function eh(s){return s==="builtin"||s==="external-package"||s==="missing"}async function Ul(s){let{repoPath:e,filePath:t}=de(s),{direction:n,limit:i,offset:r=0}=s;if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};await Q(e);let{imports:o}=L.getInstance(e);if(n==="imports"){let c=o.findByFile(t).filter(u=>u.module_specifier!=="__type_reference__").map(u=>{let m=u.resolved_path?null:So(u.module_specifier,t,e),f=u.resolved_path||m?.resolvedPath||null,h=u.resolved_path?Zf(u.module_specifier,u.resolved_path,e):m?.kind||"missing",y={module:u.module_specifier,symbols:u.imported_symbols,resolvedPath:f,relativePath:Xf(e,f),isExternal:eh(h),dependencyClass:h,isBuiltin:h==="builtin"};if(m&&!m.resolved){let b={...y,resolutionError:m.error};return m.actionable&&m.suggestion?{...b,suggestion:m.suggestion}:b}return y}),l=[...c].sort((u,m)=>(u.relativePath||"").localeCompare(m.relativePath||"")),p={results:Hl(l,i,r),total:c.length,offset:r,limit:i||c.length,hasMore:i?r+i<c.length:!1};return{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}else{let c=o.findDependents(t).map(u=>({file:u.file_path,relativePath:Hi.relative(e,u.file_path),importStatement:u.module_specifier,importedSymbols:u.imported_symbols})),l=[...c].sort((u,m)=>(u.relativePath||"").localeCompare(m.relativePath||"")),p={results:Hl(l,i,r),total:c.length,offset:r,limit:i||c.length,hasMore:i?r+i<c.length:!1};return{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}}function Hl(s,e,t=0){return e?s.slice(t,t+e):s.slice(t)}V();V();import{execSync as th}from"child_process";import nh from"fs";import Bl from"path";function Gl(s){let e=s.trim();if(!/^[A-Za-z0-9._:/-]+$/.test(e))throw new Error(`Invalid git ref: ${s}`);return e}function Ui(s){let e=s.trim();return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function sh(s){if(s.length<=1)return s;let e=[...s].sort((n,i)=>n.start-i.start),t=[];for(let n of e){let i=t[t.length-1];if(!i||n.start>i.end+1){t.push({...n});continue}i.end=Math.max(i.end,n.end)}return t}function ih(s){if(!s.trim())return[];let e=s.split(`
728
+ `).map(n=>n.trim()).filter(Boolean),t=[];for(let n of e){let i=n.split(" ").filter(Boolean);if(i.length<2)continue;let o=i[0].charAt(0).toUpperCase(),a=o==="M"?"modified":o==="A"?"added":o==="D"?"deleted":o==="R"?"renamed":o==="C"?"copied":"unknown";if((a==="renamed"||a==="copied")&&i.length>=3){t.push({status:a,oldPath:Ui(i[1]),path:Ui(i[2])});continue}t.push({status:a,path:Ui(i[1])})}return t}function rh(s){let e=new Map;if(!s.trim())return e;let t=null,n=s.split(`
729
+ `);for(let i of n){if(i.startsWith("+++ ")){let c=i.slice(4).trim();c==="/dev/null"?t=null:(t=Ui(c),e.has(t)||e.set(t,[]));continue}if(!t)continue;let r=i.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);if(!r)continue;let o=Number(r[1]),a=Number(r[2]||"1");!Number.isFinite(o)||!Number.isFinite(a)||a<=0||e.get(t).push({start:o,end:o+a-1})}for(let[i,r]of e.entries())e.set(i,sh(r));return e}function oh(s,e,t){return s<=t.end&&t.start<=e}var Bi=class{constructor(e){this.repoPath=e}execGit(e){let t=`git ${e.join(" ")}`;return th(t,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}buildDiffArgs(e,t){let n=["diff","--find-renames"];t?n.push("--unified=0","--no-color"):n.push("--name-status"),e.staged&&n.push("--cached");let i=e.baseCommit?Gl(e.baseCommit):null,r=e.headCommit?Gl(e.headCommit):null;return i&&r?n.push(i,r):i?n.push(i):e.staged||n.push("HEAD"),n}collectFileChanges(e={}){let t=this.execGit(this.buildDiffArgs(e,!1)),n=this.execGit(this.buildDiffArgs(e,!0)),i=ih(t),r=rh(n),o=new Map;for(let a of i){let c=r.get(a.path)||[];o.set(a.path,{relativePath:a.path,absolutePath:Bl.resolve(this.repoPath,a.path),status:a.status,...a.oldPath?{oldRelativePath:a.oldPath}:{},ranges:c})}if(e.includeUntracked){let a=this.execGit(["ls-files","--others","--exclude-standard"]);if(a)for(let c of a.split(`
730
+ `).map(l=>l.trim()).filter(Boolean))o.has(c)||o.set(c,{relativePath:c,absolutePath:Bl.resolve(this.repoPath,c),status:"added",ranges:[]})}return Array.from(o.values()).sort((a,c)=>a.relativePath.localeCompare(c.relativePath))}mapChangesToSymbols(e,t=30){let n=L.getInstance(this.repoPath),i=Math.max(1,Math.min(t,200)),r=[],o=new Set;for(let a of e){if(a.status==="deleted"||!nh.existsSync(a.absolutePath))continue;let c=n.exports.findByFile(a.absolutePath);if(c.length!==0)for(let l of c){let d=l.start_line||1,p=l.end_line||d,u=a.ranges.length===0?[]:a.ranges.filter(f=>oh(d,p,f));if(a.ranges.length>0&&u.length===0)continue;let m=`${a.relativePath}:${l.name}:${d}`;o.has(m)||(o.add(m),r.push({id:l.id||null,name:l.name,kind:l.kind,file:a.relativePath,absolutePath:a.absolutePath,startLine:d,endLine:p,status:a.status,changedRanges:u}))}}return r.sort((a,c)=>a.file!==c.file?a.file.localeCompare(c.file):a.startLine-c.startLine).slice(0,i)}};V();import Mo from"fs";import Mn from"path";Ae();import rp from"crypto";import Rh from"better-sqlite3";import zt from"fs";import Th from"os";import is from"path";q();var Wt=k.child({module:"edge-scanner"});function Gi(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function ah(s,e){return s==="api_route"?Gi(e).toLowerCase():e.trim().toLowerCase()}function ch(s){if(!s)return null;try{let e=JSON.parse(s);return e.path||e.name||null}catch{return null}}function lh(s,e){let t=Gi(s),n=Gi(e);if(t===n)return!0;let i=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function ph(s){Wt.info("Starting HTTP gap detection scan");let e=s.getAttachedRepos();if(e.length<2)return Wt.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
731
+ SELECT id, name, file_path, capabilities
732
+ FROM ${r.alias}.exports
733
+ WHERE kind = 'HTTP Route'
734
+ `,a=s.executeRawQuery(o);for(let c of a){let l=ch(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){Wt.warn({repo:r.alias,error:o},"Failed to query backend routes")}Wt.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
735
+ SELECT file_path, name
736
+ FROM ${r.alias}.event_synapses
737
+ WHERE type = 'api_route' AND direction = 'produce'
738
+ `,a=s.executeRawQuery(o);for(let c of a){let l=Gi(c.name);l&&l.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,routePath:l})}}catch(o){Wt.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}Wt.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&&lh(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){Wt.debug({source:r.filePath,target:o.filePath,error:a},"Skipped duplicate edge")}return Wt.info({edgesCreated:i,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),i}function dh(s){let e=s.getAttachedRepos();if(e.length<2)return 0;let t=0;for(let n of e)for(let i of e)if(n.repoPath!==i.repoPath)try{let r=s.executeRawQuery(`
739
+ SELECT
740
+ i.file_path AS source_file_path,
741
+ i.module_specifier,
742
+ i.imported_symbols,
743
+ f.path AS target_file_path
744
+ FROM ${n.alias}.imports i
745
+ JOIN ${i.alias}.files f ON i.resolved_path = f.path
746
+ WHERE i.resolved_path IS NOT NULL
747
+ AND i.resolved_path != ''
748
+ AND i.module_specifier != '__type_reference__'
749
+ `);for(let o of r)try{s.addVirtualEdge({sourceRepo:n.repoPath,sourceFilePath:o.source_file_path,targetRepo:i.repoPath,targetFilePath:o.target_file_path,relationship:"import_reference",metadata:{moduleSpecifier:o.module_specifier,importedSymbols:o.imported_symbols},confidence:.98}),t++}catch{}}catch(r){Wt.warn({sourceRepo:n.repoPath,targetRepo:i.repoPath,error:r},"Failed to scan cross-repo imports")}return t}function ql(s,e,t){let n=s.getAttachedRepos();if(n.length<2)return 0;let i=[],r=[];for(let a of n)try{let c=s.executeRawQuery(`
750
+ SELECT file_path, name, direction
751
+ FROM ${a.alias}.event_synapses
752
+ WHERE type = ?
753
+ AND direction IN ('produce', 'consume')
754
+ `,e);for(let l of c){let d=ah(e,l.name);(l.direction==="produce"?i:r).push({repoPath:a.repoPath,filePath:l.file_path,name:l.name,normalizedName:d})}}catch{}let o=0;for(let a of i)for(let c of r)if(a.repoPath!==c.repoPath&&a.normalizedName===c.normalizedName)try{s.addVirtualEdge({sourceRepo:a.repoPath,sourceFilePath:a.filePath,targetRepo:c.repoPath,targetFilePath:c.filePath,relationship:t,metadata:{type:e,name:a.name},confidence:.96}),o++}catch{}return o}function Jl(s){s.clearVirtualEdges("api_call"),s.clearVirtualEdges("import_reference"),s.clearVirtualEdges("pubsub_flow"),s.clearVirtualEdges("socket_flow");let e=ph(s),t=dh(s),n=ql(s,"pubsub_topic","pubsub_flow"),i=ql(s,"socket_event","socket_flow"),r=e+t+n+i;return{httpGaps:e,importReferences:t,pubsubFlows:n,socketFlows:i,totalEdges:r}}q();var uh=k.child({module:"fusion-index-service"}),qi=class{constructor(e){this.connection=e}executeFederatedQuery(e,...t){return this.connection.prepare(e).all(...t).map(r=>{let{_repo_alias:o,_repo_path:a,...c}=r;return{repo:o,repoPath:a,data:c}})}executeRawQuery(e,...t){return this.connection.prepare(e).all(...t)}buildAdvancedQuery(e){let t=this.connection.getAttachedRepos();if(t.length===0)throw new Error("No repositories attached");let{table:n,tableAlias:i,columns:r,joins:o,where:a,groupBy:c,having:l,orderBy:d,limit:p,offset:u}=e,m=i||n.charAt(0),f=r.join(", "),y=t.map(b=>{let g=`${b.alias}.${n} ${m}`,w="";o&&o.length>0&&(w=o.map(I=>{let N=I.alias||I.table.charAt(0);return`${I.type} JOIN ${b.alias}.${I.table} ${N} ON ${I.on}`}).join(`
755
+ `));let A=a?`WHERE ${a}`:"",x=c&&c.length>0?`GROUP BY ${c.join(", ")}`:"",E=l?`HAVING ${l}`:"";return`SELECT '${b.alias}' as _repo_alias, '${b.repoPath}' as _repo_path, ${f} FROM ${g} ${w} ${A} ${x} ${E}`.trim()}).join(`
756
+ UNION ALL
757
+ `);return d&&(y=`SELECT * FROM (${y}) AS federated_results ORDER BY ${d}`),p!==void 0&&(y+=` LIMIT ${p}`),u!==void 0&&(y+=` OFFSET ${u}`),y}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(d=>`c.${d}`).join(", ");return`${o.map(d=>`
758
+ SELECT '${d.alias}' as _repo_alias, '${d.repoPath}' as _repo_path, ${c}, bm25(${d.alias}.${e}) as _fts_rank
759
+ FROM ${d.alias}.${e} fts
760
+ JOIN ${d.alias}.${t} c ON fts.rowid = c.id
761
+ WHERE ${d.alias}.${e} MATCH '"${a}"'`).join(`
762
+ UNION ALL
763
+ `)} ORDER BY _fts_rank LIMIT ${r}`}buildCrossRepoImportsQuery(){let e=this.connection.getAttachedRepos();if(e.length<2)throw new Error("Cross-repo analysis requires at least 2 attached repositories");let t=[];for(let n of e)for(let i of e)n.alias!==i.alias&&t.push(`
764
+ SELECT
765
+ '${n.alias}' as source_repo, '${n.repoPath}' as source_repo_path,
766
+ i.file_path as source_file, i.module_specifier, i.imported_symbols,
767
+ '${i.alias}' as target_repo, '${i.repoPath}' as target_repo_path,
768
+ f.path as target_file
769
+ FROM ${n.alias}.imports i
770
+ JOIN ${i.alias}.files f ON i.resolved_path = f.path
771
+ WHERE i.resolved_path IS NOT NULL`);return t.join(`
772
+ UNION ALL
773
+ `)}buildUnionQuery(e,t,n){let i=this.connection.getAttachedRepos();if(i.length===0)throw new Error("No repositories attached");let r=t.join(", "),o=n?` WHERE ${n}`:"";return i.map(a=>`SELECT '${a.alias}' as _repo_alias, '${a.repoPath}' as _repo_path, ${r} FROM ${a.alias}.${e}${o}`).join(`
774
+ UNION ALL
775
+ `)}searchExports(e,t=50){let n=this.buildUnionQuery("exports",["id","name","kind","file_path","signature"],"name LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}searchFiles(e,t=50){let n=this.buildUnionQuery("files",["path","classification","content_hash"],"path LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}getVirtualEdges(e,t){let n="SELECT * FROM virtual_edges WHERE 1=1",i=[];return e&&(n+=" AND source_repo = ?",i.push(e)),t&&(n+=" AND target_repo = ?",i.push(t)),this.connection.prepare(n).all(...i)}addVirtualEdge(e){return this.connection.prepare(`
776
+ INSERT INTO virtual_edges
777
+ (source_repo, source_file_path, source_symbol_id, target_repo, target_file_path, target_symbol_id, relationship, metadata, confidence, updated_at)
778
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
779
+ `).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}clearVirtualEdges(e){let t=e?"DELETE FROM virtual_edges WHERE relationship = ?":"DELETE FROM virtual_edges";return(e?this.connection.prepare(t).run(e):this.connection.prepare(t).run()).changes}scanEdges(){uh.info({name:this.connection.nameValue},"Starting edge scan");let e=Jl(this);return this.connection.recordEdgeScan({api_call:e.httpGaps,import_reference:e.importReferences,pubsub_flow:e.pubsubFlows,socket_flow:e.socketFlows}),e}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};q();Ae();import mh from"crypto";import fh from"better-sqlite3";import Ji from"fs";import hh from"os";import Ds from"path";function Kl(){let s=hh.homedir(),e=Ds.join(s,".mcp-liquid-shadow","workspaces");return Ji.existsSync(e)||Ji.mkdirSync(e,{recursive:!0}),Ds.join(e,"registry.db")}function Ro(s){return s.map(e=>Ds.resolve(e)).sort()}function gh(s){return mh.createHash("sha256").update(Ro(s).join(`
780
+ `)).digest("hex").slice(0,12)}function yh(s,e,t,n){return n==="building"||n==="failed"?n:e?s.some(i=>!i.exists||!i.indexed)?"degraded":s.some(i=>i.hasIndexDrift)?"stale":t?"degraded":"ready":"failed"}function bh(s){let e=Ds.resolve(s),t=Ji.existsSync(e),n=t?Re(e):!1,i=t?ae(e):null,r=t?Ne(e):null,{lastIndexedCommit:o,lastIndexedAt:a}=t&&n?Qt(e):{lastIndexedCommit:null,lastIndexedAt:null},c=!1,l=null;return t&&n&&(!r||!o?(c=!0,l="missing_git_or_index_commit"):r!==o?(c=!0,l="head_commit_differs"):Jn(e,o)&&(c=!0,l="working_tree_changed")),{repoPath:e,repoName:Ds.basename(e),exists:t,indexed:n,currentBranch:i,headCommit:r,lastIndexedCommit:o,lastIndexedAt:a,hasIndexDrift:c,driftReason:l}}function jt(s){return Ro(s).map(e=>bh(e))}var ko=class{db;dbPath;constructor(){this.dbPath=Kl(),this.db=new fh(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("busy_timeout = 5000"),this.init()}init(){this.db.exec(`
781
+ CREATE TABLE IF NOT EXISTS workspaces (
782
+ name TEXT PRIMARY KEY,
783
+ db_path TEXT NOT NULL,
784
+ repo_paths_json TEXT NOT NULL,
785
+ repo_set_hash TEXT NOT NULL,
786
+ managed_kind TEXT NOT NULL DEFAULT 'unknown',
787
+ state TEXT NOT NULL DEFAULT 'building',
788
+ created_at INTEGER DEFAULT (unixepoch()),
789
+ updated_at INTEGER DEFAULT (unixepoch()),
790
+ last_accessed_at INTEGER,
791
+ last_fused_at INTEGER,
792
+ last_edge_scan_at INTEGER,
793
+ last_error TEXT,
794
+ virtual_edges_count INTEGER NOT NULL DEFAULT 0,
795
+ edge_counts_json TEXT
796
+ );
980
797
 
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(`
983
- `):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(a=>`- \`${a}\` (already installed)`).join(`
984
- `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
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(`
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(`
987
- `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
988
- `))),{content:[{type:"text",text:o.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(`
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(`
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(`
798
+ CREATE TABLE IF NOT EXISTS workspace_repos (
799
+ workspace_name TEXT NOT NULL,
800
+ repo_path TEXT NOT NULL,
801
+ repo_name TEXT NOT NULL,
802
+ current_branch TEXT,
803
+ head_commit TEXT,
804
+ last_indexed_commit TEXT,
805
+ last_indexed_at INTEGER,
806
+ exists_flag INTEGER NOT NULL DEFAULT 0,
807
+ indexed_flag INTEGER NOT NULL DEFAULT 0,
808
+ has_index_drift INTEGER NOT NULL DEFAULT 0,
809
+ drift_reason TEXT,
810
+ updated_at INTEGER DEFAULT (unixepoch()),
811
+ PRIMARY KEY (workspace_name, repo_path),
812
+ FOREIGN KEY (workspace_name) REFERENCES workspaces(name) ON DELETE CASCADE
813
+ );
814
+ `)}upsert(e){let t=Ro(e.repoPaths),n=e.repoSnapshots??jt(t),i=yh(n,Ji.existsSync(e.dbPath),e.lastError,e.explicitState),r=Date.now(),o=e.edgeCounts??{},a=e.virtualEdgesCount??Object.values(o).reduce((c,l)=>c+l,0);return this.db.transaction(()=>{this.db.prepare(`
815
+ INSERT INTO workspaces (
816
+ name,
817
+ db_path,
818
+ repo_paths_json,
819
+ repo_set_hash,
820
+ managed_kind,
821
+ state,
822
+ created_at,
823
+ updated_at,
824
+ last_accessed_at,
825
+ last_fused_at,
826
+ last_edge_scan_at,
827
+ last_error,
828
+ virtual_edges_count,
829
+ edge_counts_json
830
+ )
831
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
832
+ ON CONFLICT(name) DO UPDATE SET
833
+ db_path = excluded.db_path,
834
+ repo_paths_json = excluded.repo_paths_json,
835
+ repo_set_hash = excluded.repo_set_hash,
836
+ managed_kind = excluded.managed_kind,
837
+ state = excluded.state,
838
+ updated_at = excluded.updated_at,
839
+ last_accessed_at = COALESCE(excluded.last_accessed_at, workspaces.last_accessed_at),
840
+ last_fused_at = COALESCE(excluded.last_fused_at, workspaces.last_fused_at),
841
+ last_edge_scan_at = COALESCE(excluded.last_edge_scan_at, workspaces.last_edge_scan_at),
842
+ last_error = excluded.last_error,
843
+ virtual_edges_count = excluded.virtual_edges_count,
844
+ edge_counts_json = excluded.edge_counts_json
845
+ `).run(e.name,e.dbPath,JSON.stringify(t),e.repoSetHash,e.managedKind??"unknown",i,r,r,e.lastAccessedAt??r,e.lastFusedAt??null,e.lastEdgeScanAt??null,e.lastError??null,a,JSON.stringify(o)),this.db.prepare("DELETE FROM workspace_repos WHERE workspace_name = ?").run(e.name);let c=this.db.prepare(`
846
+ INSERT INTO workspace_repos (
847
+ workspace_name,
848
+ repo_path,
849
+ repo_name,
850
+ current_branch,
851
+ head_commit,
852
+ last_indexed_commit,
853
+ last_indexed_at,
854
+ exists_flag,
855
+ indexed_flag,
856
+ has_index_drift,
857
+ drift_reason,
858
+ updated_at
859
+ )
860
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
861
+ `);for(let l of n)c.run(e.name,l.repoPath,l.repoName,l.currentBranch,l.headCommit,l.lastIndexedCommit,l.lastIndexedAt,l.exists?1:0,l.indexed?1:0,l.hasIndexDrift?1:0,l.driftReason,r)})(),this.get(e.name)}get(e){let t=this.db.prepare(`
862
+ SELECT
863
+ name,
864
+ db_path,
865
+ repo_paths_json,
866
+ repo_set_hash,
867
+ managed_kind,
868
+ state,
869
+ created_at,
870
+ updated_at,
871
+ last_accessed_at,
872
+ last_fused_at,
873
+ last_edge_scan_at,
874
+ last_error,
875
+ virtual_edges_count,
876
+ edge_counts_json
877
+ FROM workspaces
878
+ WHERE name = ?
879
+ `).get(e);if(!t)return null;let n=this.db.prepare(`
880
+ SELECT
881
+ repo_path,
882
+ repo_name,
883
+ current_branch,
884
+ head_commit,
885
+ last_indexed_commit,
886
+ last_indexed_at,
887
+ exists_flag,
888
+ indexed_flag,
889
+ has_index_drift,
890
+ drift_reason
891
+ FROM workspace_repos
892
+ WHERE workspace_name = ?
893
+ ORDER BY repo_path ASC
894
+ `).all(e);return{name:t.name,dbPath:t.db_path,repoPaths:JSON.parse(t.repo_paths_json),repoSetHash:t.repo_set_hash,managedKind:t.managed_kind,state:t.state,createdAt:t.created_at,updatedAt:t.updated_at,lastAccessedAt:t.last_accessed_at,lastFusedAt:t.last_fused_at,lastEdgeScanAt:t.last_edge_scan_at,lastError:t.last_error,virtualEdgesCount:t.virtual_edges_count,edgeCounts:t.edge_counts_json?JSON.parse(t.edge_counts_json):{},repoSnapshots:n.map(i=>({repoPath:i.repo_path,repoName:i.repo_name,exists:!!i.exists_flag,indexed:!!i.indexed_flag,currentBranch:i.current_branch,headCommit:i.head_commit,lastIndexedCommit:i.last_indexed_commit,lastIndexedAt:i.last_indexed_at,hasIndexDrift:!!i.has_index_drift,driftReason:i.drift_reason}))}}list(){return this.db.prepare("SELECT name FROM workspaces ORDER BY COALESCE(last_accessed_at, 0) DESC").all().map(t=>this.get(t.name)).filter(t=>t!==null)}delete(e){this.db.prepare("DELETE FROM workspaces WHERE name = ?").run(e)}close(){this.db.open&&this.db.close()}},ns=null;function Ki(){let s=Kl();return ns&&ns.dbPath!==s&&(ns.close(),ns=null),ns??=new ko,ns}function An(s){return Ki().upsert(s)}function Os(s){return Ki().get(s)}function Vi(){return Ki().list()}function Fs(s){Ki().delete(s)}function Vl(s){return An({name:s.name,dbPath:s.dbPath,repoPaths:s.repoPaths,repoSetHash:gh(s.repoPaths),managedKind:s.managedKind??"unknown",explicitState:"failed",lastError:s.error})}q();Ae();import _h from"better-sqlite3";import To from"crypto";import Ke from"fs";import Sh from"os";import In from"path";var Yl=k.child({module:"fusion-connection"}),Yi=5,wh=1,Ql=["files","exports","imports","configs","schema_migrations"],Co=3,Eh=15e3,Xl=3e4,xh=125;function vh(s){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,s)}function Zl(s){try{return process.kill(s,0),!0}catch{return!1}}function ep(s){return`${s}.lock`}function tp(s){if(!Ke.existsSync(s))return{path:s,exists:!1,pid:null,acquiredAt:null,ageMs:null,ownerAlive:null,stale:!1,malformed:!1};try{let e=Ke.readFileSync(s,"utf8"),t=JSON.parse(e),n=typeof t.pid=="number"&&Number.isFinite(t.pid)?t.pid:null,i=typeof t.acquiredAt=="number"&&Number.isFinite(t.acquiredAt)?t.acquiredAt:null,r=i?Date.now()-i:null,o=n&&n>0?Zl(n):null,a=!!(i&&Date.now()-i>Xl||n&&n>0&&o===!1);return{path:s,exists:!0,pid:n,acquiredAt:i,ageMs:r,ownerAlive:o,stale:a,malformed:!1}}catch{return{path:s,exists:!0,pid:null,acquiredAt:null,ageMs:null,ownerAlive:null,stale:!0,malformed:!0}}}function np(s){return Ke.existsSync(s)?(Ke.rmSync(s,{force:!0}),!0):!1}function kh(s){let e=Date.now();for(Ke.mkdirSync(In.dirname(s),{recursive:!0});Date.now()-e<Eh;)try{let t=Ke.openSync(s,"wx");return Ke.writeFileSync(t,JSON.stringify({pid:process.pid,acquiredAt:Date.now()})),()=>{try{Ke.closeSync(t)}catch{}Ke.rmSync(s,{force:!0})}}catch(t){if((t instanceof Error&&"code"in t?String(t.code):"")!=="EEXIST")throw t;try{let i=Ke.readFileSync(s,"utf8"),r=JSON.parse(i),o=r.acquiredAt??0,a=r.pid??0;if(Date.now()-o>Xl||a>0&&!Zl(a)){Ke.rmSync(s,{force:!0});continue}}catch{Ke.rmSync(s,{force:!0});continue}vh(xh)}throw new Error(`Timed out acquiring workspace lock: ${s}`)}var Qi=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;lockPath;workspaceNameKind="unknown";constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),this.lockPath=`${this.fusionDbPath}.lock`,Yl.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=In.dirname(this.fusionDbPath);Ke.existsSync(t)||Ke.mkdirSync(t,{recursive:!0}),this.fusionDb=new _h(this.fusionDbPath),this.fusionDb.pragma("journal_mode = WAL"),this.fusionDb.pragma("busy_timeout = 5000"),this.initFusionSchema(),this.syncWorkspaceState({nameKind:"unknown",explicitState:"building"});try{this.withMutationLock(()=>{for(let n of e.repoPaths)this.attachRepoUnlocked(n);this.persistWorkspaceState()}),this.syncWorkspaceState()}catch(n){throw this.syncWorkspaceState({explicitState:"failed",lastError:n instanceof Error?n.message:String(n)}),this.closeUnlocked(),n}}getFusionDbPath(e){let t=Sh.homedir(),n=In.join(t,".mcp-liquid-shadow","fused"),i=e.replace(/[^a-zA-Z0-9-_]/g,"_");return In.join(n,`${i}.db`)}initFusionSchema(){this.fusionDb.exec(`
995
895
  CREATE TABLE IF NOT EXISTS fused_repos (
996
896
  alias TEXT PRIMARY KEY,
997
897
  repo_path TEXT NOT NULL UNIQUE,
@@ -1025,64 +925,102 @@ File: ${H.file}`,P=await M(D);if(P){let B=o.intentLogs.findSemanticMatches(P,3,l
1025
925
 
1026
926
  CREATE INDEX IF NOT EXISTS idx_virtual_edges_source ON virtual_edges(source_repo, source_file_path);
1027
927
  CREATE INDEX IF NOT EXISTS idx_virtual_edges_target ON virtual_edges(target_repo, target_file_path);
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=`
1030
- SELECT id, name, file_path, capabilities
1031
- FROM ${r.alias}.exports
1032
- WHERE kind = 'HTTP Route'
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=`
1034
- SELECT file_path, name
1035
- FROM ${r.alias}.event_synapses
1036
- WHERE type = 'api_route' AND direction = 'produce'
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(`
1039
- UNION ALL
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
1042
- FROM ${p.alias}.${e} fts
1043
- JOIN ${p.alias}.${t} c ON fts.rowid = c.id
1044
- WHERE ${p.alias}.${e} MATCH '"${a}"'`).join(`
1045
- UNION ALL
1046
- `)} ORDER BY _fts_rank LIMIT ${r}`}buildCrossRepoImportsQuery(){let e=this.connection.getAttachedRepos();if(e.length<2)throw new Error("Cross-repo analysis requires at least 2 attached repositories");let t=[];for(let n of e)for(let i of e)n.alias!==i.alias&&t.push(`
1047
- SELECT
1048
- '${n.alias}' as source_repo, '${n.repoPath}' as source_repo_path,
1049
- i.file_path as source_file, i.module_specifier, i.imported_symbols,
1050
- '${i.alias}' as target_repo, '${i.repoPath}' as target_repo_path,
1051
- f.path as target_file
1052
- FROM ${n.alias}.imports i
1053
- JOIN ${i.alias}.files f ON i.resolved_path = f.path
1054
- WHERE i.resolved_path IS NOT NULL`);return t.join(`
1055
- UNION ALL
1056
- `)}buildUnionQuery(e,t,n){let i=this.connection.getAttachedRepos();if(i.length===0)throw new Error("No repositories attached");let r=t.join(", "),o=n?` WHERE ${n}`:"";return i.map(a=>`SELECT '${a.alias}' as _repo_alias, '${a.repoPath}' as _repo_path, ${r} FROM ${a.alias}.${e}${o}`).join(`
1057
- UNION ALL
1058
- `)}searchExports(e,t=50){let n=this.buildUnionQuery("exports",["id","name","kind","file_path","signature"],"name LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}searchFiles(e,t=50){let n=this.buildUnionQuery("files",["path","classification","content_hash"],"path LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}getVirtualEdges(e,t){let n="SELECT * FROM virtual_edges WHERE 1=1",i=[];return e&&(n+=" AND source_repo = ?",i.push(e)),t&&(n+=" AND target_repo = ?",i.push(t)),this.connection.prepare(n).all(...i)}addVirtualEdge(e){return this.connection.prepare(`
1059
- INSERT INTO virtual_edges
1060
- (source_repo, source_file_path, source_symbol_id, target_repo, target_file_path, target_symbol_id, relationship, metadata, confidence, updated_at)
1061
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
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+=`
928
+ `),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(wh.toString()),this.fusionDb.prepare("INSERT OR IGNORE INTO fused_metadata (key, value, updated_at) VALUES ('created_at', ?, unixepoch())").run(Date.now().toString())}attachRepo(e){this.withMutationLock(()=>{this.attachRepoUnlocked(e),this.persistWorkspaceState()})}attachRepoUnlocked(e){let t=In.resolve(e);if(this.attachedRepos.has(t))return;if(!Re(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=ye(t),i=n.name;this.validateSchemaCompatibility(n,t);let r=this.getSchemaVersion(n),o=this.generateAlias(t),a=this.buildAttachSql(i,o);try{n.pragma("wal_checkpoint(PASSIVE)")}catch{}for(let c=1;c<=Co;c++)try{this.fusionDb.exec(a);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)
929
+ VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(l){if(this.isLockContentionError(l)&&c<Co){Yl.warn({repoPath:t,attempt:c,maxAttempts:Co},"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){this.withMutationLock(()=>{this.detachRepoUnlocked(e),this.persistWorkspaceState()})}detachRepoUnlocked(e){let t=In.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.withMutationLock(()=>{this.detachRepoUnlocked(e),this.attachRepoUnlocked(e),this.persistWorkspaceState(Date.now())})}refreshAll(){this.withMutationLock(()=>{let e=Array.from(this.attachedRepos.keys());for(let t of e)this.detachRepoUnlocked(t),this.attachRepoUnlocked(t);this.persistWorkspaceState(Date.now())})}validateSchemas(){let e=Array.from(this.attachedRepos.values()).map(t=>{let n=ye(t.repoPath),i=Ql.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=Yi&&i.length===0,missingTables:i}});return{valid:e.every(t=>t.compatible),minVersion:Yi,repos:e}}getAttachedRepos(){return Array.from(this.attachedRepos.values())}prepare(e){return this.fusionDb.prepare(e)}exec(e){this.fusionDb.exec(e)}close(){this.withMutationLock(()=>{this.closeUnlocked()})}closeUnlocked(){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()}recordWorkspaceAccess(e){this.withMutationLock(()=>{e&&(this.workspaceNameKind=e),this.persistWorkspaceState(void 0,void 0,e)})}recordWorkspaceFailure(e){this.withMutationLock(()=>{this.persistWorkspaceState(void 0,void 0,void 0,e),this.syncWorkspaceState({explicitState:"failed",lastError:e})})}generateAlias(e){let t=In.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=To.createHash("sha256").update(e).digest("hex").substring(0,6);return`repo_${t}_${n}`}buildAttachSql(e,t){return`ATTACH DATABASE '${e.replace(/'/g,"''")}' AS ${t}`}recordEdgeScan(e){this.withMutationLock(()=>{this.persistWorkspaceState(void 0,Date.now(),void 0,void 0,e)})}persistWorkspaceState(e,t,n,i,r){let o=Array.from(this.attachedRepos.keys()).sort(),a=To.createHash("sha256").update(o.join(`
930
+ `)).digest("hex").slice(0,12),c=Date.now().toString();this.setMetadata("last_accessed_at",c),this.setMetadata("repo_paths_json",JSON.stringify(o)),this.setMetadata("repo_count",o.length.toString()),this.setMetadata("repo_set_hash",a),n&&this.setMetadata("workspace_name_kind",n),e&&this.setMetadata("last_fused_at",e.toString()),t&&this.setMetadata("last_edge_scan_at",t.toString()),i?this.setMetadata("last_error",i):this.fusionDb.prepare("DELETE FROM fused_metadata WHERE key = 'last_error'").run(),this.syncWorkspaceState({nameKind:n,lastError:i??null,lastAccessedAt:Number(c),lastFusedAt:e,lastEdgeScanAt:t,edgeCounts:r})}setMetadata(e,t){this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES (?, ?, unixepoch())").run(e,t)}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<Yi)throw new Error(`Schema version mismatch for ${t}. Expected >= ${Yi}, got ${n}.`);let i=Ql.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}withMutationLock(e){let t=kh(this.lockPath);try{return e()}finally{t()}}getEdgeCounts(){let e=this.fusionDb.prepare("SELECT relationship, COUNT(*) as count FROM virtual_edges GROUP BY relationship").all();return Object.fromEntries(e.map(t=>[t.relationship,t.count]))}syncWorkspaceState(e){let t=Array.from(this.attachedRepos.keys()).sort(),n=To.createHash("sha256").update(t.join(`
931
+ `)).digest("hex").slice(0,12),i=e?.edgeCounts??this.getEdgeCounts(),r=Object.values(i).reduce((o,a)=>o+a,0);An({name:this.name,dbPath:this.fusionDbPath,repoPaths:t,repoSetHash:n,managedKind:e?.nameKind??this.workspaceNameKind,explicitState:e?.explicitState,lastError:e?.lastError??null,lastAccessedAt:e?.lastAccessedAt,lastFusedAt:e?.lastFusedAt,lastEdgeScanAt:e?.lastEdgeScanAt,virtualEdgesCount:r,edgeCounts:i,repoSnapshots:jt(t)})}};var sp=k.child({module:"fused-index"});function Ch(s){return s.replace(/[^a-zA-Z0-9-_]/g,"_")}function Rt(s){let e=s.map(r=>is.resolve(r)).sort(),t=e.map(r=>is.basename(r).replace(/[^a-zA-Z0-9-_]/g,"_").toLowerCase()).filter(Boolean).slice(0,3).join("-"),n=rp.createHash("sha256").update(e.join(`
932
+ `)).digest("hex").slice(0,10);return`workspace-${(t||"workspace").slice(0,48)}-${n}`}function Ie(s){let e=Th.homedir(),t=is.join(e,".mcp-liquid-shadow","fused");return is.join(t,`${Ch(s)}.db`)}function Xi(s){return s.map(e=>is.resolve(e)).sort()}function Zi(s){return rp.createHash("sha256").update(Xi(s).join(`
933
+ `)).digest("hex").slice(0,12)}function ip(s){return/^workspace-\d+$/.test(s)}function op(s){Ah(s);let e=Ie(s);for(let t of[e,`${e}-wal`,`${e}-shm`])zt.rmSync(t,{force:!0});Fs(s)}function er(s){let e=Ie(s),t=[e,`${e}-wal`,`${e}-shm`].filter(n=>zt.existsSync(n));return op(s),{name:s,dbPath:e,removedFiles:t}}var Ao=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Qi(e),this.service=new qi(this.connection)}attachRepo(e){this.connection.attachRepo(e)}detachRepo(e){this.connection.detachRepo(e)}refreshRepo(e){this.connection.refreshRepo(e)}getAttachedRepos(){return this.connection.getAttachedRepos()}checkHealth(){return this.connection.checkHealth()}recordWorkspaceAccess(e){this.connection.recordWorkspaceAccess(e)}recordWorkspaceFailure(e){this.connection.recordWorkspaceFailure(e)}close(){this.connection.close(),sp.info({name:this.configName},"Fused index closed")}getStatus(){let e=this.service.executeRawQuery("SELECT relationship, COUNT(*) as count FROM virtual_edges GROUP BY relationship"),t=Object.fromEntries(e.map(n=>[n.relationship,n.count]));return{name:this.connection.nameValue,path:this.connection.dbPath,attachedRepos:this.connection.getAttachedRepos().length,repos:this.connection.getAttachedRepos(),virtualEdgesCount:Object.values(t).reduce((n,i)=>n+i,0),edgeCounts:t}}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)}clearVirtualEdges(e){return this.service.clearVirtualEdges(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 sp.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},ss=new Map;function Ws(s){let e=ss.get(s.name),t=Ie(s.name),n=Zi(s.repoPaths);if(e){if(e.dbPath===t&&e.repoSetHash===n)return e.manager.recordWorkspaceAccess(),e.manager;e.manager.close(),ss.delete(s.name)}let i=new Ao(s);return i.recordWorkspaceAccess(),ss.set(s.name,{manager:i,dbPath:t,repoSetHash:n}),i}function Ah(s){let e=ss.get(s);e&&(e.manager.close(),ss.delete(s))}function Ih(){return Array.from(ss.keys())}function Pn(){let s=new Set([...Ih(),...Vi().map(t=>t.name)]),e=is.dirname(Ie("workspace"));if(!zt.existsSync(e))return Array.from(s).sort();for(let t of zt.readdirSync(e,{withFileTypes:!0}))!t.isFile()||!t.name.endsWith(".db")||t.name!=="registry.db"&&s.add(t.name.slice(0,-3));return Array.from(s).sort()}function Io(s){let e=Ie(s);if(!zt.existsSync(e))return null;let t=null;try{t=new Rh(e,{readonly:!0});let n=t.prepare("SELECT key, value FROM fused_metadata").all(),i=new Map(n.map(g=>[g.key,g.value])),r=t.prepare("SELECT repo_path FROM fused_repos ORDER BY repo_path ASC").all(),o=t.prepare("SELECT COUNT(*) as count FROM virtual_edges").get(),a=t.prepare("SELECT relationship, COUNT(*) as count FROM virtual_edges GROUP BY relationship").all(),c=i.get("repo_paths_json"),l=Xi(c?JSON.parse(c):r.map(g=>g.repo_path)),d=jt(l),p=l.filter(g=>!zt.existsSync(g)),u=l.filter(g=>zt.existsSync(g)&&!Re(g)),m=d.filter(g=>g.hasIndexDrift).map(g=>g.repoPath),f=[];p.length>0&&f.push(`missing:${p.length}`),u.length>0&&f.push(`unindexed:${u.length}`),m.length>0&&f.push(`stale:${m.length}`);let h=i.get("last_error")??null;h&&f.push(h);let y=Object.fromEntries(a.map(g=>[g.relationship,g.count])),b=p.length>0||u.length>0?"degraded":m.length>0?"stale":h?"failed":"ready";return{name:s,path:e,repoPaths:l,repoSetHash:i.get("repo_set_hash")??Zi(l),attachedRepos:l.length,virtualEdgesCount:o?.count??0,createdAt:Number(i.get("created_at")??"")||null,lastAccessedAt:Number(i.get("last_accessed_at")??"")||null,managedKind:i.get("workspace_name_kind")??"unknown",healthy:b==="ready",missingRepoPaths:p,unindexedRepoPaths:u,staleRepoPaths:m,state:b,repoSnapshots:d,dbExists:!0,lastFusedAt:Number(i.get("last_fused_at")??"")||null,lastEdgeScanAt:Number(i.get("last_edge_scan_at")??"")||null,lastError:h,edgeCounts:y,issues:f}}catch(n){return{name:s,path:e,repoPaths:[],repoSetHash:Zi([]),attachedRepos:0,virtualEdgesCount:0,createdAt:null,lastAccessedAt:null,managedKind:"unknown",healthy:!1,missingRepoPaths:[],unindexedRepoPaths:[],staleRepoPaths:[],state:"failed",repoSnapshots:[],dbExists:!0,lastFusedAt:null,lastEdgeScanAt:null,lastError:n instanceof Error?n.message:String(n),edgeCounts:{},issues:[n instanceof Error?n.message:String(n)]}}finally{t?.close()}}function Ph(s,e){let t=Os(s);if(!e&&!t)return null;!t&&e&&An({name:s,dbPath:e.path,repoPaths:e.repoPaths,repoSetHash:e.repoSetHash,managedKind:e.managedKind,explicitState:e.state,lastError:e.lastError,lastAccessedAt:e.lastAccessedAt??void 0,lastFusedAt:e.lastFusedAt??void 0,lastEdgeScanAt:e.lastEdgeScanAt??void 0,virtualEdgesCount:e.virtualEdgesCount,edgeCounts:e.edgeCounts,repoSnapshots:e.repoSnapshots});let n=Os(s);if(!n&&e)return e;let i=Xi(n?.repoPaths.length?n.repoPaths:e?.repoPaths??[]),r=jt(i),o=r.filter(m=>!m.exists).map(m=>m.repoPath),a=r.filter(m=>m.exists&&!m.indexed).map(m=>m.repoPath),c=r.filter(m=>m.hasIndexDrift).map(m=>m.repoPath),l=[...new Set([...e?.issues??[],...o.map(()=>`missing:${o.length}`),...a.map(()=>`unindexed:${a.length}`),...c.map(()=>`stale:${c.length}`),...n?.lastError?[n.lastError]:[],...e||zt.existsSync(Ie(s))?[]:["missing_db"]].filter(Boolean))],d=n?.edgeCounts&&Object.keys(n.edgeCounts).length>0?n.edgeCounts:e?.edgeCounts??{},p=n?.virtualEdgesCount??e?.virtualEdgesCount??Object.values(d).reduce((m,f)=>m+f,0),u=o.length>0||a.length>0?"degraded":c.length>0?"stale":n?.lastError??e?.lastError?"failed":n?.state==="building"?"building":"ready";return{name:s,path:n?.dbPath??e?.path??Ie(s),repoPaths:i,repoSetHash:n?.repoSetHash??e?.repoSetHash??Zi(i),attachedRepos:i.length,virtualEdgesCount:p,createdAt:n?.createdAt??e?.createdAt??null,lastAccessedAt:n?.lastAccessedAt??e?.lastAccessedAt??null,managedKind:n?.managedKind??e?.managedKind??"unknown",healthy:u==="ready",missingRepoPaths:o,unindexedRepoPaths:a,staleRepoPaths:c,state:u,repoSnapshots:r,dbExists:zt.existsSync(n?.dbPath??Ie(s)),lastFusedAt:n?.lastFusedAt??e?.lastFusedAt??null,lastEdgeScanAt:n?.lastEdgeScanAt??e?.lastEdgeScanAt??null,lastError:n?.lastError??e?.lastError??null,edgeCounts:d,issues:l}}function Lh(s){return Ph(s,Io(s))}function Po(){return Pn().map(s=>Lh(s)).filter(s=>s!==null).sort((s,e)=>(e.lastAccessedAt??0)-(s.lastAccessedAt??0))}function tr(){let s=Po(),e=new Set,t=[],n=new Map,i=new Set(s.map(r=>r.name));for(let r of s){if(r.repoPaths.length===0)continue;let o=Rt(r.repoPaths);n.set(r.repoSetHash,o)}for(let r of s){if(!r.dbExists){Fs(r.name);continue}let o=n.get(r.repoSetHash),a=!!o&&i.has(o)&&o&&r.name!==o&&(ip(r.name)||r.managedKind==="auto"&&r.name.startsWith("workspace-")),c=r.missingRepoPaths.length===r.repoPaths.length&&(r.managedKind==="auto"||ip(r.name));if(!!o&&o!==r.name&&r.managedKind==="custom"){t.push({name:r.name,reason:`custom_duplicate_of:${o}`});continue}if(!a&&!c){r.state==="stale"&&t.push({name:r.name,reason:"stale_workspace"});continue}op(r.name),e.add(r.name)}return{pruned:Array.from(e).sort(),retained:t}}import Nh from"crypto";import Mh from"fs";import $h from"path";q();var Dh=k.child({module:"workspace-lifecycle"});function Oh(s){return/^workspace-\d+$/.test(s)}function cn(s){return[...new Set((s??[]).map(e=>$h.resolve(e)))].sort()}function Ln(s){return s.length===0?null:Nh.createHash("sha256").update(cn(s).join(`
934
+ `)).digest("hex").slice(0,12)}function cp(){return Array.from(new Set([...Pn(),...Vi().map(s=>s.name)])).sort()}function rs(s){return{name:s,registry:Os(s),db:Io(s)}}function zs(s){return cn(s.registry?.repoPaths.length?s.registry.repoPaths:s.db?.repoPaths??[])}function Lo(s){return s.registry?.repoSetHash??s.db?.repoSetHash??Ln(zs(s))}function Fh(s){return s.registry?.dbPath??s.db?.path??Ie(s.name)}function js(s){let e=zs(s),t=e.length>0?jt(e):[],n=s.registry?.lastError??s.db?.lastError??null,i="missing";return(s.registry||s.db)&&(s.registry?.state==="building"&&!s.db?i="building":s.db?t.some(r=>!r.exists||!r.indexed)?i="degraded":n?i="failed":t.some(r=>r.hasIndexDrift)?i="stale":i="ready":i="failed"),{state:i,lastAccessedAt:s.registry?.lastAccessedAt??s.db?.lastAccessedAt??null,managedKind:s.registry?.managedKind??s.db?.managedKind??"unknown"}}function Wh(s,e){if(s.length===0)return null;let t=n=>n==="ready"?0:n==="stale"?1:n==="degraded"?2:n==="building"?3:n==="failed"?4:5;return[...s].sort((n,i)=>{if(e&&n.name===e&&i.name!==e)return-1;if(e&&i.name===e&&n.name!==e)return 1;let r=js(n).state,o=js(i).state,a=t(r),c=t(o);if(a!==c)return a-c;let l=js(n).lastAccessedAt??0;return(js(i).lastAccessedAt??0)-l})[0]??null}function lt(s,e){s.some(t=>t.code===e.code&&t.repoPath===e.repoPath)||s.push(e)}function jh(s,e){let t=s==="ready"?.96:s==="stale"?.72:s==="degraded"?.48:s==="building"?.38:s==="failed"?.18:.05,n=e.reduce((i,r)=>r.severity==="error"?i+.08:r.severity==="warning"?i+.03:i,0);return Math.max(.01,Math.min(.99,Number((t-n).toFixed(2))))}function zh(s){let e=ln({name:s});return{name:s,state:e.state,confidence:e.confidence,lastEdgeScanAt:e.freshness.lastEdgeScanAt,lastFusedAt:e.freshness.lastFusedAt,issues:e.causes.map(t=>t.code)}}function Hh(s,e,t,n,i){let r=e.map(o=>o.code);if(s==="ready")return{type:"use",safe:!0,reasonCodes:r};if(s==="building"&&t.exists&&!t.stale)return{type:"wait",safe:!0,reasonCodes:r};if(s==="missing"){let o=n.some(c=>!c.exists),a=n.some(c=>c.exists&&!c.indexed);return{type:o?"restore_repos":a?"index_repos":i?"ensure":"none",safe:!(o||a),reasonCodes:r}}return t.exists&&t.stale?{type:"repair",safe:!0,reasonCodes:r}:e.some(o=>["registry_missing_db","db_missing_registry","workspace_last_error","db_read_failed"].includes(o.code))?{type:e.some(o=>o.code==="db_missing_registry")?"repair":"rebuild",safe:!0,reasonCodes:r}:n.some(o=>!o.exists)?{type:"restore_repos",safe:!1,reasonCodes:r}:n.some(o=>o.exists&&!o.indexed)?{type:"index_repos",safe:!0,reasonCodes:r}:s==="stale"||e.some(o=>["repo_index_drift","edge_scan_missing","edge_scan_outdated"].includes(o.code))?{type:"refresh",safe:!0,reasonCodes:r}:{type:s==="failed"?"repair":"none",safe:s!=="failed",reasonCodes:r}}function ln(s){let e=cn(s.repoPaths),t=Ln(e),n=e.length>0?Rt(e):null,i=s.name?.trim()||null,r=i?rs(i):null,o=r?zs(r):[],a=e.length>0?cp().map(P=>rs(P)).filter(P=>Lo(P)===t):r?[r]:[],c=r??Wh(a,i??n),l=c&&i?"exact_name":c&&n&&c.name===n?"repo_set_canonical":c?"repo_set_existing":"missing",d=e.length>0?e:c?zs(c):[],p=d.length>0?jt(d):[],u=c?Fh(c):i?Ie(i):n?Ie(n):null,m=tp(u?ep(u):""),f=c?.registry??null,h=c?.db??null,y=[];if(!c)lt(y,{code:"workspace_missing",scope:"workspace",severity:"warning",message:"No persisted workspace matched the requested name or repo set."});else if(!f&&h&&lt(y,{code:"db_missing_registry",scope:"registry",severity:"warning",message:"Fused DB exists but registry entry is missing."}),f&&!h&&lt(y,{code:"registry_missing_db",scope:"db",severity:"error",message:"Registry entry exists but fused DB is missing or unreadable."}),f&&h){let P=cn(h.repoPaths),C=cn(f.repoPaths);P.join(`
935
+ `)!==C.join(`
936
+ `)&&lt(y,{code:"registry_db_repo_mismatch",scope:"workspace",severity:"warning",message:"Registry repo set does not match fused DB metadata.",details:{registryRepoPaths:C,dbRepoPaths:P}})}if(i&&e.length>0&&o.length>0){let P=Ln(e),C=Ln(o);P!==C&&lt(y,{code:"requested_name_repo_mismatch",scope:"workspace",severity:"error",message:"Requested workspace name resolves to a different repo set than the input repoPaths.",details:{requestedRepoPaths:e,resolvedRepoPaths:o}})}m.exists&&lt(y,{code:m.stale?"lock_stale":"lock_present",scope:"lock",severity:m.stale?"warning":"info",message:m.stale?"Workspace lock exists but appears stale.":"Workspace lock is currently held.",details:{pid:m.pid,acquiredAt:m.acquiredAt,ownerAlive:m.ownerAlive}});for(let P of p)P.exists?P.indexed?P.hasIndexDrift&&lt(y,{code:"repo_index_drift",scope:"repo",severity:"warning",message:"Workspace repo index is stale relative to git state.",repoPath:P.repoPath,details:{driftReason:P.driftReason}}):lt(y,{code:"repo_unindexed",scope:"repo",severity:"warning",message:"Workspace repo is present but not indexed.",repoPath:P.repoPath}):lt(y,{code:"repo_missing",scope:"repo",severity:"error",message:"Workspace repo path is missing on disk.",repoPath:P.repoPath});let b=f?.lastEdgeScanAt??h?.lastEdgeScanAt??null,g=f?.lastFusedAt??h?.lastFusedAt??null,w=d.length>1&&(b===null||p.some(P=>typeof P.lastIndexedAt=="number"&&P.lastIndexedAt>b));c&&d.length>1&&b===null?lt(y,{code:"edge_scan_missing",scope:"edges",severity:"warning",message:"Workspace has no recorded cross-repo edge scan."}):w&&lt(y,{code:"edge_scan_outdated",scope:"edges",severity:"warning",message:"Workspace edge scan predates repo index freshness."});let A=f?.lastError??h?.lastError??null;A&&lt(y,{code:h?"workspace_last_error":"db_read_failed",scope:h?"workspace":"db",severity:"error",message:A});let x="missing";c&&(m.exists&&!m.stale&&(f?.state==="building"||!h&&f)?x="building":h?f?p.some(P=>!P.exists||!P.indexed)?x="degraded":A||y.some(P=>["requested_name_repo_mismatch","db_read_failed"].includes(P.code))?x="failed":m.stale||p.some(P=>P.hasIndexDrift)||w||y.some(P=>P.code==="registry_db_repo_mismatch")?x="stale":x="ready":x="stale":x="failed");let E=jh(x,y),I=Hh(x,y,m,p,d.length>0),N=a.map(P=>{let C=js(P);return{name:P.name,managedKind:C.managedKind,state:C.state,lastAccessedAt:C.lastAccessedAt}}).sort((P,C)=>(C.lastAccessedAt??0)-(P.lastAccessedAt??0));return{query:{name:i,repoPaths:e,repoSetHash:t},workspace:{name:c?.name??null,canonicalName:n,selectedBy:l,path:u,managedKind:f?.managedKind??h?.managedKind??null,repoPaths:d,repoSetHash:Ln(d)??Lo(c??rs(n??i??"workspace")),relatedWorkspaces:N},state:x,causes:y,registry:{present:!!f,state:f?.state??null,lastError:f?.lastError??null,updatedAt:f?.updatedAt??null,lastAccessedAt:f?.lastAccessedAt??null,lastFusedAt:f?.lastFusedAt??null,lastEdgeScanAt:f?.lastEdgeScanAt??null},db:{present:!!h,path:u,readable:!!h,lastError:h?.lastError??null,attachedRepos:h?.attachedRepos??d.length},lock:m,repoHealth:{total:p.length,missing:p.filter(P=>!P.exists).length,unindexed:p.filter(P=>P.exists&&!P.indexed).length,stale:p.filter(P=>P.hasIndexDrift).length,snapshots:p},edges:{virtualEdgesCount:f?.virtualEdgesCount??h?.virtualEdgesCount??Object.values(f?.edgeCounts??h?.edgeCounts??{}).reduce((P,C)=>P+C,0),edgeCounts:f?.edgeCounts??h?.edgeCounts??{}},freshness:{lastAccessedAt:f?.lastAccessedAt??h?.lastAccessedAt??null,lastFusedAt:g,lastEdgeScanAt:b,edgeScanAgeMs:typeof b=="number"?Date.now()-b:null,isEdgeScanStale:w},confidence:E,recommendedAction:I}}async function ap(s,e,t){for(let n of s){if(!Mh.existsSync(n)){t?.push({action:"ensure_repo_index",repoPath:n,reason:"repo_missing"});continue}await Q(n),e.push({action:"ensure_repo_index",repoPath:n,result:"ok"})}}async function No(s){let e=ln({name:s.name,repoPaths:s.repoPaths}),t=[],n=[],i=cn(s.repoPaths??e.workspace.repoPaths),r=e.workspace.name??s.name??(e.workspace.canonicalName&&i.length>0?e.workspace.canonicalName:null),o=s.rebuildPolicy??"auto",a=i.length>0?Rt(i):null,c=s.nameKind??(r&&a&&r===a?"auto":s.name?"custom":"auto");if(!r)return{workspace:e.workspace,initialState:e.state,finalState:e.state,issuesFound:e.causes,repairsApplied:t,repairsSkipped:[{action:"resolve_workspace",reason:"workspace_identity_unresolved"}],confidence:e.confidence,status:e};e.lock.exists&&e.lock.stale&&(np(e.lock.path),t.push({action:"clear_stale_lock",path:e.lock.path}));let l=rs(r);!l.registry&&l.db&&(An({name:r,dbPath:l.db.path,repoPaths:l.db.repoPaths,repoSetHash:l.db.repoSetHash,managedKind:l.db.managedKind,explicitState:l.db.state,lastError:l.db.lastError,lastAccessedAt:l.db.lastAccessedAt??void 0,lastFusedAt:l.db.lastFusedAt??void 0,lastEdgeScanAt:l.db.lastEdgeScanAt??void 0,virtualEdgesCount:l.db.virtualEdgesCount,edgeCounts:l.db.edgeCounts,repoSnapshots:l.db.repoSnapshots}),t.push({action:"adopt_db_into_registry",workspace:r}));let d=ln({name:r,repoPaths:i.length>0?i:void 0});d.registry.present&&!d.db.present&&i.length>0&&o!=="never"&&(er(r),t.push({action:"delete_missing_db_workspace",workspace:r}));try{if(i.length>0){await ap(i,t,n);let u=Ws({name:r,repoPaths:i});u.recordWorkspaceAccess(c),u.refreshAll();let m=u.scanEdges();t.push({action:"refresh_workspace",workspace:r,scan:m})}else n.push({action:"refresh_workspace",reason:"repo_paths_unavailable"})}catch(u){if(o==="never"||i.length===0)n.push({action:"rebuild_workspace",reason:u instanceof Error?u.message:String(u)});else{Dh.warn({error:u,workspaceName:r,repoPaths:i},"Workspace refresh failed; attempting rebuild"),er(r),t.push({action:"delete_corrupt_workspace",workspace:r}),await ap(i,t,n);let m=Ws({name:r,repoPaths:i});m.recordWorkspaceAccess(c),m.refreshAll();let f=m.scanEdges();t.push({action:"rebuild_workspace",workspace:r,scan:f})}}let p=ln({name:r,repoPaths:i.length>0?i:void 0});return{workspace:p.workspace,initialState:e.state,finalState:p.state,issuesFound:e.causes,repairsApplied:t,repairsSkipped:n,confidence:p.confidence,status:p}}async function lp(s){let e=cn(s.repoPaths),t=ln({name:s.name,repoPaths:e}),n=s.repairPolicy??"safe",i=s.rebuildPolicy??"auto",r=[],a=(!s.name&&t.workspace.name&&t.workspace.repoPaths.length>0&&t.state==="ready"?t.workspace.name:null)??s.name??t.workspace.name??Rt(e);if(t.state==="ready"&&t.workspace.name===a)return{workspace:t.workspace,initialState:t.state,finalState:t.state,reused:!0,refreshed:!1,repaired:!1,rebuilt:!1,actionsTaken:[{action:"reuse_workspace",workspace:a}],confidence:t.confidence,freshness:t.freshness,status:t};if(n==="off")return{workspace:t.workspace,initialState:t.state,finalState:t.state,reused:!1,refreshed:!1,repaired:!1,rebuilt:!1,actionsTaken:[{action:"repair_skipped",reason:"repair_policy_off"}],confidence:t.confidence,freshness:t.freshness,status:t};let c=await No({name:a,repoPaths:e,rebuildPolicy:i,nameKind:s.name?"custom":"auto"});return r.push(...c.repairsApplied),r.push(...c.repairsSkipped.map(l=>({...l,applied:!1}))),{workspace:c.workspace,initialState:t.state,finalState:c.finalState,reused:!1,refreshed:c.repairsApplied.some(l=>l.action==="refresh_workspace"),repaired:c.repairsApplied.length>0,rebuilt:c.repairsApplied.some(l=>l.action==="rebuild_workspace"||l.action==="delete_corrupt_workspace"),actionsTaken:r,confidence:c.confidence,freshness:c.status.freshness,status:c.status}}function pp(s={}){let e=cn(s.repoPaths),t=Ln(e),n=s.apply===!0,i=Math.max(1,s.olderThanDays??30)*24*60*60*1e3,r=s.name?[s.name]:cp().filter(d=>{if(!t)return!0;let p=rs(d);return Lo(p)===t}),o=[],a=[],c=[],l=new Map;for(let d of r){let p=rs(d),u=zs(p),m=Ln(u);m&&u.length>0&&l.set(m,Rt(u))}for(let d of r){let p=ln({name:d}),u=p.workspace.managedKind,m=p.workspace.repoPaths.length>0?Rt(p.workspace.repoPaths):p.workspace.canonicalName,f=p.causes.map(b=>b.code),h=p.freshness.lastAccessedAt,y=typeof h=="number"?Date.now()-h:Number.POSITIVE_INFINITY;if(p.registry.present&&!p.db.present){o.push({name:d,classification:"orphaned_registry",safety:"safe",reasons:f.length>0?f:["registry_missing_db"],state:p.state,managedKind:u,repoPaths:p.workspace.repoPaths});continue}if(!p.registry.present&&p.db.present){a.push({name:d,reasons:f.length>0?f:["db_missing_registry"],safety:"caution",state:p.state}),o.push({name:d,classification:"repairable_orphan_db",safety:"caution",reasons:f.length>0?f:["db_missing_registry"],state:p.state,managedKind:u,repoPaths:p.workspace.repoPaths});continue}if(m&&d!==m&&(u==="auto"||u==="unknown"||Oh(d))){o.push({name:d,classification:"safe_auto_duplicate",safety:"safe",reasons:[...f,`duplicate_of:${m}`],state:p.state,managedKind:u,repoPaths:p.workspace.repoPaths});continue}if((u==="auto"||u==="unknown")&&y>=i&&p.state!=="ready"){o.push({name:d,classification:"old_unused_auto",safety:"caution",reasons:[...f,`unused_for_ms:${y}`],state:p.state,managedKind:u,repoPaths:p.workspace.repoPaths}),a.push({name:d,reasons:[...f,`unused_for_ms:${y}`],safety:"caution",state:p.state});continue}if(u==="custom"&&!s.includeCustom){a.push({name:d,reasons:[...f,"custom_workspace_retained"],safety:"retain",state:p.state}),o.push({name:d,classification:"ambiguous_custom",safety:"retain",reasons:[...f,"custom_workspace_retained"],state:p.state,managedKind:u,repoPaths:p.workspace.repoPaths});continue}}if(n){for(let d of o)if(d.safety==="safe"){if(d.classification==="orphaned_registry"){Fs(d.name),c.push({action:"remove_registry_entry",name:d.name});continue}er(d.name),c.push({action:"delete_workspace",name:d.name})}}return{dryRun:!n,candidates:o,actionsApplied:c,retained:a}}function nr(s){return zh(s)}bt();import{Visitor as Bh}from"@swc/core/Visitor.js";var os=class extends Bh{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(d=>d.key?.type==="Identifier"&&(d.key.value==="action"||d.key.value==="type")||d.key?.type==="StringLiteral"&&(d.key.value==="action"||d.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})}}}},pn=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 d=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),p=d?d[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:p})}}}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 d=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),p=d?d[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:p})}}}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 as=class{constructor(e){this.repoPath=e}async analyze(e,t={}){let{filePath:n,depth:i=3,limit:r=50,offset:o=0}=t,a=L.getInstance(this.repoPath),c=new an(this.repoPath),l=n?a.exports.findByNameAndFile(e,n):a.exports.findByNameGlobal(e);if(l.length===0)return[];let d=[];for(let p of l){let u=a.imports.findImpactDependents(p.file_path,`%${e}%`,i),m=[],f=new Set;for(let E of u){let I=Mn.relative(this.repoPath,E.consumer_path);if(f.has(I))continue;let N=`Imports ${E.imported_symbols}`,P=await this.verifySymbolUsage(E.consumer_path,p.name);P?N+=" (\u2705 Verified Call)":N+=" (\u26A0\uFE0F Potential Import - Usage not statically detected)",f.add(I),m.push({type:"IMPORT",file:I,depth:E.depth,details:N,verified:P})}let h=a.exports.findRoutesByCapability(e);p.kind==="HTTP Route"&&h.push({name:p.name,file_path:p.file_path,signature:p.signature});for(let E of h){let N=E.name.split("/").filter(C=>C.length>3&&!C.includes("{")&&!C.includes("$")&&!C.includes("<")).sort((C,W)=>W.length-C.length)[0];if(!N||["admin","api","user","users","update","create","delete","list","index","show","store"].includes(N.toLowerCase()))continue;let P=a.files.findContentByToken(N,10);for(let C of P){let W=Mn.relative(this.repoPath,C);!f.has(W)&&C!==p.file_path&&(f.add(W),m.push({type:"API_USAGE",file:W,depth:2,details:`Likely calls route ${E.name} (matched token '${N}')`,verified:!1}))}}let y=a.files.findContentByToken(e,20);for(let E of y){let I=Mn.relative(this.repoPath,E);!f.has(I)&&E!==p.file_path&&(f.add(I),m.push({type:"POTENTIAL_USAGE",file:I,depth:2,details:`Contains keyword '${e}' (Dynamic/Implicit usage)`,verified:!1}))}p.kind==="HTTP Route"&&await this.addCrossRepoImpact(m,f,p),m.sort((E,I)=>E.verified&&!I.verified?-1:!E.verified&&I.verified?1:E.depth!==I.depth?E.depth-I.depth:E.file.localeCompare(I.file));let b=m.length,g=m.slice(o,o+r),w=o+r<b,A=c.getMappedTestsForSymbol(p.file_path,p.name,12),x=this.calculateRiskScore(p,b,m);d.push({symbol:e,definedIn:Mn.relative(this.repoPath,p.file_path),riskScore:x,impact:g,pagination:{total:b,offset:o,limit:r,hasMore:w},verification:{coverageHint:A.length>0?"covered":"uncovered",mappedTestCount:A.length,mappedTests:A.map(E=>E.file)}})}return d}async verifySymbolUsage(e,t){try{if(!Mo.existsSync(e))return!1;let n=Mo.readFileSync(e,"utf8"),i=Mn.extname(e).toLowerCase(),r=new Set;if(i===".ts"||i===".tsx"||i===".js"||i===".jsx"){let o=new os;try{let a=await Ts(n,{syntax:"typescript",tsx:e.endsWith(".tsx"),target:"es2020"});o.visitModule(a),r=o.calls}catch{return n.includes(t)}}else{let o=new pn;o.visit(n,i),r=o.calls}if(r.has(t))return!0;for(let o of r){if(o===t)return!0;let a=o.split(/(?:\.|->|::)+/),c=a[a.length-1],l=t.split(/(?:\.|->|::)+/),d=l[l.length-1];if(c===d)return!0}return!1}catch{return!1}}async addCrossRepoImpact(e,t,n){try{let i=Pn();for(let r of i)try{let o=Ie(r),a=nr(r);if(!Mo.existsSync(o))continue;let c=(await import("better-sqlite3")).default,l=new c(o),d=l.prepare("SELECT source_repo, source_file_path, relationship, metadata FROM virtual_edges WHERE target_repo = ? AND target_file_path = ?").all(this.repoPath,n.file_path);l.close();for(let p of d){let u=Mn.relative(p.source_repo,p.source_file_path),m=`${p.source_repo}:${u}`;if(!t.has(m)){t.add(m);let h={api_call:"CROSS_REPO_API_CALL",import_reference:"CROSS_REPO_IMPORT",pubsub_flow:"CROSS_REPO_PUBSUB",socket_flow:"CROSS_REPO_SOCKET"}[p.relationship]??"CROSS_REPO_EDGE";e.push({type:h,file:m,depth:1,details:`Cross-repo ${p.relationship} from ${Mn.basename(p.source_repo)}`,verified:!0,workspace:a})}}}catch{}}catch{}}calculateRiskScore(e,t,n){let a=(new be(this.repoPath).getSnapshot().gravity?.hotspots||[]).find(u=>u.filePath===e.file_path&&u.symbol===e.name)?.gravity||0,c=n.filter(u=>u.type.startsWith("CROSS_REPO_")).length,l=a/50+t/15+c*2,d="LOW",p="Peripheral symbol with limited usage.";return l>=8?(d="CRITICAL",p=`Core architectural pillar (Gravity: ${a.toFixed(0)}). Modification will destabilize ${t} dependents.`):l>=4?(d="HIGH",p=`High-gravity symbol with significant blast radius (${t} files).`):l>=1.5&&(d="MEDIUM",p="Standard library symbol with moderate dependency chain."),{score:Math.min(10,Math.round(l*10)/10),level:d,rationale:p}}};async function up(s){let{repoPath:e}=de(s),{baseCommit:t,headCommit:n,staged:i=!0,includeUntracked:r=!0,maxSymbols:o=20,impactDepth:a=2,impactLimit:c=12}=s;await Q(e);let l=new Bi(e),d=l.collectFileChanges({baseCommit:t,headCommit:n,staged:i,includeUntracked:r}),p=l.mapChangesToSymbols(d,o);if(d.length===0)return{content:[{type:"text",text:JSON.stringify({summary:"No diff detected.",changes:[]},null,2)}]};let u=new as(e),m=new an(e),f=L.getInstance(e),h=[],y=new Set,b=new Set;for(let w of p){let A=await u.analyze(w.name,{filePath:w.absolutePath,depth:a,limit:c}),x=A.length>0?A[0]:null;for(let N of x?.impact||[])N?.file&&y.add(String(N.file));let E=f.exports.findTypeGraphEdges(w.name,{filePath:w.absolutePath,direction:"both",limit:20}),I=m.getMappedTestsForSymbol(w.absolutePath,w.name,10);for(let N of I)b.add(N.file);h.push({symbol:{name:w.name,kind:w.kind,file:w.file,startLine:w.startLine,endLine:w.endLine,status:w.status,changedRanges:w.changedRanges},impact:x?{riskScore:x.riskScore,blastRadius:x.pagination.total,topImpacted:x.impact.slice(0,8)}:null,typeGraph:{edgeCount:E.length,edges:E.slice(0,10).map(N=>({direction:N.direction,relationship:N.relationship,source:N.source_symbol_name,target:N.target_symbol_name}))},verification:{mappedTestCount:I.length,mappedTests:I.map(N=>({file:N.file,via:N.via,confidence:N.confidence}))}})}let g={changedFiles:d.length,changedSymbols:p.length,impactedFiles:y.size,suggestedTests:b.size};return{content:[{type:"text",text:JSON.stringify({summary:g,diffScope:{staged:i,includeUntracked:r,...t?{baseCommit:t}:{},...n?{headCommit:n}:{}},changes:d.map(w=>({file:w.relativePath,status:w.status,...w.oldRelativePath?{from:w.oldRelativePath}:{},changedRanges:w.ranges})),symbols:h,verification:{suggestedTestFiles:Array.from(b).sort()}},null,2)}]}}V();import $n from"fs";import De from"path";q();var Gh=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"]),qh=new Set(["GET","POST","PUT","DELETE","PATCH"]),Jh=[/\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 Kh(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Us(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function $o(s){let e=Us(s).replace(/:[^/]+/g,"__SEG__").replace(/\{[^}]+\}/g,"__SEG__").replace(/\$[^/]+/g,"__SEG__").replace(/\*/g,"__SEG__"),t=Kh(e).replace(/__SEG__/g,"[^/]+");return new RegExp(`^${t}$`)}function mp(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&&qh.has(t)?t:null}function Vh(s){return s.replace(/<[^>]+>/g," ")}function Yh(s){return Jh.some(e=>e.test(s))}function Qh(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 Xh(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 Us(e)}function Zh(s,e){let t=Qh(s);for(let n of t){let i=Xh(n);if(!i)continue;let r=$o(i),o=e.replace(/\*/g,"test-val");if(r.test(o)||!/[:{*$]/.test(i)&&o.startsWith(`${i}/`))return!0}return!1}function eg(s,e){if(e)try{let i=JSON.parse(e);if(typeof i.path=="string"&&i.path.startsWith("/"))return Us(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 Us(i)}}return null}function tg(s,e){let t=s.toLowerCase();return e.reduce((n,i)=>n+(t.includes(i.toLowerCase())?20:0),0)}function fp(s,e,t){let n=e,i=e.match(/\$\{([^}]+)\}/g);if(i)for(let m of i){let f=m.substring(2,m.length-1),h=s.configs.findEnvValue(f);h&&(n=n.replace(m,h))}let r=n.split("?")[0].split("#")[0];try{r.includes("://")&&(r=new URL(r).pathname)}catch{}r=Us(r);let o=t?.toUpperCase(),a=[],c=!1,l=r.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),d=s.files.findSynapses({type:"api_route",name:l.includes("%")?l:r,direction:"consume",limit:10});for(let m of d)$o(m.name).test(r.replace(/\*/g,"test-val"))&&(a.push({file_path:m.file_path,start_line:m.line_number||0,signature:`[Synapse] ${m.name}`,score:1e3}),c=!0);let p=r.split(/[^a-zA-Z0-9-_]/).filter(m=>m.length>=3&&!Gh.has(m.toLowerCase())&&!/^\d+$/.test(m));if(p.length>0){let h=[...p].sort((b,g)=>g.length-b.length).slice(0,2).flatMap(b=>s.exports.findRoutesByToken(b,20)),y=new Set;for(let b of h){let g=`${b.file_path}:${b.start_line}:${b.name}`;if(y.has(g))continue;y.add(g);let w=b.signature||b.name||"",A=mp(w);if(o&&A&&o!==A)continue;let x=eg(w,b.capabilities);if(o&&!A&&!x)continue;let E=40;if(x){if(!$o(x).test(r.replace(/\*/g,"test-val")))continue;E+=280,c=!0}o&&A&&o===A&&(E+=120,c=!0),E+=tg(`${w} ${x||""}`,p),a.push({file_path:b.file_path,start_line:b.start_line,signature:`[Boundary] ${w}`,capabilities:b.capabilities||void 0,score:E})}}if(a.length<3&&!c){let m=p.map(f=>f.replace(/[^a-zA-Z0-9_]/g,"")).filter(f=>f.length>0).join(" AND ");if(m.length>0){let f=s.content.search(m);for(let h of f){let y=Vh(h.snippet);if(!Yh(y)||!Zh(y,r))continue;let b=mp(y);if(o&&b&&b!==o)continue;let g=0,w=h.file_path.toLowerCase(),A=y.toLowerCase();(w.includes("route")||w.includes("controller"))&&(g+=10),(w.includes("src/api")||w.includes("services/api"))&&(g+=5),(A.includes("addroute")||A.includes("@get"))&&(g+=15),(A.includes("axios.")||A.includes("fetch("))&&(g-=10),(w.includes(".spec.")||w.includes(".test."))&&(g-=20),o&&A.includes(o.toLowerCase())&&(g+=20),g>0&&a.push({file_path:h.file_path,start_line:0,signature:`[FTS Match] ${y.replace(/\n/g," ")}`,score:g})}}}let u=new Map;return a.sort((m,f)=>f.score-m.score).forEach(m=>{u.has(m.file_path)||u.set(m.file_path,m)}),Array.from(u.values()).slice(0,c?2:3)}var Do=7,dn=80,ng=2,sg=4,ig=6,hp=24,rg=3,og=24,ag=new Set(["publish","publishmessage","publishtaskbynameandpayload"]),cg=new Set(["Error","TypeError","RangeError","ReferenceError","SyntaxError","Promise","Map","Set","WeakMap","WeakSet","Date","Array","Object","String","Number","Boolean","RegExp","URL","URLSearchParams","FormData"]),lg=new Set(["error","errors","request","response","result","results","value","values","item","data","payload","message","messages","text","description","name","id","type","status","code","count","test"]),yp=new Set(["req","res","request","response","error","err","event","item","row","data","value","obj","window","document","console","json","math"]),pg=new Set(["length","size","value","values","name","id","type","status","count"]),bp=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 dg(s,e){return De.resolve(s)===De.resolve(e)}function _p(s){if(cg.has(s))return!0;let e=s.trim().toLowerCase();if(!e||e.length<2||/\[|\]|\s/.test(s)||lg.has(e))return!0;let t=s.split(/(?:\.|->|::)+/).filter(Boolean),n=(t.length>0?t[t.length-1]:e).replace(/^\$+/,"");if(pg.has(n.toLowerCase())||bp.has(n))return!0;if(t.length>1){let i=t[0].replace(/^\$+/,"").toLowerCase();if(yp.has(i))return!0}return!1}function Fo(s,e){if(e.has(s))return e.get(s)??null;try{let t=$n.readFileSync(s,"utf8");return e.set(s,t),t}catch{return null}}function Oo(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 ug(s,e,t){if(_p(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 Oo([...i,...t.exports.findTopLevelByNameGlobal(n)]);let o=r[0]?.replace(/^\$+/,"")||"",a=o.toLowerCase(),c=r[r.length-1];if(!c)return i;let l=t.exports.findByNameAndFile(c,e);if(bp.has(c)||yp.has(a))return Oo([...i,...l]);let d=o?t.exports.findMemberCandidates(o,c,e):[],u=o&&!new Set(["this","self","static","parent"]).has(a)&&d.length===0?t.exports.findMemberCandidates(o,c):[];return Oo([...d,...l,...i,...u])}function mg(s){return s<20?Do:s<45?Do-1:Math.max(4,Do-2)}function fg(s,e){let t=s<=2?1:s<=4?.7:.4,n=e<25?1:e<55?.8:.55,i=Math.floor(og*t*n);return Math.max(rg,i)}function hg(s,e){let t=s.split(`
937
+ `),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,d=c.match(/\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/),p=c.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*[^=]/),u=d?.[1]||p?.[1];if(u){n.set(u,l);continue}for(let[m,f]of n.entries()){if(l<=f||!new RegExp(`\\b${Sp(m)}\\b`).test(c))continue;let h=i.get(m)||0;if(h>=2)continue;let y=`${m}:${f}->${l}`;o.has(y)||(r.push({symbol:m,fromLine:f,toLine:l}),o.add(y),i.set(m,h+1))}}return r}function gg(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 yg(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 bg(s,e,t=ig){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 gp(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 Sp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wo(s){let e=s.split(/(?:\.|::|->)+/).filter(Boolean);return e.length>0?e[e.length-1]:s.trim()}function _g(s){return s&&(s.includes("Class")||s.includes("Interface")||s.includes("TypeAlias")||s.includes("Enum"))?"component":"function"}function Sg(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 ir(s,e,t){let n=Wo(e);if(!n)return null;try{let i=t?Fo(s,t):$n.readFileSync(s,"utf8");if(!i)return null;let r=i.split(`
938
+ `),o=Sp(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(d=>d.test(l)))return Sg(r,c)}}catch{return null}return null}function wp(s,e,t,n){try{let i=n?Fo(s,n):$n.readFileSync(s,"utf8");if(!i)return!0;let r=i.split(`
939
+ `);if(e.start<1||e.end<e.start||e.start>r.length||e.end>r.length||!r.slice(e.start-1,e.end).join(`
940
+ `).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=Wo(t);if(l&&!a.includes(l))return!0}return!1}catch{return!0}}function sr(s,e,t,n){if(e){if(!t)return e;if(wp(s,e,t,n)){let i=ir(s,t,n);if(i)return i}return e}}function wg(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 Eg(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=gp(t),c=i.find(l=>!l?.name||typeof l.name!="string"?!1:gp(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 rr(s){let{repoPath:e,filePath:t,symbolName:n}=de(s);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let i=t;await Q(e);let r=L.getInstance(e);if(!$n.existsSync(i))return{isError:!0,content:[{type:"text",text:`File not found: ${i}`}]};let o=new Map,a,c=De.basename(i),l,d=n?"function":"file";if(n){let f=Wo(n),h=Eg(r,i,n);if(h){let y=h;a={start:y.start_line,end:y.end_line},c=y.name,l=y.start_line,d=_g(y.kind)}else{let y=ir(i,n,o);if(y)a=y,l=y.start,c=f||n;else{let b=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}"
941
+ File: ${De.relative(e,i)}
942
+ `+(b.length>0?`Top symbols in file: ${b.join(", ")}`:"No indexed symbols found for this file.")}]}}}if(a&&wp(i,a,n,o)){let y=ir(i,n,o);y&&(k.warn({filePath:i,symbolName:n,start:a.start,end:a.end},"Indexed symbol range appears degenerate; using source-inferred range for flow"),a=y,l=y.start,c===De.basename(i)&&(c=f||n))}if(a){let y=ir(i,n,o);y&&wg(a,y)&&(k.warn({filePath:i,symbolName:n,start:a.start,end:a.end},"Indexed symbol range appears overwide; using source-inferred range for flow"),a=y,l=y.start)}}let p={type:a?d:"file",name:c,path:De.relative(e,i),line:l,children:[]},u=new Set;u.add(i+(n?`:${n}`:""));let m={count:0,truncated:!1,pruned:!1,dataFlowCount:0};return await cs(i,p,e,r,u,1,m,o,a),(m.truncated||m.pruned)&&p.children.push({type:"function",name:"\u26A0\uFE0F Trace Pruned",details:`Adaptive trace limits applied (depth/node budget). Current cap: ${dn} nodes.`,children:[]}),{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}async function cs(s,e,t,n,i,r,o,a,c){let l=mg(o.count);if(r>l){o.pruned=!0;return}if(o.count>=dn){o.truncated=!0;return}try{let d=Fo(s,a);if(!d)throw new Error(`Unable to read source: ${s}`);let p=d,u=De.extname(s).toLowerCase(),f=(p.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
943
+ `);c&&(p=p.split(`
944
+ `).slice(c.start-1,c.end).join(`
945
+ `));let h;if(u===".ts"||u===".tsx"||u===".js"||u===".jsx"){h=new os;let j={syntax:"typescript",tsx:s.endsWith(".tsx"),target:"es2020"};try{let K=c?`${f}
946
+ ${p}`:p,U=await Ts(K,j);h.visitModule(U)}catch{if(c)try{let U=`${f}
947
+ class TraceContext {
948
+ ${p}
949
+ }`,H=await Ts(U,j);h.visitModule(H)}catch{let H=new pn,M=u;H.visit(p,M),h.calls=H.calls,h.apiCalls=H.apiCalls,h.imports=H.imports}else{let U=new pn;U.visit(p,u),h.calls=U.calls,h.apiCalls=U.apiCalls,h.imports=U.imports}}}else h=new pn,h.visit(p,u);k.info({file:De.basename(s),calls:h.calls.size,apiCalls:h.apiCalls.length,depth:r},"Analyzed file");let y=Math.max(0,dn-o.count),b=Math.max(2,Math.min(10,Math.floor(y/(r<=2?3:5)))),g=h.apiCalls.slice(0,b);h.apiCalls.length>b&&(o.pruned=!0);for(let j of g){if(o.count>=dn)break;if(o.count++,j.method==="PUBSUB"){let M={type:"event_trigger",name:`PubSub Event: ${j.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(M);let D=j.url.toLowerCase();if(ag.has(D)){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 O=n.exports.findByNameGlobal(j.url).concat(n.exports.findByMethodName(j.url));if(j.url.length>10){let z=j.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(z!==j.url){let v=n.exports.findByNameGlobal(z).concat(n.exports.findByMethodName(z));O.push(...v)}}let Y=new Set;for(let z of O.slice(0,sg)){if(Y.has(z.file_path)||z.file_path===s)continue;if(Y.add(z.file_path),o.count>=dn)break;o.count++;let v={type:"subscriber",name:`${z.name} (${De.basename(z.file_path)})`,path:De.relative(t,z.file_path),line:z.start_line,details:"Potential Subscriber / Handler",children:[]};M.children.push(v),$n.existsSync(z.file_path)&&!i.has(z.file_path)&&(i.add(z.file_path),await cs(z.file_path,v,t,n,i,r+1,o,a))}continue}let K={type:"api_call",name:`${j.method} ${j.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(K);let H=fp(n,j.url,j.method).slice(0,ng);for(let M of H){if(dg(M.file_path,s))continue;if(o.count>=dn)break;o.count++;let D={type:"route",name:M.signature||"Route Handler",path:M.file_path,line:M.start_line,children:[]};if(K.children.push(D),$n.existsSync(M.file_path)&&!i.has(M.file_path)&&(i.add(M.file_path),await cs(M.file_path,D,t,n,i,r+1,o,a)),M.capabilities)try{let O=JSON.parse(M.capabilities);if(O.handler){let[Y,z]=O.handler.split("@");if(Y){let _=Y.split("\\").pop();if(_){let R=n.exports.findClassByName(_);if(R){let T=n.exports.findByNameAndFile(z||"",R.file_path),$,F=R.start_line;T.length>0&&($=sr(R.file_path,{start:T[0].start_line,end:T[0].end_line},z||"",a),$||($={start:T[0].start_line,end:T[0].end_line}),F=$.start);let B={type:"component",name:`${_}${z?" :: "+z:""}`,path:De.relative(t,R.file_path),line:F,details:"Controller Logic (Macro IR)",children:[]};D.children.push(B),i.has(R.file_path+(z?`:${z}`:""))||(i.add(R.file_path+(z?`:${z}`:"")),await cs(R.file_path,B,t,n,i,r+1,o,a,$))}}}}}catch{}}}let w=c?c.start-1:0,A=gg(hg(p,w)),x=Math.max(0,hp-o.dataFlowCount),{visibleEdges:E,omittedCount:I}=bg(A,x);I>0&&(o.pruned=!0);for(let j of E){if(o.count>=dn)break;o.count++,o.dataFlowCount++,e.children.push({type:"data_flow",name:`${j.symbol} handoff`,line:j.toLines[0],details:yg(j),children:[]})}I>0&&E.length>0&&o.count<dn&&(o.count++,e.children.push({type:"data_flow",name:`${I} additional handoffs omitted`,details:x<=E.length?`Suppressed after trace hit the data-flow readability cap (${hp} nodes per trace).`:"Suppressed to keep file-level trace readable.",children:[]}));let N=h.calls,P=Array.from(N).sort(),C=fg(r,o.count),W=P.slice(0,C);P.length>C&&(o.pruned=!0);for(let j of W)if(h.imports.has(j)){let K=h.imports.get(j);if(!K.startsWith(".")){if(["react","react-dom"].includes(K))continue;e.children.push({type:"function",name:j,details:`External: ${K}`,children:[]});continue}let U=Cn(K,s,t);if(U&&$n.existsSync(U)){let H=n.exports.findByNameAndFile(j,U),M=H.length>0?H[0]:null,D=M?`${U}:${M.name}`:U;if(i.has(D))e.children.push({type:"function",name:j,details:"Circular / Already Visited",path:De.relative(t,U),line:M?.start_line,children:[]});else{i.add(D);let O={type:M?"component":"file",name:j,details:M?`Imported symbol from ${De.basename(U)}`:`Imported from ${De.basename(U)}`,path:De.relative(t,U),line:M?.start_line,children:[]};e.children.push(O);let Y=M?sr(U,{start:M.start_line,end:M.end_line},j,a):void 0;await cs(U,O,t,n,i,r+1,o,a,Y)}}}else if(!["log","info","error","warn","print"].includes(j)&&!_p(j)){let K=ug(j,s,n);if(K.length>0){let U=K.find(M=>M.file_path===s),H=U||(K.length===1?K[0]:null);if(H){let M=`${H.file_path}:${H.name}`;if(!i.has(M)){i.add(M);let D={type:"component",name:j,details:`Resolved via global index${U?" (local)":""}`,path:De.relative(t,H.file_path),line:sr(H.file_path,{start:H.start_line,end:H.end_line},j,a)?.start,children:[]};e.children.push(D);let O=sr(H.file_path,{start:H.start_line,end:H.end_line},j,a)||{start:H.start_line,end:H.end_line};await cs(H.file_path,D,t,n,i,r+1,o,a,O)}}}}}catch(d){k.error({filePath:s,error:d.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:d.message,children:[]})}}q();async function Ep(s){let{repoPath:e,filePath:t,symbolName:n,depth:i=3,limit:r=50,offset:o=0}=s;await Q(e);try{let c=await new as(e).analyze(n,{filePath:t,depth:i,limit:r,offset:o});return c.length===0?{content:[{type:"text",text:`Symbol "${n}" not found.`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(c,null,2)}]}}catch(a){return k.error({error:a,args:s},"Impact Analysis failed"),{content:[{type:"text",text:`Impact Analysis failed: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}}V();import xg from"fs";import vg from"path";function kg(s,e){let t=(s.source_file_path||"").toLowerCase(),n=(s.target_file_path||"").toLowerCase(),i=(s.relationship||"").toLowerCase(),r=(s.metadata||"").toLowerCase();return t.includes(e)||n.includes(e)||i.includes(e)||r.includes(e)}function Rg(s){if(!s)return 1;try{return JSON.parse(s)?.confidence??1}catch{return 1}}var or=class{constructor(e){this.repoPath=e}async analyzeMesh(e,t){let n=e.trim().toLowerCase(),{files:i}=L.getInstance(this.repoPath),r=i.findSynapses({name:e,type:t?.type,limit:500}),o=[],a=[];for(let p of r){let u={file:vg.relative(this.repoPath,p.file_path),line:p.line_number??null,snippet:p.code_snippet??null,repoPath:this.repoPath};p.direction==="produce"?o.push(u):a.push(u)}let c=[],l=new Set,d=new Map;if(t?.includeCrossRepo)try{let p=Pn();for(let u of p)try{let m=Ie(u),f=nr(u);if(d.set(u,f),!xg.existsSync(m))continue;let h=(await import("better-sqlite3")).default,y=new h(m,{readonly:!0}),b=y.prepare(`SELECT source_repo, target_repo, source_file_path, target_file_path, relationship, metadata
950
+ FROM virtual_edges
951
+ WHERE (source_repo = ? OR target_repo = ?)
952
+ AND (
953
+ lower(source_file_path) LIKE ?
954
+ OR lower(target_file_path) LIKE ?
955
+ OR lower(relationship) LIKE ?
956
+ OR lower(COALESCE(metadata, '')) LIKE ?
957
+ )
958
+ LIMIT 200`).all(this.repoPath,this.repoPath,`%${n}%`,`%${n}%`,`%${n}%`,`%${n}%`);y.close();for(let g of b){if(!kg(g,n))continue;let w=[g.source_repo,g.source_file_path,g.target_repo,g.target_file_path,g.relationship].join("::");l.has(w)||(l.add(w),c.push({sourceRepo:g.source_repo,targetRepo:g.target_repo,sourceFile:g.source_file_path,targetFile:g.target_file_path,relationship:g.relationship,confidence:Rg(g.metadata),workspaceName:u,workspaceState:f.state,workspaceConfidence:f.confidence}))}}catch{}}catch{}return{topic:e,type:t?.type,producers:o,consumers:a,crossRepoEdges:c,workspaces:Array.from(d.values()),totalEdges:o.length+a.length+c.length}}};async function xp(s){let{repoPath:e,topic:t,type:n,includeCrossRepo:i=!1,format:r="json"}=s;if(!t||typeof t!="string"||t.trim().length===0)return{isError:!0,content:[{type:"text",text:"topic must be a non-empty string"}]};await Q(e);let a=await new or(e).analyzeMesh(t.trim(),{type:n,includeCrossRepo:i});if(a.totalEdges===0)return{content:[{type:"text",text:`No producers or consumers found for topic "${t}" in the indexed files.
959
+
960
+ Suggestions:
961
+ - Check the topic name \u2014 partial matches are supported.
962
+ - Use type filter: socket_event, api_route, or pubsub_topic.
963
+ - If the index is empty, run shadow_recon_onboard first.`}]};if(r==="text"){let c=`# Event Mesh: "${a.topic}"
964
+ `;a.type&&(c+=`Type: ${a.type}
1082
965
  `),c+=`
966
+ ## Producers (${a.producers.length})
967
+ `;for(let l of a.producers)c+=`- ${l.file}${l.line?`:${l.line}`:""}
968
+ `,l.snippet&&(c+=` \`${l.snippet.slice(0,120)}\`
969
+ `);c+=`
970
+ ## Consumers (${a.consumers.length})
971
+ `;for(let l of a.consumers)c+=`- ${l.file}${l.line?`:${l.line}`:""}
972
+ `,l.snippet&&(c+=` \`${l.snippet.slice(0,120)}\`
973
+ `);if(a.crossRepoEdges.length>0){c+=`
974
+ ## Cross-Repo Edges (${a.crossRepoEdges.length})
975
+ `;for(let l of a.crossRepoEdges)c+=`- ${l.sourceRepo} \u2192 ${l.targetRepo} (${l.relationship})
976
+ `}return{content:[{type:"text",text:c.trim()}]}}return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}V();async function vp(s){let{repoPath:e,filePath:t}=de(s),{symbolName:n,direction:i="both",relationship:r,limit:o=50}=s;await Q(e);let c=L.getInstance(e).exports.findTypeGraphEdges(n,{filePath:t,direction:i,relationship:r,limit:o}),l=c.reduce((d,p)=>(d.byRelationship[p.relationship]||(d.byRelationship[p.relationship]=0),d.byRelationship[p.relationship]+=1,d.byDirection[p.direction]||(d.byDirection[p.direction]=0),d.byDirection[p.direction]+=1,d),{byRelationship:{},byDirection:{}});return{content:[{type:"text",text:JSON.stringify({symbol:n,...t?{filePath:t}:{},direction:i,...r?{relationship:r}:{},totalEdges:c.length,summary:l,edges:c.map(d=>({direction:d.direction,relationship:d.relationship,source:d.source_symbol_name,target:d.target_symbol_name,file:d.file_path,line:d.line_number}))},null,2)}]}}import Pg from"path";var Pe=Qu(Tp(),1);import*as Tt from"@clack/prompts";var le={red:Pe.default.red,green:Pe.default.green,yellow:Pe.default.yellow,blue:Pe.default.blue,magenta:Pe.default.magenta,cyan:Pe.default.cyan,white:Pe.default.white,gray:Pe.default.gray,bold:Pe.default.bold,dim:Pe.default.dim,italic:Pe.default.italic,underline:Pe.default.underline,inverse:Pe.default.inverse},un=s=>s.replace(/\x1b\[[0-9;]*m/g,""),ke=s=>Tt.intro(Pe.default.bgCyan(Pe.default.black(Pe.default.bold(` ${s} `)))),_t=s=>Tt.outro(Pe.default.cyan(s)),we=(s,e,t="blue")=>{let n=e.split(`
977
+ `),i=un(s),r=Math.max(i.length+4,...n.map(c=>un(c).length))+2,o="\u2500".repeat(r),a=le[t];console.log(a(`\u250C${o}\u2510`)),console.log(a("\u2502 ")+le.bold(s).padEnd(r+(s.length-i.length)-1)+a("\u2502")),console.log(a(`\u251C${o}\u2524`)),n.forEach(c=>{let l=un(c),d=" ".repeat(r-l.length-1);console.log(a("\u2502 ")+c+d+a("\u2502"))}),console.log(a(`\u2514${o}\u2518`))},ge=(s,e)=>{let t=s.map((i,r)=>Math.max(un(i).length,...e.map(o=>un(o[r]||"").length))+2),n=le.cyan("\u2502");console.log(n),console.log(n+" "+s.map((i,r)=>le.bold(le.cyan(i)).padEnd(t[r]+(i.length-un(i).length))).join(le.gray(" "))+" "),e.forEach(i=>{console.log(n+" "+i.map((r,o)=>(r||"").padEnd(t[o]+(r.length-un(r).length))).join(le.gray(" "))+" ")}),console.log(n)},Cp=(s,e="\u2022")=>{s.forEach(t=>{console.log(`${le.cyan("\u2502")} ${le.cyan(e)} ${t}`)})},lr=(s,e=40)=>{let t=Math.max(...s.map(i=>i.value)),n=Math.max(...s.map(i=>un(i.label).length));console.log(le.cyan("\u2502")),s.forEach(i=>{let r=Math.round(i.value/t*e),o="\u2588".repeat(r)+le.dim("\u2591".repeat(e-r)),a=i.color?le[i.color]:le.cyan,c=i.label.padEnd(n);console.log(`${le.cyan("\u2502")} ${le.bold(c)} ${a(o)} ${le.white(i.value.toString())}`)}),console.log(le.cyan("\u2502"))},zo=(s,e="")=>{s.forEach((t,n)=>{let i=n===s.length-1,r=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?le[t.color]:t.children?le.blue:le.white,a=t.info?` ${le.gray(`(${t.info})`)}`:"";if(console.log(`${le.cyan("\u2502")} ${e}${le.gray(r)}${o(t.name)}${a}`),t.children&&t.children.length>0){let c=e+(i?" ":"\u2502 ");zo(t.children,c)}})},st=()=>Tt.spinner();async function Bs(s,e,t){if(e.length===0)return;let n=await Tt.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(!Tt.isCancel(n))return n}var Ig=s=>{console.error("");let e=s instanceof Error?s.message:String(s);console.error(` ${le.red("\u2716")} ${le.bold("Error: ")} ${e}`),s instanceof Error&&"cause"in s&&console.error(` ${le.dim("Cause: "+String(s.cause))}`),console.error(""),process.exit(1)},ee=async s=>{try{await s()}catch(e){Ig(e)}},S=le;function Ho(s,e,t){let n=s[e];if(n===void 0){s[e]=t;return}if(Array.isArray(n)){n.push(String(t));return}s[e]=[String(n),String(t)]}function Ap(s){return s.startsWith("-")&&s!=="-"}function Ve(s){let e=[],t={};for(let n=0;n<s.length;n+=1){let i=s[n];if(!Ap(i)){e.push(i);continue}let r=i.replace(/^-+/,"");if(!r){e.push(i);continue}let o=r.indexOf("=");if(o>=0){let c=r.slice(0,o),l=r.slice(o+1);Ho(t,c,l);continue}let a=s[n+1];if(a&&!Ap(a)){Ho(t,r,a),n+=1;continue}Ho(t,r,!0)}return{positionals:e,flags:t}}function pr(s,e){for(let t of e){let n=s[t];if(n!==void 0)return n}}function Uo(s){if(s!==void 0)return Array.isArray(s)?s[s.length-1]:s}function G(s,...e){let t=Uo(pr(s,e));if(typeof t=="string"&&t.length>0)return t}function Ip(s,e,...t){let n=G(s,...t);if(n!==void 0&&e.includes(n))return n}function re(s,e,t=!1){let n=Uo(pr(s,e));if(typeof n=="boolean")return n;if(typeof n=="string"){if(["false","0","no","off"].includes(n.toLowerCase()))return!1;if(["true","1","yes","on"].includes(n.toLowerCase()))return!0}return t}function se(s,e){let t=Uo(pr(s,e));if(typeof t=="string"&&t.length>0){let n=Number(t);if(Number.isFinite(n))return n}}function Ue(s,...e){let t=pr(s,e);return t===void 0?[]:Array.isArray(t)?t.flatMap(n=>String(n).split(",").map(i=>i.trim()).filter(Boolean)):String(t).split(",").map(n=>n.trim()).filter(Boolean)}function Oe(s){return Pg.resolve(s||process.cwd())}function Ye(s){if(console.log(""),console.log(` ${S.bold(s.command)}`),console.log(` ${s.summary}`),console.log(""),console.log(` ${S.bold("Usage:")} ${s.usage}`),s.actions?.length){console.log(""),console.log(` ${S.bold("Actions")}`);for(let e of s.actions)console.log(` ${S.cyan(e.command.padEnd(24))} ${e.description}`)}if(s.examples?.length){console.log(""),console.log(` ${S.bold("Examples")}`);for(let e of s.examples)console.log(` ${e}`)}if(s.notes?.length){console.log(""),console.log(` ${S.bold("Notes")}`);for(let e of s.notes)console.log(` ${e}`)}console.log("")}function Ht(){Ye({command:"liquid-shadow analyze",summary:"Human CLI for the shared analysis suite: impact, deps, flow, mesh, debt, type graph, and diff explain.",usage:"liquid-shadow analyze <mode> [args] [--flags]",actions:[{command:"impact <symbol>",description:"Blast radius, risk score, and mapped tests"},{command:"deps <file>",description:"Direct imports or importers for a file"},{command:"flow <file>",description:"Execution trace from a file or symbol entrypoint"},{command:"mesh <topic>",description:"Event/API producers and consumers"},{command:"type-graph <symbol>",description:"Extends / implements / constrained_by edges"},{command:"debt <dead-code|circular-deps>",description:"Dead code and circular dependency reporting"},{command:"explain-diff",description:"Summarize changed symbols, blast radius, and suggested tests"}],examples:["liquid-shadow analyze impact RepositoryFactory --file src/data/factory.ts","liquid-shadow analyze deps src/entry/cli/index.ts --direction imports","liquid-shadow analyze flow src/entry/cli/index.ts --symbol withProjectDefaults","liquid-shadow analyze mesh /api/orders --type api_route","liquid-shadow analyze debt dead-code --confidence high --limit 15"]})}function ps(s){try{return JSON.parse(s)}catch{return null}}function mn(s){console.log(""),console.log(s),console.log("")}function Lg(s){let e=ps(s);if(!Array.isArray(e)){mn(s);return}for(let t of e){let n=Array.isArray(t.impact)?t.impact:[],i=typeof t.verification=="object"&&t.verification?t.verification:{},r=typeof t.riskScore=="object"&&t.riskScore?t.riskScore:{};console.log(""),console.log(` ${S.bold(String(t.symbol??"symbol"))} ${S.dim(`(${String(t.definedIn??"unknown")})`)}`),console.log(` ${S.dim("Risk:")} ${S.bold(String(r.level??"unknown"))} ${S.dim(`(${String(r.score??"n/a")})`)} ${String(r.rationale??"")}`),console.log(` ${S.dim("Blast radius:")} ${n.length} shown of ${String(t.pagination?.total??n.length)}`),n.length>0&&ge(["File","Type","Depth","Verified"],n.map(a=>{let c=a;return[String(c.file??""),String(c.type??""),String(c.depth??""),c.verified?S.green("yes"):S.yellow("maybe")]}));let o=Array.isArray(i.mappedTests)?i.mappedTests:[];o.length>0?console.log(` ${S.dim("Mapped tests:")} ${o.join(", ")}`):console.log(` ${S.dim("Mapped tests:")} none detected`)}console.log("")}function Ng(s){let e=ps(s);if(!e||Array.isArray(e)){mn(s);return}let t=Array.isArray(e.results)?e.results:[];if(console.log(""),console.log(` ${S.bold("Dependencies")} ${S.dim(`showing ${t.length} of ${String(e.total??t.length)}`)}`),t.length===0){console.log(` ${S.dim("No dependency rows returned.")}`),console.log("");return}"module"in t[0]?ge(["Module","Class","Resolved","External"],t.map(i=>{let r=i;return[String(r.module??""),String(r.dependencyClass??""),String(r.relativePath??r.resolvedPath??""),r.isExternal?S.yellow("yes"):S.green("no")]})):ge(["Importer","Statement","Symbols"],t.map(i=>{let r=i;return[String(r.relativePath??r.file??""),String(r.importStatement??""),String(r.importedSymbols??"")]})),console.log("")}function Mg(s){let e=ps(s);if(!e||Array.isArray(e)){mn(s);return}let t=Array.isArray(e.edges)?e.edges:[];console.log(""),console.log(` ${S.bold(String(e.symbol??"Type graph"))} ${S.dim(`${String(e.totalEdges??t.length)} edge(s)`)}`),t.length>0?ge(["Direction","Relationship","Source","Target","File"],t.map(n=>{let i=n;return[String(i.direction??""),String(i.relationship??""),String(i.source??""),String(i.target??""),String(i.file??"")]})):console.log(` ${S.dim("No type edges returned.")}`),console.log("")}function Lp(s,e="",t=!0){let n=e?t?"\u2514\u2500 ":"\u251C\u2500 ":"",i=String(s.name??s.path??"node"),r=[typeof s.type=="string"?s.type:null,typeof s.path=="string"?s.path:null,typeof s.line=="number"?`line ${s.line}`:null].filter(Boolean).join(" \xB7 ");console.log(` ${e}${n}${S.bold(i)}${r?` ${S.dim(`(${r})`)}`:""}`);let o=Array.isArray(s.children)?s.children:[];o.forEach((a,c)=>{if(typeof a!="object"||!a)return;let l=e+(e?t?" ":"\u2502 ":"");Lp(a,l,c===o.length-1)})}function $g(s){let e=ps(s);if(!e||Array.isArray(e)){mn(s);return}console.log(""),Lp(e),console.log("")}function Dg(s){let e=ps(s);if(!e||Array.isArray(e)){mn(s);return}let t=Array.isArray(e.producers)?e.producers:[],n=Array.isArray(e.consumers)?e.consumers:[];console.log(""),console.log(` ${S.bold(String(e.topic??"Mesh topic"))} ${S.dim(`(${String(e.type??"all")})`)}`),console.log(` ${S.dim("Producers:")} ${t.length} ${S.dim("Consumers:")} ${n.length}`),t.length>0&&ge(["Producer","Line","Snippet"],t.map(i=>{let r=i;return[String(r.file??""),String(r.line??""),String(r.snippet??"").slice(0,60)]})),n.length>0&&ge(["Consumer","Line","Snippet"],n.map(i=>{let r=i;return[String(r.file??""),String(r.line??""),String(r.snippet??"").slice(0,60)]})),console.log("")}function Og(s){let e=ps(s);if(!e||Array.isArray(e)){mn(s);return}let t=Array.isArray(e.changes)?e.changes:[],n=Array.isArray(e.verification?.suggestedTestFiles)?e.verification?.suggestedTestFiles??[]:[];console.log(""),console.log(` ${S.bold("Diff summary")}`);let i=typeof e.summary=="object"&&e.summary?e.summary:{};console.log(` ${S.dim("Changed files:")} ${String(i.changedFiles??t.length)} ${S.dim("Changed symbols:")} ${String(i.changedSymbols??"n/a")} ${S.dim("Suggested tests:")} ${n.length}`),t.length>0&&ge(["File","Status","From"],t.map(r=>{let o=r;return[String(o.file??""),String(o.status??""),String(o.from??"")]})),n.length>0&&console.log(` ${S.dim("Suggested test files:")} ${n.join(", ")}`),console.log("")}function Pp(s,e){if(e)return ls.isAbsolute(e)?e:ls.join(s,e)}async function Bo(s){let e=Ve(s),[t,...n]=e.positionals;if(!t){Ht();return}if(t==="help"||t==="--help"||t==="-h"){Ht();return}let i=Oe(G(e.flags,"dir","d"));await ee(async()=>{try{switch(t){case"impact":{let r=n[0];if(!r){Ht(),process.exitCode=1;return}let o=await Ep({repoPath:i,symbolName:r,filePath:Pp(i,G(e.flags,"file")),depth:se(e.flags,["depth"]),limit:se(e.flags,["limit"]),offset:se(e.flags,["offset"])});Lg(o.content[0]?.text??"");return}case"deps":{let r=n[0];if(!r){Ht(),process.exitCode=1;return}let o=await Ul({repoPath:i,filePath:ls.isAbsolute(r)?r:ls.join(i,r),direction:G(e.flags,"direction")??"imports",limit:se(e.flags,["limit"]),offset:se(e.flags,["offset"])});Ng(o.content[0]?.text??"");return}case"flow":{let r=n[0];if(!r){Ht(),process.exitCode=1;return}let o=await rr({repoPath:i,filePath:ls.isAbsolute(r)?r:ls.join(i,r),symbolName:G(e.flags,"symbol")});$g(o.content[0]?.text??"");return}case"mesh":{let r=n[0];if(!r){Ht(),process.exitCode=1;return}let o=G(e.flags,"format")??"json",a=await xp({repoPath:i,topic:r,type:G(e.flags,"type"),includeCrossRepo:re(e.flags,["cross-repo","include-cross-repo"]),format:o});o==="text"?mn(a.content[0]?.text??""):Dg(a.content[0]?.text??"");return}case"type-graph":{let r=n[0];if(!r){Ht(),process.exitCode=1;return}let o=await vp({repoPath:i,symbolName:r,filePath:Pp(i,G(e.flags,"file")),direction:G(e.flags,"direction"),relationship:G(e.flags,"relationship"),limit:se(e.flags,["limit"])});Mg(o.content[0]?.text??"");return}case"debt":{let r=n[0];if(!r||!["dead-code","circular-deps"].includes(r)){Ht(),process.exitCode=1;return}let o=await zl({repoPath:i,mode:r,limit:se(e.flags,["limit"]),includeTests:re(e.flags,["include-tests"]),includeMigrations:re(e.flags,["include-migrations"]),includeFixtures:re(e.flags,["include-fixtures"]),confidenceThreshold:G(e.flags,"confidence","confidence-threshold"),excludePatterns:Ue(e.flags,"exclude","exclude-patterns")});mn(o.content[0]?.text??"");return}case"explain-diff":{let r=await up({repoPath:i,baseCommit:G(e.flags,"base","base-commit"),headCommit:G(e.flags,"head","head-commit"),staged:!re(e.flags,["unstaged-only"],!1),includeUntracked:re(e.flags,["include-untracked"],!0),maxSymbols:se(e.flags,["max-symbols","symbols"]),impactDepth:se(e.flags,["impact-depth","depth"]),impactLimit:se(e.flags,["impact-limit","limit"])});Og(r.content[0]?.text??"");return}default:Ht(),process.exitCode=1}}finally{await ne(i)}})}V();import Fg from"path";import{performance as Np}from"perf_hooks";async function Mp(s){let e=Fg.resolve(s);await ee(async()=>{console.log(`
978
+ ${S.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${S.gray("Repository: ")} ${e}`),console.log(` ${S.yellow("Starting fresh index (DB deleted)...")}
979
+ `);let t=Np.now();try{await Q(e,10,!0);let n=Np.now()-t,i=L.getInstance(e),r=i.files.getCount(),o=i.exports.getCount(),a=i.exports.getWithEmbeddingsCount();we("Benchmark Results",`${S.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
980
+ ${S.bold("Files Processed")}: ${S.cyan(r.toString())}
981
+ ${S.bold("Symbols Extracted")}: ${S.cyan(o.toString())}
982
+ ${S.bold("Symbols Embedded")}: ${S.cyan(a.toString())} (${(a/o*100).toFixed(1)}%)
983
+ `+"\u2500".repeat(40)+`
984
+ ${S.bold("Files/sec")}: ${S.green((r/(n/1e3)).toFixed(2))}
985
+ ${S.bold("Symbols/sec")}: ${S.green((o/(n/1e3)).toFixed(2))}
986
+ ${S.bold("ms per file")}: ${S.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
987
+ Benchmark failed during execution:`,n),n}finally{await ne(e)}})}import zg from"path";V();q();V();q();V();Hs();q();import{execSync as ds}from"child_process";var dr=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{ds(`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 ds(`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=ds(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
988
+ `);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{ds(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{ds(`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{ds(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};var us=k.child({module:"persistence-service"}),St=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new dr(e)}async syncMissionToGitNotes(e){let{missions:t,intentLogs:n}=L.getInstance(this.repoPath),i=t.findById(e);if(!i)throw new Error(`Mission ${e} not found`);if(!i.commit_sha){us.info({missionId:e},"Skipping Git Notes sync because mission has no commit_sha yet");return}us.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(d=>d.type==="adr"),c=o.filter(d=>d.type==="decision").map(d=>({content:d.content,symbol_name:d.symbol_name,created_at:d.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}=L.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){us.error({missionId:r.id,...He(o)},"Failed to sync mission")}}async recoverFromGitNotes(){let e=this.gitNotes.listNotes(),{missions:t,intentLogs:n}=L.getInstance(this.repoPath),i=0,r=0,o=0;for(let[a,c]of e.entries())try{let l=JSON.parse(c);if(l.version!=="1.0")continue;if(t.findByCommitShas([a]).some(m=>m.name===l.mission.name)){us.debug({commitSha:a,missionName:l.mission.name},"Mission already exists, skipping recovery");continue}let u=t.create({name:l.mission.name,goal:l.mission.goal,status:l.mission.status,strategy_graph:l.mission.strategy_graph,git_branch:l.mission.git_branch,commit_sha:a,parent_id:l.mission.parent_id,verification_context:l.mission.verification_context,outcome_contract:l.mission.outcome_contract});if(i++,l.adr&&(n.create({mission_id:Number(u),symbol_id:null,file_path:null,type:"adr",content:l.adr,confidence:1,symbol_name:null,signature:null,commit_sha:a}),r++),l.decisions&&l.decisions.length>0)for(let m of l.decisions)n.create({mission_id:Number(u),symbol_id:null,file_path:null,type:"decision",content:m.content,confidence:1,symbol_name:m.symbol_name,signature:null,commit_sha:a}),r++;us.info({commitSha:a,missionName:l.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(l){o+=1,us.error({commitSha:a,...He(l)},"Failed to parse Git Note for recovery")}return{missionsRecovered:i,logsRecovered:r,notesFailed:o}}};q();var Wg=k.child({module:"reasoning-engine"}),Ut=class{analyze(e){Wg.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 Gs=k.child({module:"briefing-engine"}),Bt=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=L.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Ut,this.persistencePivot=new St(e)}async distillMission(e,t=!0){Gs.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.missions.findById(e),r=(this.intentLogs.findByMission(e,1e3)??[]).filter(u=>u.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),c=new Set(o.map(u=>u.symbol_name).filter(Boolean)),l=`# Architectural Decision Record: Mission #${e}
989
+
990
+ `;l+=`## Summary of Intent
991
+ `,l+=`Collected ${o.length} intent events across ${c.size} symbols.
992
+
993
+ `,a.context.length>0&&(l+=`### Context
994
+ `,a.context.forEach(u=>{l+=`- ${u}
995
+ `}),l+=`
996
+ `),a.decisions.length>0&&(l+=`### Key Decisions
997
+ `,a.decisions.forEach(u=>{l+=`- ${u}
998
+ `}),l+=`
999
+ `),a.consequences.length>0&&(l+=`### Consequences & Evolutions
1000
+ `,a.consequences.forEach(u=>{l+=`- ${u}
1001
+ `}),l+=`
1002
+ `),a.recommendations.length>0&&(l+=`### Strategic Recommendations
1003
+ `,a.recommendations.forEach(u=>{l+=`- ${u}
1004
+ `}),l+=`
1005
+ `),a.unclassified.length>0&&(l+=`### Additional Notes
1006
+ `,a.unclassified.forEach(u=>{l+=`- ${u}
1007
+ `}),l+=`
1008
+ `),l+=`
1083
1009
  ---
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)
1010
+ *Generated by Liquid Shadow Reasoning Engine v1*`;let d="skipped_dry_run",p="skipped_dry_run";if(t){let u=r[0];if(u?(this.intentLogs.update(u.id,{content:l,confidence:1,commit_sha:n?.commit_sha??null}),d="updated"):(this.intentLogs.create({mission_id:e,type:"adr",content:l,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:n?.commit_sha??null}),d="created"),!n?.commit_sha)p="skipped_no_commit",Gs.info({missionId:e},"Skipping Git Notes sync because mission has no commit_sha yet");else try{await this.persistencePivot.syncMissionToGitNotes(e),p="synced",Gs.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(m){p="failed",Gs.error({missionId:e,error:m},"Failed to sync ADR to Git Notes")}}else Gs.info({missionId:e},"Tactical Briefing synthesized (dry-run).");return{missionId:e,adr:l,metrics:{totalLogs:o.length,symbolCount:c.size},persistence:{adrLog:d,gitNotes:p,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")}};var jg=k.child({module:"narrative-service"}),fn=class{missions;intentLogs;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t,intentLogs:n}=L.getInstance(e);this.missions=t,this.intentLogs=n,this.briefingEngine=new Bt(e)}async generateChronicle(e={}){jg.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,d)=>d.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 d=this.missions.findByParentId(l.id),p=d.length>0,u=await this.briefingEngine.distillMission(l.id,!1),m=this.resolveNarrativeText(l.id,u.adr);if(p){let f=[];for(let b of d){let g=await this.mapMissionToEpisode(b);g&&f.push(g)}let h=await this.mapMissionToEpisode(l);if(h&&f.unshift(h),!m&&f.length===0)continue;let y={kind:"initiative",root_mission_id:l.id,title:l.name,strategy_graph:l.strategy_graph?JSON.parse(l.strategy_graph):{},episodes:e.compact?[]:f,synthesized_narrative:e.compact?this.truncateText(m):m};o.push(y),c.push(y)}else{let f=await this.mapMissionToEpisode(l,m,e.compact);if(!f)continue;a.push(f),c.push(f)}}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;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((c,l)=>l.created_at-c.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(`
1011
+ `):""}truncateText(e,t=300){return e?e.length<=t?e:e.slice(0,t)+"... (truncated)":""}renderChronicleMarkdown(e){let t=`# Repository Chronicle
1012
+
1013
+ `;if(t+=`*Generated at ${new Date(e.generated_at).toISOString()}*
1014
+
1015
+ `,e.timeline&&e.timeline.length>0)for(let n of e.timeline)n.kind==="initiative"?(t+=`### \u{1F9EC} ${n.title} (Mission #${n.root_mission_id})
1016
+ `,t+=`${n.synthesized_narrative}
1017
+
1018
+ `):(t+=`### \u269B\uFE0F ${n.title} (Mission #${n.mission_id})
1019
+ `,t+=`${n.adr_summary}
1020
+
1021
+ `),t+=`---
1022
+ `;return t}};q();async function $p(s,e){let t=zg.resolve(s||process.cwd()),n=e.format==="json"?"json":"markdown",i=k.child({module:"cli:chronicle",repoPath:t});i.info("Generating repository chronicle...");try{let r=new fn(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)}}var Dp=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],Hg=["--help","-h","--version","-v","--dir","-d"],Ug={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 Bg(){let s=Object.entries(Ug).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
1023
+ `),e=Dp.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
1086
1024
  _liquid_shadow() {
1087
1025
  local cur="\${COMP_WORDS[COMP_CWORD]}"
1088
1026
  local words=("\${COMP_WORDS[@]}")
@@ -1092,7 +1030,7 @@ _liquid_shadow() {
1092
1030
  if [[ "\${words[$i]}" != -* ]]; then cmd="\${words[$i]}"; break; fi
1093
1031
  ((i++))
1094
1032
  done
1095
- local opts="${dm.join(" ")}"
1033
+ local opts="${Hg.join(" ")}"
1096
1034
  if [ -n "$cmd" ]; then
1097
1035
  case "$cmd" in
1098
1036
  ${s}
@@ -1104,11 +1042,11 @@ ${s}
1104
1042
  COMPREPLY=($(compgen -W "$opts" -- "$cur"))
1105
1043
  }
1106
1044
  complete -F _liquid_shadow liquid-shadow
1107
- `}function hm(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
1045
+ `}function Gg(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
1108
1046
  # Run after compinit (e.g. in .zshrc after compinit)
1109
1047
 
1110
1048
  _liquid_shadow() {
1111
- local -a cmds; cmds=(${tl.map(e=>`'${e}'`).join(" ")})
1049
+ local -a cmds; cmds=(${Dp.map(e=>`'${e}'`).join(" ")})
1112
1050
  if [ $CURRENT -eq 2 ]; then
1113
1051
  _describe 'command' cmds
1114
1052
  return
@@ -1125,19 +1063,69 @@ _liquid_shadow() {
1125
1063
  _describe 'flag' fl
1126
1064
  }
1127
1065
  compdef _liquid_shadow liquid-shadow
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
1066
+ `}async function Op(s){s==="bash"?console.log(Bg()):s==="zsh"?console.log(Gg()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}Ae();V();import jp from"path";Kt();q();import ue from"fs";import qg from"os";import Ct from"path";var Dn=k.child({module:"git-hooks"}),Jg="Generated by liquid-shadow",Kg=1e6,Go=["post-merge","post-checkout","post-commit"];function Vg(){let s=process.env.LIQUID_SHADOW_CLI_ENTRY;if(s){let t=Ct.resolve(s);if(ue.existsSync(t))return t}let e=je("dist/entry/cli/index.js");return ue.existsSync(e)?e:null}function qo(s){return s.includes("liquid-shadow")||s.includes("mcp-liquid-shadow")||s.includes(Jg)}function Yg(){let s=Ct.join(qg.homedir(),".mcp-liquid-shadow","logs"),e=Ct.join(s,"post-checkout.log");try{if(!ue.existsSync(e)||ue.statSync(e).size<=Kg)return null;ue.mkdirSync(s,{recursive:!0});let n=`${e}.1`;return ue.existsSync(n)&&ue.unlinkSync(n),ue.renameSync(e,n),null}catch(t){return`Failed to rotate post-checkout.log: ${t}`}}function Qg(s,e){return{"post-merge":`#!/bin/sh
1067
+ # Liquid Shadow: Auto-refresh index after merge/pull
1068
+ # Generated by liquid-shadow
1130
1069
 
1131
- `;if(t+=`*Generated at ${new Date(e.generated_at).toISOString()}*
1070
+ REPO_PATH="$(git rev-parse --show-toplevel)"
1132
1071
 
1133
- `,e.timeline&&e.timeline.length>0)for(let n of e.timeline)n.kind==="initiative"?(t+=`### \u{1F9EC} ${n.title} (Mission #${n.root_mission_id})
1134
- `,t+=`${n.synthesized_narrative}
1072
+ # Run liquid-shadow sync in background to avoid blocking git operations
1073
+ nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
1135
1074
 
1136
- `):(t+=`### \u269B\uFE0F ${n.title} (Mission #${n.mission_id})
1137
- `,t+=`${n.adr_summary}
1075
+ exit 0
1076
+ `,"post-checkout":`#!/bin/sh
1077
+ # Liquid Shadow: Auto-refresh index after branch checkout
1078
+ # Generated by liquid-shadow
1138
1079
 
1139
- `),t+=`---
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:`---
1080
+ # Only run on branch checkouts, not file checkouts
1081
+ # $3 is 1 for branch checkout, 0 for file checkout
1082
+ [ "$3" = "1" ] || exit 0
1083
+
1084
+ # Skip no-op checkouts where HEAD does not change
1085
+ [ "$1" = "$2" ] && exit 0
1086
+
1087
+ REPO_PATH="$(git rev-parse --show-toplevel)"
1088
+ LOG_DIR="$HOME/.mcp-liquid-shadow/logs"
1089
+ LOG_FILE="$LOG_DIR/post-checkout.log"
1090
+
1091
+ mkdir -p "$LOG_DIR"
1092
+
1093
+ # Run incremental index in background (default mode preserves fast-path)
1094
+ nohup "${s}" "${e}" index "$REPO_PATH" >> "$LOG_FILE" 2>&1 &
1095
+
1096
+ exit 0
1097
+ `,"post-commit":`#!/bin/sh
1098
+ # Liquid Shadow: Trigger symbol shift detection after commit
1099
+ # Generated by liquid-shadow
1100
+
1101
+ REPO_PATH="$(git rev-parse --show-toplevel)"
1102
+
1103
+ # Run liquid-shadow sync in background
1104
+ nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
1105
+
1106
+ exit 0
1107
+ `}}function Fp(){return[...Go]}function ur(s){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=s,i=Ct.join(e,".git","hooks"),r=[],o=[],a=[];if(!ue.existsSync(Ct.join(e,".git")))return a.push("Not a git repository"),{installed:r,skipped:o,errors:a};ue.existsSync(i)||ue.mkdirSync(i,{recursive:!0});let c=Vg();if(!c)return a.push(`Unable to resolve CLI entry at install time. Expected ${je("dist/entry/cli/index.js")} to exist.`),{installed:r,skipped:o,errors:a};let l=Qg(process.execPath,c),d=new Set;if(t&&(d.add("post-merge"),d.add("post-checkout")),n&&d.add("post-commit"),d.has("post-checkout")){let p=Yg();p&&(a.push(p),Dn.warn({rotationError:p},"Post-checkout log rotation failed"))}for(let p of d){let u=Ct.join(i,p),m=l[p];if(!m){a.push(`No template found for hook: ${p}`);continue}try{if(ue.existsSync(u)){let f=ue.readFileSync(u,"utf-8"),h=qo(f);if(h&&f===m){ue.chmodSync(u,493),o.push(p),Dn.info({hookName:p},"Hook already installed, skipping");continue}if(!h){let y=`${u}.backup-${Date.now()}`;ue.copyFileSync(u,y),Dn.info({hookName:p,backupPath:y},"Backed up existing hook")}}ue.writeFileSync(u,m,{mode:493}),ue.chmodSync(u,493),r.push(p),Dn.info({hookName:p},"Installed git hook")}catch(f){a.push(`Failed to install ${p}: ${f}`),Dn.error({hookName:p,err:f},"Failed to install hook")}}return{installed:r,skipped:o,errors:a}}function Wp(s){let e=Ct.join(s,".git","hooks"),t=[],n=[];if(!ue.existsSync(e))return{removed:t,errors:n};for(let i of Go){let r=Ct.join(e,i);try{if(ue.existsSync(r)){let o=ue.readFileSync(r,"utf-8");qo(o)&&(ue.unlinkSync(r),t.push(i),Dn.info({hookName:i},"Removed git hook"))}}catch(o){n.push(`Failed to remove ${i}: ${o}`),Dn.error({hookName:i,err:o},"Failed to remove hook")}}return{removed:t,errors:n}}function Xg(s,e){let t=Ct.join(s,".git","hooks"),n=Ct.join(t,e);if(!ue.existsSync(t)||!ue.existsSync(n))return"missing";try{let i=ue.readFileSync(n,"utf-8");return qo(i)?(ue.statSync(n).mode&73)!==0?"installed":"disabled":"foreign"}catch{return"foreign"}}function At(s){let e=[],t=[],n=[],i=[],r={};for(let a of Go){let c=Xg(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 zp(s){let e=jp.resolve(s);try{await ee(async()=>{ke("Liquid Shadow Intelligence Dashboard");let t=L.getInstance(e),n=Xn(),i=At(e),r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);if(we("Operational Core",`${S.bold("State")}: ${Re(e)?S.green("IDENTIFIED (Stable)"):S.red("UNKNOWN (Needs Index)")}
1108
+ ${S.bold("Repository")}: ${S.cyan(jp.basename(e))}
1109
+ ${S.bold("Infrastructure")}: ${i.installed.length>0?S.green("Git-Hooked"):S.yellow("Standalone")}
1110
+ ${S.bold("Last Sync")}: ${a?S.yellow(new Date(a).toLocaleString()):S.red("Never")}`,"blue"),console.log(""),we("Intelligence Density",`${S.bold("Files Target")}: ${S.cyan(r.toString())}
1111
+ ${S.bold("Symbols Mapped")}: ${S.cyan(o.toString())}
1112
+ ${S.bold("Graph Edges")}: ${S.cyan(t.imports.getCount().toString())}
1113
+ ${S.bold("Hotspots")}: ${S.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";we("Reasoning Efficiency",`${S.bold("Query Count")}: ${S.cyan(n.query.count.toString())}
1114
+ ${S.bold("Avg Latency")}: ${S.yellow(`${n.query.avgLatencyMs?.toFixed(2)||0}ms`)}
1115
+ ${S.bold("Cache Hit Rate")}: ${S.green(`${l}%`)}`,"green")}c.length>0&&(console.log(""),console.log(` ${S.bold("Intelligence Landscape")}`),lr(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),35)),console.log(""),_t("Liquid Shadow is observing.")})}finally{await ne(e)}}Ae();import Hp from"fs";import mr from"path";q();var Zg=k.child({module:"mcp:tools:env:diagnose"});async function Up(s){let{repoPath:e}=s,t=mr.isAbsolute(e)?mr.normalize(e):mr.resolve(process.cwd(),e);Zg.info({repoPath:t},"Running MCP diagnose");let n=["# MCP Server Health Check","",`**Repository path**: \`${t}\``,""],i=!1;try{i=Hp.statSync(t).isDirectory()}catch{}n.push("## 1. Path"),n.push(i?"\u2705 Directory exists":"\u274C Path missing or not a directory"),n.push("");let r=mr.join(t,".git"),o=i&&Hp.existsSync(r);n.push("## 2. Git repository"),n.push(o?"\u2705 `.git` found":"\u274C Not a Git repository (or path invalid)"),n.push("");let a=!1,c=!1;if(i)try{ye(t),a=!0,c=Re(t)}catch{}n.push("## 3. Database & index"),n.push(a?"\u2705 Database connected":"\u274C Database not available"),n.push(c?"\u2705 Repository indexed":"\u26A0\uFE0F Not indexed yet"),n.push("");let l=i?At(t):{installed:[],notInstalled:[],missing:[],foreign:[],disabled:[],statuses:{}};n.push("## 4. Git hooks");let d=["post-merge","post-checkout","post-commit"],p=u=>u==="installed"?"\u2705":u==="missing"?"\u26A0\uFE0F":u==="foreign"?"\u274C":u==="disabled"?"\u23F8\uFE0F":"\u2753";if(i){for(let u of d){let m=l.statuses[u]??"missing";n.push(`- \`${u}\`: ${p(m)} ${m}`)}l.notInstalled.length>0&&n.push('- Run `shadow_env_hooks({ action: "install" })` to repair missing hooks.')}else n.push("\u26A0\uFE0F Path unavailable; hook status not checked");return n.push(""),n.push("## 5. Next steps"),i?c?((l.statuses["post-checkout"]??"missing")!=="installed"&&n.push('- Install/repair hooks: run **shadow_env_hooks** with `action: "install"`.'),n.push("- Index is ready. Use shadow_search_*, shadow_inspect_*, shadow_analyze_*.")):n.push("- Run **shadow_recon_onboard** to populate the index."):n.push("- Use a valid repository path."),{content:[{type:"text",text:n.join(`
1116
+ `)}]}}q();var Jo=k.child({module:"mcp:tools:env:hooks"});async function Bp(s){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:i}=s;if(t==="install"){Jo.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:i},"Installing git hooks");let r=ur({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(`
1117
+ `):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(a=>`- \`${a}\` (already installed)`).join(`
1118
+ `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
1119
+ `)),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(`
1120
+ `)}]}}if(t==="remove"){Jo.info({repoPath:e},"Uninstalling git hooks");let r=Wp(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(a=>`- \`${a}\``).join(`
1121
+ `):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(a=>`- ${a}`).join(`
1122
+ `))),{content:[{type:"text",text:o.join(`
1123
+ `)}]}}if(t==="status"){Jo.info({repoPath:e},"Checking git hooks status");let r=At(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(`
1124
+ `):"- None","",`## Missing (${r.missing.length})`,r.missing.length>0?r.missing.map(c=>`- \`${c}\``).join(`
1125
+ `):"- None","",`## Foreign (${r.foreign.length})`,r.foreign.length>0?r.foreign.map(c=>`- \`${c}\` (non-Liquid hook content)`).join(`
1126
+ `):"- None","",`## Disabled (${r.disabled.length})`,r.disabled.length>0?r.disabled.map(c=>`- \`${c}\` (not executable)`).join(`
1127
+ `):"- 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(`
1128
+ `)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}function Ko(){Ye({command:"liquid-shadow env",summary:"Thin CLI bridge for the MCP env tools: diagnose and hooks.",usage:"liquid-shadow env <diagnose|hooks> [args] [--flags]",actions:[{command:"diagnose [repo]",description:"Run the MCP environment diagnosis flow"},{command:"hooks <install|remove|status> [repo]",description:"Run the MCP git hook manager"}],examples:["liquid-shadow env diagnose .","liquid-shadow env hooks status .","liquid-shadow env hooks install . --auto-refresh --symbol-healing"]})}function Gp(s){console.log(""),console.log(s),console.log("")}async function fr(s){let e=Ve(s),[t,...n]=e.positionals;if(!t||t==="help"||t==="--help"||t==="-h"){Ko();return}await ee(async()=>{let i=Oe(t==="hooks"?n[1]:n[0]);try{if(t==="diagnose"){let r=await Up({repoPath:i});Gp(r.content[0]?.text??"");return}if(t==="hooks"){let r=n[0],o=r==="uninstall"?"remove":r;if(!o||!["install","remove","status"].includes(o)){Ko(),process.exitCode=1;return}let a=await Bp({repoPath:i,action:o,enableAutoRefresh:re(e.flags,["auto-refresh"],!0),enableSymbolHealing:re(e.flags,["symbol-healing"],!0)});Gp(a.content[0]?.text??"");return}Ko(),process.exitCode=1}finally{await ne(i)}})}async function Vo(s){let e=[...s];e[0]==="uninstall"&&(e[0]="remove"),await fr(["hooks",...e])}import ny from"fs";import Kp from"path";import qp from"fs";import ty from"ignore";import Jp from"path";V();q();import It from"path";var ey=50;function hr(s,e,t,n){let i={name:It.basename(e)||e,type:"directory",path:e,children:[]};return[...s].sort((o,a)=>{let c=It.relative(e,o.path),l=It.relative(e,a.path),d=c.includes(It.sep),p=l.includes(It.sep);if(d!==p)return d?-1:1;let u=c.split(It.sep).length,m=l.split(It.sep).length;return u!==m?u-m:c.localeCompare(l)}).forEach(o=>{let c=It.relative(e,o.path).split(It.sep),l=i;for(let d=0;d<c.length;d++){let p=c[d];if(n!==void 0&&d>=n)return;let u=d===c.length-1;if(n===1&&d===0&&u)return;let m=n!==void 0&&d===n-1&&!u,f=It.join(e,...c.slice(0,d+1)),h=l.children?.find(y=>y.name===p);if(!h){if(l.children&&l.children.length>=ey){l.children.find(g=>g.type==="truncated")||l.children.push({name:"... (truncated)",type:"truncated",path:"",children:void 0});return}h={name:p,type:u?"file":"directory",path:f,children:u||m?void 0:[],summary:u?{classification:o.classification,summaryText:o.summary,exports:o.exports,imports:o.imports,chunks:o.chunks}:void 0},h.summary&&(t==="structure"||t==="signatures")&&(delete h.summary.chunks,delete h.summary.imports),l.children?.push(h)}l=h}}),i}async function ms(s,e=wi.DEFAULT_CONCURRENCY,t="detailed",n,i){k.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await Q(s,e);let{files:r,exports:o,imports:a}=L.getInstance(s),c=n?r.findInSubPath(s,n):r.findAll(),l=Ot(s),d=ty(),p=Jp.join(s,".gitignore");if(qp.existsSync(p)&&d.add(qp.readFileSync(p,"utf8")),l.ignore&&l.ignore.length>0&&d.add(l.ignore),d.add(Si),c=c.filter(g=>{let w=Jp.relative(s,g.path);return!d.ignores(w)}),k.info({count:c.length},"Fetching data from DB..."),t==="lite"){let g=c.map(w=>({path:w.path,mtime:w.mtime}));return hr(g,s,t,i)}if(t==="summaries"){let g=c.map(w=>({path:w.path,mtime:w.mtime,classification:w.classification||void 0,summary:w.summary||void 0}));return hr(g,s,t,i)}let u=c.map(g=>g.path),m=o.findByFiles(u),f=t==="detailed"?a.findByFiles(u):[],h=new Map;for(let g of m){let w=h.get(g.file_path)||[];w.push(g),h.set(g.file_path,w)}let y=new Map;for(let g of f){let w=y.get(g.file_path)||[];w.push(g),y.set(g.file_path,w)}let b=c.map(g=>{let A=(h.get(g.path)||[]).map(E=>({name:E.name,kind:E.kind,signature:E.signature,line:E.start_line}));t==="structure"?A=A.map(E=>({name:E.name,kind:E.kind,line:E.line})):t==="signatures"&&(A=A.map(E=>({name:E.name,kind:E.kind,signature:E.signature,line:E.line})));let x=[];return t==="detailed"&&(x=(y.get(g.path)||[]).map(I=>({module:I.module_specifier,resolved_path:I.resolved_path}))),{path:g.path,mtime:g.mtime,classification:g.classification||void 0,summary:g.summary||void 0,exports:A,imports:x.length>0?x:void 0,chunks:[]}});return k.info({count:b.length},"Building hierarchical project tree..."),hr(b,s,t,i)}async function Vp(s,e){let t=Kp.resolve(s);await ee(async()=>{if(ke("\u{1F311} Liquid Shadow: Intelligence Deployment"),console.log(` ${S.bold("Target")}: ${S.cyan(t)}`),console.log(` ${S.bold("Objective")}: ${e.output?S.magenta("Data Extraction"):S.green("Semantic Mapping")}`),console.log(""),!e.output){let i=st();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 Q(t,void 0,e.force,e.deep??!0,o),i.message("\u{1FA79} Running Nano-Repair healing...");let c=new $e(t).detectAndRepairShifts();i.stop("Intelligence mapping successfully concluded."),console.log(""),console.log(` ${S.bold("Next Steps:")}`),console.log(` ${S.dim("view your repo stats")} -> ${S.bold(S.cyan("liquid-shadow dashboard"))}`),console.log(` ${S.dim("start a chat search")} -> ${S.bold(S.cyan('liquid-shadow search-concept "your query"'))}`),console.log(""),_t("Liquid Shadow is online.")}catch(a){throw i.stop(`Operation failed: ${a.message}`),a}finally{await ne(t)}return}let n=st();n.start("Engaging intelligence engines...");try{let i=await ms(t,5,e.level,e.subPath),r=Kp.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!Ms.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");ny.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Data extraction saved: ${S.bold(S.cyan(r))}`),_t("Extraction complete.")}catch(i){throw n.stop(`Extraction failed: ${i.message}`),i}finally{await ne(t)}})}import*as Le from"@clack/prompts";import hn from"fs";import ry from"os";import fs from"path";import{pino as oy}from"pino";import*as Gt from"@clack/prompts";import pt from"fs";import sy from"os";import Pt from"path";var Yp={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:`---
1141
1129
  name: chronicle
1142
1130
  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.
1143
1131
  ---
@@ -1440,45 +1428,378 @@ Use this skill to build the shortest reliable path from "what is this?" to "I ca
1440
1428
  - Start broad and narrow down; do not jump straight to full-symbol inspection unless you already know the target.
1441
1429
  - \`shadow_analyze_type_graph\` requires \`symbolName\`.
1442
1430
  - \`shadow_analyze_mesh\` requires \`topic\`.
1443
- `,shadow_workspace:`---
1444
- name: workspace
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.
1431
+ `,shadow_workspace:'---\nname: workspace\ndescription: 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.\n---\n\n# Workspace\n\nManage multi-repository workspaces and cross-repo mission links using the Shadow Engine.\n\n## Core calls\n\n- List active work across repos:\n - `shadow_workspace_list({ repoPaths, status?, limit?, summarize? })`\n- Inspect workspace identity, freshness, and next safe action:\n - `shadow_workspace_status({ name?, repoPaths? })`\n- Make a workspace usable without guessing whether to reuse, refresh, repair, or rebuild:\n - `shadow_workspace_ensure({ repoPaths, name?, repairPolicy?, rebuildPolicy? })`\n- Repair stale registry/db/lock state when a workspace exists but is degraded:\n - `shadow_workspace_repair({ name?, repoPaths?, rebuildPolicy? })`\n- Dry-run or apply cleanup for obsolete, duplicate, or orphaned workspaces:\n - `shadow_workspace_gc({ name?, repoPaths?, apply?, olderThanDays?, includeCustom? })`\n- Build a fused search index:\n - `shadow_workspace_fuse({ repoPaths, name? })`\n- Link missions across repos:\n - `shadow_workspace_link({ parentRepoPath, parentMissionId, childRepoPath, childMissionId, relationship })`\n- Visualize a repo\'s mission graph:\n - `shadow_ops_graph({ repoPath, missionId?, depth?, format? })`\n\n## Recommended sequence\n\n- Start with `shadow_workspace_status` when you need to know whether a named or inferred workspace is healthy.\n- Use `shadow_workspace_ensure` for the normal "make this workspace work" path.\n- Use `shadow_workspace_repair` when the workspace already exists and you specifically need cleanup/recovery behavior.\n- Use `shadow_workspace_gc` for maintenance, duplicate cleanup, or stale/orphaned fused indexes.\n- Use `shadow_workspace_fuse` only when you explicitly want to create a fused index, not as the default repair path.\n- Use `shadow_workspace_list` when you need a federated mission/repo overview across multiple repos.\n\n## After fusion\n\n- Use the normal `shadow_search_*` and `shadow_analyze_*` tools inside the participating repos.\n- For routes and events that cross repo boundaries, use:\n - `shadow_analyze_mesh({ repoPath, topic, includeCrossRepo: true })`\n- For cross-repo impact tracing, pair fused workspaces with:\n - `shadow_analyze_impact({ repoPath, symbolName, filePath? })`\n\n## Rules\n\n- `shadow_workspace_list`, `shadow_workspace_fuse`, and `shadow_workspace_ensure` take `repoPaths`, not `repoPath`.\n- `shadow_workspace_status`, `shadow_workspace_repair`, and `shadow_workspace_gc` can resolve by `name`, `repoPaths`, or both depending on what context you have.\n- `shadow_workspace_link` uses explicit parent and child repo paths; there is no shared `repoPath` parameter.\n- Prefer `shadow_workspace_status` before mutating workspace state when you are unsure which workspace will be selected.\n- Prefer `shadow_workspace_ensure` over calling `shadow_workspace_fuse` directly for routine operator/agent recovery.\n'};function iy(s){return[{name:"Claude Code",dir:Pt.join(s,".claude","skills"),folderBased:!0,createIfMissing:!1},{name:"Cursor",dir:Pt.join(s,".cursor","skills"),folderBased:!0,createIfMissing:!1},{name:"Gemini CLI",dir:Pt.join(s,".gemini","skills"),folderBased:!0,createIfMissing:!0},{name:"Codex",dir:Pt.join(s,".codex","skills"),folderBased:!0,createIfMissing:!1},{name:"Antigravity",dir:Pt.join(s,".gemini","antigravity","global_workflows"),folderBased:!1,createIfMissing:!1}]}function Yo(s=!1){let e=sy.homedir(),t=iy(e),n=0;for(let i of t){if(!pt.existsSync(i.dir))if(i.createIfMissing)pt.mkdirSync(i.dir,{recursive:!0});else continue;if(i.folderBased)try{for(let r of pt.readdirSync(i.dir))r.startsWith("shadow_shadow_")&&pt.rmSync(Pt.join(i.dir,r),{recursive:!0,force:!0})}catch{}for(let[r,o]of Object.entries(Yp))if(i.folderBased){let a=Pt.join(i.dir,r);pt.existsSync(a)||pt.mkdirSync(a,{recursive:!0});let c=Pt.join(a,"skill.md");pt.existsSync(c)&&pt.unlinkSync(c);let l=Pt.join(a,"SKILL.md");(s||!pt.existsSync(l))&&(pt.writeFileSync(l,o),n++)}else{let a=Pt.join(i.dir,`${r}.md`);(s||!pt.existsSync(a))&&(pt.writeFileSync(a,o),n++)}}return n}async function Qo(){Gt.intro("\u{1F311} Liquid Shadow: Skills Update");let s=Gt.spinner();s.start("Deploying latest skill definitions...");let e=Yo(!0);s.stop("Done."),e>0?Gt.note(`Updated ${e} skill files across all detected targets.`,"Manifest"):Gt.note("No skill targets found (Claude Code, Cursor, Gemini CLI, Codex, Antigravity).","Manifest"),Gt.outro("\u{1F311} Skills are up to date.")}var qt=oy({transport:{target:"pino-pretty",options:{colorize:!0}}}),On="liquid-shadow",Xo="liquid-shadow-mcp";function ay(s){let e=(s||Xo).trim();return e.length>0?e:Xo}function cy(s){let e=[],t=/[^\s"']+|"([^"]*)"|'([^']*)'/g,n;for(;(n=t.exec(s))!==null;)e.push(n[1]??n[2]??n[0]??"");return e}function Xp(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 cy(e)}function Qp(s){return s.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ly(s,e){let t=`[${e.map(n=>`"${Qp(n)}"`).join(", ")}]`;return`[mcp_servers.${On}]
1432
+ command = "${Qp(s)}"
1433
+ args = ${t}`}function py(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(`
1434
+ `)?s:`${s}
1435
+ `}
1436
+ ${t}
1437
+ `;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(`
1438
+ `);return`${[...n.slice(0,i),...o,...n.slice(r)].join(`
1439
+ `).replace(/\n{3,}/g,`
1440
+
1441
+ `).trimEnd()}
1442
+ `}async function Zp(s=!1,e=!1,t=Xo,n=[]){Le.intro("\u{1F311} Liquid Shadow: Tactical Onboarding");let i=ry.homedir(),r=0,o=ay(t),a=Array.isArray(n)?n:[],c=e||await Le.confirm({message:"Deploy Autonomous Reasoning Skills? (Injects /onboard, /understand, etc.)",initialValue:!0});if(Le.isCancel(c)){Le.outro("Onboarding aborted.");return}let l=e||await Le.confirm({message:"Connect to MCP Reasoning Engines? (Claude Code, Claude Desktop, Gemini CLI, Codex)",initialValue:!0});if(Le.isCancel(l)){Le.outro("Onboarding aborted.");return}if(!c&&!l){Le.outro("No actions selected. Operational state unchanged.");return}let d=Le.spinner();d.start("Establishing intelligence assets..."),c&&(r=Yo(!0)),l&&(dy(i,o,a,!0),uy(i,o,a,!0)),d.stop("Intelligence layer established."),r>0?Le.note(`Successfully deployed ${r} tactical skills.`,"Manifest"):Le.note("No new skills deployed (up to date or scope skipped).","Manifest"),Le.outro("\u{1F311} Liquid Shadow is operational.")}function dy(s,e,t,n){let i=[{name:"Claude Code",path:fs.join(s,".claude.json"),extraFields:{type:"stdio"},createIfMissing:!1},{name:"Claude Desktop",path:fs.join(s,"Library","Application Support","Claude","claude_desktop_config.json"),createIfMissing:!1},{name:"Gemini CLI",path:fs.join(s,".gemini","settings.json"),createIfMissing:!0},{name:"Antigravity IDE",path:fs.join(s,".gemini","antigravity","mcp_config.json"),createIfMissing:!1}];for(let r of i){if(!hn.existsSync(r.path))if(r.createIfMissing)hn.mkdirSync(fs.dirname(r.path),{recursive:!0}),hn.writeFileSync(r.path,"{}");else{qt.debug(`${r.name} config not found at ${r.path}, skipping.`);continue}try{let o=JSON.parse(hn.readFileSync(r.path,"utf8"));if(o.mcpServers||(o.mcpServers={}),o.mcpServers[On]){if(!n){qt.info(`${r.name}: ${On} already configured.`);continue}qt.info(`${r.name}: updating existing ${On} configuration.`)}o.mcpServers[On]={command:e,args:t,env:{},...r.extraFields??{}},hn.writeFileSync(r.path,JSON.stringify(o,null,2)),qt.info(`Updated ${r.name} config at ${r.path}`)}catch(o){qt.error(`Failed to update ${r.name} config at ${r.path}: ${o}`)}}}function uy(s,e,t,n){let i=fs.join(s,".codex","config.toml");if(!hn.existsSync(i)){qt.debug(`Codex config not found at ${i}, skipping.`);return}try{let r=hn.readFileSync(i,"utf8"),o=`[mcp_servers.${On}]`,a=ly(e,t);if(r.includes(o)&&!n){qt.info(`Codex: ${On} already configured.`);return}let c=py(r,o,a);hn.writeFileSync(i,c),qt.info(`Updated Codex config at ${i}`)}catch(r){qt.error(`Failed to update Codex config at ${i}: ${r}`)}}import md from"path";V();import my from"fs";import ed from"path";en();var fy=new Set(["ClassDeclaration","FunctionDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","VariableDeclaration"]),td=new Set(["ClassDeclaration","ClassExpression"]);function sd(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zo(s,e,t){let n=t.trim();return!!(!n||n.length>8e3||/^\w{1,4}\s+['"].*['"];?$/.test(n)&&!n.startsWith("export ")||n.includes(`
1443
+ import `)&&!n.startsWith("import ")||e&&fy.has(e)&&s&&!new RegExp(`\\b${sd(s)}\\b`).test(n))}function hy(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(`
1444
+ `),r=et(i,s.kind);return r?r.length>800?`${r.slice(0,797)}...`:r:s.signature||""}function gy(s,e,t){if(!s)return null;let n=sd(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 yy(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 by(s){return Array.isArray(s)?s.filter(e=>e.module!=="__type_reference__"):s}function _y(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 Sy(s,e){if(!s||e!=="TsTypeAliasDeclaration"&&e!=="TsInterfaceDeclaration")return s;let t=s.indexOf(`
1445
+ export `);return t<=0?s:s.slice(0,t).trim()}function qs(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 wy(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 Ey(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 nd(s,e){let t=qs(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=Ey(s);return i?`${n} [${i}]`:void 0}async function Js(s){let{repoPath:e,filePath:t}=de(s);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=s.detailLevel||"signatures";await Q(e);let{files:i,exports:r}=L.getInstance(e),o=i.findByPath(t),a=ed.basename(t),c=/\.(ts|tsx|php|py|go)$/.test(a),l;c?l=await As(t):l={exports:r.findByFile(t),imports:[]};let d=null;if(c)try{d=my.readFileSync(t,"utf8").split(`
1446
+ `)}catch{d=null}Array.isArray(l.exports)&&d&&(l.exports=l.exports.map(h=>{let y=typeof h.signature=="string"?h.signature:"",b=h.start_line??h.line??1,g=h.end_line??h.endLine??b;if(Zo(h.name||"",h.kind,y)){let A=gy(h.name||"",h.kind,d),x=A??b,E=A?yy(x,h.kind,d):g,I=hy({name:h.name||"",kind:h.kind,signature:y,start_line:x,end_line:E},d),N=Sy(I,h.kind),P=Zo(h.name||"",h.kind,N)?_y(h.name||"",h.kind):N;return{...h,signature:P,start_line:x,end_line:E,line:x,endLine:E,members:Array.isArray(h.members)?h.members.filter(C=>{let W=typeof C.signature=="string"?C.signature:"";return!Zo(C.name||"",C.kind,W)}):h.members}}return h}));let p=wy(l.exports);l.imports=by(l.imports),n==="structure"?(delete l.content,l.exports=l.exports.map(h=>{let y=nd(h,p),b={name:h.name,kind:h.kind,line:h.start_line,classification:h.classification,...y?{displayName:y}:{},...qs(h)?{defaultTarget:qs(h)}:{}};return td.has(h.kind)&&Array.isArray(h.members)&&h.members.length>0?{...b,members:h.members.map(g=>({name:`${h.name}.${g.name}`,kind:g.kind,line:g.start_line}))}:b}),delete l.imports):n==="signatures"&&(delete l.content,l.exports=l.exports.map(h=>{let y=nd(h,p),b={name:h.name,kind:h.kind,signature:h.signature,line:h.start_line,classification:h.classification,capabilities:JSON.parse(h.capabilities||"[]"),...y?{displayName:y}:{},...qs(h)?{defaultTarget:qs(h)}:{}};return td.has(h.kind)&&Array.isArray(h.members)&&h.members.length>0?{...b,members:h.members.map(g=>({name:`${h.name}.${g.name}`,kind:g.kind,signature:g.signature,line:g.start_line}))}:b}),delete l.imports);let u=ed.relative(e,t),m=l.exports?.length||0,f="";return n==="structure"&&m>0?f=`
1447
+
1448
+ \u{1F4A1} Showing ${m} top-level symbol names. For full signatures: shadow_inspect_file({ filePath: "${u}", detailLevel: "signatures" })`:n==="signatures"&&m>0&&(f=`
1449
+
1450
+ \u{1F4A1} Showing ${m} top-level 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:vn(t,L.getInstance(e)).layer},null,2)+f}]}}Ae();V();import na from"fs";import ud from"path";import xy from"crypto";var ea="ls:sym:v1:";function id(s){if(!s)return null;let e=s.replace(/\s+/g," ").trim();return e.length>0?e:null}function rd(s){let e=id(s.signature)??"(no-signature)",t=s.parentName?.trim()||"",n=s.kind?.trim()||"",i=s.symbolName.trim();return xy.createHash("sha1").update(JSON.stringify({n:i,p:t,k:n,s:e})).digest("hex").slice(0,16)}function gr(s){let e={v:1,n:s.symbolName.trim(),h:rd(s)};s.parentName?.trim()&&(e.p=s.parentName.trim()),s.kind?.trim()&&(e.k=s.kind.trim());let t=id(s.signature);return t&&(e.s=t),s.filePath?.trim()&&(e.f=s.filePath.trim()),typeof s.startLine=="number"&&Number.isFinite(s.startLine)&&s.startLine>0&&(e.l=Math.trunc(s.startLine)),`${ea}${Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}`}function yr(s){if(!s||!s.startsWith(ea))return null;try{let e=s.slice(ea.length),t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t.v!==1||typeof t.n!="string"||!t.h?null:{symbolName:t.n,parentName:t.p??null,kind:t.k??null,signature:t.s??null,filePath:t.f??null,startLine:typeof t.l=="number"&&Number.isFinite(t.l)?t.l:null,fingerprint:t.h}}catch{return null}}function ta(s,e){let t=yr(s);return!t||t.symbolName!==e.symbolName.trim()||(t.parentName??"")!==(e.parentName?.trim()||"")||(t.kind??"")!==(e.kind?.trim()||"")?!1:t.fingerprint===rd(e)}var od=parseFloat(process.env.LIQUID_SHADOW_COST_PER_1K_TOKENS_USD??"0.003");function br(s){return s?Math.ceil(s.length/4):0}function vy(s,e=od){return Number((s/1e3*e).toFixed(6))}function Jt(s,e){let t=br(e);return{toolName:s,outputTokens:t,estimatedCostUsd:vy(t),costRateUsdPer1kTokens:od}}function hs(s,e){return s+`
1451
+
1452
+ > telemetry: ${e.toolName} output\u2248${e.outputTokens} tokens, ref_cost\u2248$${e.estimatedCostUsd.toFixed(6)}`}function ky(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 Ry(s,e){let t=ky(s.toLowerCase(),e.toLowerCase()),n=Math.max(s.length,e.length);return Math.round((n-t)/n*100)}function ad(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 Ty(s,e){let t=ad(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 Cy(s,e){return ad(e).map(i=>i[0].toLowerCase()).join("")===s.toLowerCase()}function Ay(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 Cy(s,e)?{matchType:"acronym",score:75}:Ty(s,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:Ry(s,e)*.6}}function Ks(s,e,t=50,n=5){let i=[];for(let r of e){let{matchType:o,score:a}=Ay(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)}function Iy(s,e,t){let n=s.split(`
1453
+ `),i=[],r=0;for(let p=0;p<Math.min(n.length,50);p++){let u=n[p].trim();if(u.startsWith("import ")||u.startsWith("from ")||u.startsWith("export ")&&u.includes(" from "))r=p+1;else if(u&&!u.startsWith("//")&&!u.startsWith("/*")&&!u.startsWith("*")&&u!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((p,u)=>p.startLine-u.startLine),a=0,c=0;for(let p of o)if(p.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${p.name} \u2501\u2501\u2501`);let u=n.slice(p.startLine-1,p.endLine);i.push(...u),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),c++}else{let u=p.signature||Py(n,p.startLine-1,p.kind);u&&(i.push(`${u}`),i.push(` /* implementation: ${p.lineCount} lines */`),i.push(""),a++)}let l=o[o.length-1];if(l)for(let p=l.endLine;p<n.length;p++){let u=n[p].trim();if(u==="}"||u==="};"){i.push(n[p]);break}else if(u&&!u.startsWith("//"))break}return{foldedSource:i.join(`
1454
+ `),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:c,siblingsFolded:a}}function Py(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 Ly(s,e){let t=Math.max(0,e.start_line-1),n=Math.min(s.length,Math.max(e.end_line,e.start_line)),i=s.slice(t,Math.min(n,t+18)).join(`
1455
+ `),r=e.signature?.trim();return r&&i.includes(r)?!0:i.includes(e.name)}function cd(s,e){let t=0;return e&&(s.file_path===e.filePath&&(t+=5),typeof e.startLine=="number"&&s.start_line===e.startLine&&(t+=3),(s.parent_name??null)===e.parentName&&(t+=2)),t}function ld(s,e){let t=typeof e.symbolId=="string"&&e.symbolId.trim().length>0?e.symbolId.trim():null,n=typeof e.symbolName=="string"&&e.symbolName.trim().length>0?e.symbolName.trim():null;if(t){let r=yr(t);if(r){let o=e.filePath||r.filePath||void 0,c=(r.parentName?s.exports.findMemberCandidates(r.parentName,r.symbolName,o):s.exports.findDefinitionCandidates(r.symbolName,o)).find(p=>ta(t,{symbolName:p.name,parentName:p.parent_name,kind:p.kind,signature:p.signature,filePath:p.file_path,startLine:p.start_line}));if(c)return{result:c,symbolName:r.symbolName,requestedSymbolId:t,resolutionMode:"symbol-id-exact",driftStatus:"exact"};let d=(r.parentName?s.exports.findMemberCandidates(r.parentName,r.symbolName):s.exports.findDefinitionCandidates(r.symbolName)).filter(p=>ta(t,{symbolName:p.name,parentName:p.parent_name,kind:p.kind,signature:p.signature,filePath:p.file_path,startLine:p.start_line})).sort((p,u)=>cd(u,r)-cd(p,r))[0];if(d)return{result:d,symbolName:r.symbolName,requestedSymbolId:t,resolutionMode:"symbol-id-rebound",driftStatus:"rebound"}}}if(!n)return null;let i=n.includes(".")?(()=>{let[r,o]=n.split(".");return s.exports.findMemberCandidates(r,o,e.filePath)})():s.exports.findDefinitionCandidates(n,e.filePath);return i.length===0?null:{result:i[0],symbolName:n,requestedSymbolId:t,resolutionMode:"symbol-name",driftStatus:"exact"}}function pd(s,e,t){if(e<=0)return s;let n=s.split(`
1456
+ `),i=Math.max(24,Math.floor(e/3));return n.length<=i?s:n.slice(0,i).join(`
1457
+ `)+`
1458
+
1459
+ ... (${t} folded to stay within token budget)`}function dd(s,e,t){if(!t||t<=0)return s;let n=structuredClone(s);(()=>{n.definition?.verifiedUsages?.length>3&&(n.definition.verifiedUsages=n.definition.verifiedUsages.slice(0,3)),n.verifiedUsages?.length>3&&(n.verifiedUsages=n.verifiedUsages.slice(0,3)),n.dependencies?.length>6&&(n.dependencies=n.dependencies.slice(0,6));let o=n.definition?.intelligence??n.intelligence;if(o?.related_knowledge?.length>1&&(o.related_knowledge=o.related_knowledge.slice(0,1)),o?.recent_activity)for(let a of Object.keys(o.recent_activity))o.recent_activity[a]=o.recent_activity[a].slice(0,1)})();let r=JSON.stringify(n,null,2);return br(r)<=t||(e==="full"&&n.definition?.source&&(n.definition.source=pd(n.definition.source,Math.floor(t*.35),"definition source")),e==="definition"&&n.source&&(n.source=pd(n.source,Math.floor(t*.45),"symbol source")),r=JSON.stringify(n,null,2),br(r)<=t)||(e==="full"&&(delete n.dependencies,delete n.verifiedUsages),n.definition?.intelligence&&delete n.definition.intelligence,n.intelligence&&delete n.intelligence),n}function Ny(s,e=","){let t=[],n="",i=0,r=0,o=0,a=0,c=null,l=!1;for(let p of s){if(c){if(n+=p,l){l=!1;continue}if(p==="\\"){l=!0;continue}p===c&&(c=null);continue}if(p==='"'||p==="'"||p==="`"){c=p,n+=p;continue}if(p==="("?i++:p===")"?i=Math.max(0,i-1):p==="{"?r++:p==="}"?r=Math.max(0,r-1):p==="["?o++:p==="]"?o=Math.max(0,o-1):p==="<"?a++:p===">"&&(a=Math.max(0,a-1)),p===e&&i===0&&r===0&&o===0&&a===0){let u=n.trim();u&&t.push(u),n="";continue}n+=p}let d=n.trim();return d&&t.push(d),t}function My(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 _r(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 $y(s){let t=s.trim(),n=!1;t.startsWith("...")&&(n=!0,t=t.slice(3).trim());let i=_r(t,"="),r=i>=0,o=r?t.slice(0,i).trim():t,a=r?t.slice(i+1).trim():void 0,c=_r(o,":"),l=(c>=0?o.slice(0,c):o).replace(/^(?:readonly\s+)?(?:public|private|protected)\s+/,"").trim(),d=l.includes("?"),p=l.replace(/\?/g,"").trim(),u=c>=0&&o.slice(c+1).trim()||null;return{name:p||"(anonymous)",type:u,optional:d,rest:n,hasDefault:r,...a?{defaultValue:a}:{}}}function Dy(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=_r(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=_r(t,":");return i>=0&&t.slice(i+1).replace(/\{.*$/,"").trim()||null}function Oy(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 Fy(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?My(n):null,l=n&&c?n.slice(c.start+1,c.end):"",d=l?Ny(l).map($y):[],p=n&&c?Dy(n,c.end):null,u=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:u?.[1]||null,parameters:d,parameterCount:d.length,returnType:p}}function Wy(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=Oy(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:ud.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 gs(s){let e=nn(),{repoPath:t,filePath:n,resolver:i}=de(s),r=typeof s.symbolName=="string"?s.symbolName.trim():"",o=typeof s.symbolId=="string"?s.symbolId.trim():"",a=yr(o),c=r||a?.symbolName||o,l=s.context||"definition",d=s.tokenBudget;if(n&&!i.isWithinRoot(n))return e({toolName:"shadow_inspect_symbol"}),{content:[{type:"text",text:`Error: Access denied. Path ${n} is outside the repository root.`}],isError:!0};await Q(t);let p=L.getInstance(t),u=ld(p,{...s,filePath:n});if(!u){let _=p.exports.findPotentialParents(c);if(_.length>0){let F=_.map(B=>`\`${B.name}\` (in ${i.getRelative(B.file_path)})`).join(", ");return e({toolName:"shadow_inspect_symbol"}),{content:[{type:"text",text:`Symbol "${c}" not found as a top-level export.
1460
+ However, it likely exists inside: ${F}.
1461
+ Try: shadow_inspect_symbol({ symbolName: "${_[0].name}", context: "full" }) to see the class body.`}]}}let T=p.exports.findFuzzyCandidates(c).map(F=>F.name),$=Ks(c,T,50,3);if($.length>0){let F=$.map(B=>` \u2022 \`${B.match}\` (${B.score}% match)`).join(`
1462
+ `);return e({toolName:"shadow_inspect_symbol"}),{content:[{type:"text",text:`Error: Symbol "${c}" not found in the index.
1463
+
1464
+ Suggestions:
1465
+ ${F}
1466
+
1467
+ Next steps:
1468
+ \u2022 Search semantically: shadow_search_concept({ query: "${c}" })
1469
+ \u2022 Verify repository is indexed: shadow_sync_index({ repoPath: "${t}" })`}]}}return e({toolName:"shadow_inspect_symbol"}),{content:[{type:"text",text:`Error: Symbol "${c}" not found in the index.
1470
+
1471
+ Next steps:
1472
+ \u2022 Search for it: shadow_search_concept({ query: "${c}" })
1473
+ \u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${c}", filePath: "..." })
1474
+ `}]}}let{result:m}=u,f=u.driftStatus;if(m.kind==="ExportSpecifier"||m.kind==="ExportAllDeclaration"){let _=p.imports.findImportSource(m.file_path,u.symbolName);if(_&&_.resolved_path)return e({toolName:"shadow_inspect_symbol"}),gs({...s,filePath:_.resolved_path})}let h=na.readFileSync(m.file_path,"utf8"),y=h.split(`
1475
+ `);if(!Ly(y,m)){let _=ld(p,{repoPath:t,filePath:void 0,symbolId:u.requestedSymbolId??void 0,symbolName:u.symbolName,context:l});_&&(m=_.result,f="range-repaired",h=na.readFileSync(m.file_path,"utf8"))}let b=gr({symbolName:m.name,parentName:m.parent_name,kind:m.kind,signature:m.signature,filePath:i.getRelative(m.file_path),startLine:m.start_line}),g=h.split(`
1476
+ `),w=m.end_line-m.start_line+1,A=150,x,E=!1,I=null,N=null;if(l==="definition"&&w>A){let R=p.exports.findSiblings(m.file_path).map(T=>({name:T.name,kind:T.kind,signature:T.signature||"",startLine:T.start_line,endLine:T.end_line,lineCount:T.end_line-T.start_line+1,isTarget:T.name===m.name&&T.start_line===m.start_line,parentName:T.parent_name}));if(R.length>1){I=Iy(h,{name:m.name,startLine:m.start_line,endLine:m.end_line},R);let T=i.getRelative(m.file_path);x=I.foldedSource+`
1477
+
1478
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
1479
+ \u{1F4CA} Semantic Fold Applied (context: "definition")
1480
+
1481
+ Original file: ${I.totalOriginalLines} lines
1482
+ Folded view: ${I.foldedToLines} lines
1483
+ Target Symbol: ${m.name}
1484
+ \u{1F4A1} Need more context?
1485
+ \u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${m.name}", context: "full" })
1486
+ \u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${T}", detailLevel: "signatures" })
1487
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,E=!0,N=I.foldedToLines}else{let T=g.slice(m.start_line-1,m.start_line-1+A);x=T.join(`
1488
+ `)+`
1489
+
1490
+ ... (truncated ${w-A} lines)`,E=!0,N=T.length}}else x=g.slice(m.start_line-1,m.end_line).join(`
1491
+ `);let P=m.parent_name?`${m.parent_name}.${m.name}`:m.name,C=p.exports.findHydratedById(m.id),W=m.parent_name||m.name,j=p.imports.findProxies(m.file_path).map(_=>_.file_path),K=Array.from(new Set([m.file_path,...j])),U=p.imports.findVerifiedDependents(K,W),H=Wy(U,t),M=Fy(m.signature,P,m.kind),D={symbolId:b,name:P,kind:m.kind,signature:M,file:i.getRelative(m.file_path),startLine:m.start_line,endLine:m.end_line,totalLines:w,...E&&N!==null&&{truncated:!0,previewLines:N},...I&&{semanticFold:{totalOriginalLines:I.totalOriginalLines,foldedToLines:I.foldedToLines,siblingsShown:I.siblingsShown,siblingsFolded:I.siblingsFolded}},classification:m.classification,retrieval:{requestedSymbolName:r||null,requestedSymbolId:o||null,resolutionMode:u.resolutionMode,driftStatus:f},freshness:(()=>{let _=Qt(t),R=na.statSync(m.file_path),T=_.lastIndexedAt,$=R.mtimeMs;return{lastIndexedAt:T?new Date(T).toISOString():null,lastIndexedCommit:_.lastIndexedCommit,fileMtime:new Date($).toISOString(),staleRisk:typeof T=="number"?$>T+1e3:!1}})(),callerSummary:H,source:x};if(C&&C.recent_intents&&C.recent_intents.length>0){let _={},R=Date.now();for(let T of C.recent_intents){if(T.is_crystallized&&T.type!=="crystal")continue;let $=T.created_at;$<1e10&&($*=1e3);let F=new Date($).getTime(),B=R-F,X="just now";if(B>0){let he=Math.floor(B/1e3),Ce=Math.floor(he/60),it=Math.floor(Ce/60),_e=Math.floor(it/24);_e>0?X=`${_e}d ago`:it>0?X=`${it}h ago`:Ce>0?X=`${Ce}m ago`:X=`${he}s ago`}_[T.type]||(_[T.type]=[]),_[T.type].push(`[${X}] ${T.content}`)}D.intelligence={working_set_of:C.active_missions.map(T=>`Mission #${T.id}: ${T.name}`),total_intents:C.intent_log_count,recent_activity:_}}else C&&(D.intelligence={working_set_of:C.active_missions.map(_=>`Mission #${_.id}: ${_.name}`),total_intents:C.intent_log_count,recent_activity:null});try{let{generateEmbedding:_}=await Promise.resolve().then(()=>(Ge(),vt)),R=`Symbol: ${D.name}
1492
+ Signature: ${m.signature||""}
1493
+ File: ${D.file}`,T=await _(R);if(T){let $=p.intentLogs.findSemanticMatches(T,3,m.id),F=new Promise(X=>setTimeout(()=>X([]),100)),B=await Promise.race([$,F]);B&&B.length>0&&(D.intelligence||(D.intelligence={}),D.intelligence.related_knowledge=B.map(X=>({type:X.type,content:X.content,from_symbol:X.symbol_name,similarity:`${(X.similarity*100).toFixed(0)}%`})))}}catch{}if(l==="definition"){let _=dd(D,l,d),R=JSON.stringify(_,null,2),T=Jt("shadow_inspect_symbol",R);return _.telemetry=T,e({toolName:T.toolName,outputTokens:T.outputTokens,estimatedCostUsd:T.estimatedCostUsd}),{content:[{type:"text",text:JSON.stringify(_,null,2)}]}}let O={definition:D,dependencies:p.imports.getImportsForFile(m.file_path).map(_=>({module:_.module_specifier,symbols:_.imported_symbols,relativePath:_.resolved_path?ud.relative(t,_.resolved_path):null})),callerSummary:H};O.verifiedUsages=H.topCallers;let Y=dd(O,l,d),z=JSON.stringify(Y,null,2),v=Jt("shadow_inspect_symbol",z);return Y.telemetry=v,e({toolName:v.toolName,outputTokens:v.outputTokens,estimatedCostUsd:v.estimatedCostUsd}),{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function Sr(){Ye({command:"liquid-shadow inspect",summary:"Read a symbol or file with the shared inspection logic instead of raw grep output.",usage:"liquid-shadow inspect <symbol|file> [repo] [target] [--flags]",actions:[{command:"symbol [repo] <name>",description:"Inspect a symbol by name or stable id"},{command:"file [repo] <path>",description:"Inspect a file with structure/signature detail levels"}],examples:["liquid-shadow inspect symbol . RepositoryFactory","liquid-shadow inspect symbol . --id ls:sym:v1:...","liquid-shadow inspect file . src/entry/cli/index.ts --detail signatures"]})}async function sa(s){let e=Ve(s),[t,...n]=e.positionals;if(!t||t==="help"||t==="--help"||t==="-h"){Sr();return}await ee(async()=>{let i=Oe(n[0]);if(t==="symbol"){let r=n[1],o=G(e.flags,"id","symbol-id");if(!r&&!o){Sr(),process.exitCode=1;return}let a=await gs({repoPath:i,...r?{symbolName:r}:{},...o?{symbolId:o}:{},filePath:G(e.flags,"file"),context:G(e.flags,"context"),tokenBudget:se(e.flags,["token-budget"])});console.log(""),console.log(a.content?.[0]?.text??""),console.log("");return}if(t==="file"){let r=n[1];if(!r){Sr(),process.exitCode=1;return}let o=md.isAbsolute(r)?r:md.join(i,r),a=await Js({repoPath:i,filePath:o,detailLevel:G(e.flags,"detail","detail-level")});console.log(""),console.log(a.content?.[0]?.text??""),console.log("");return}Sr(),console.error(` ${S.red("\u2716")} Unknown inspect mode: ${t}`),console.log(""),process.exitCode=1})}Ae();V();import jy from"path";async function fd(s){let e=jy.resolve(s);try{await ee(async()=>{let t=L.getInstance(e),n=At(e),i=Xn(),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",d=i.index.lastDurationMs?`${(i.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",p=i.query.avgLatencyMs?`${i.query.avgLatencyMs.toFixed(2)}ms`:"N/A",u=i.query.lastLatencyMs?`${i.query.lastLatencyMs.toFixed(2)}ms`:"N/A",m=i.index.runs>0?(i.index.cacheHits/i.index.runs*100).toFixed(1):"0.0";we("Performance Metrics",`${S.bold("Uptime")}: ${S.cyan(c)}
1494
+ ${S.bold("Indexed")}: ${Re(e)?S.green("Yes"):S.red("No")}
1495
+ ${S.bold("Files")}: ${S.cyan(t.files.getCount().toString())}
1496
+ ${S.bold("Exports")}: ${S.cyan(t.exports.getCount().toString())}
1497
+ ${S.bold("Imports")}: ${S.cyan(t.imports.getCount().toString())}
1498
+ ${S.bold("Last Indexed Commit")}: ${En(e)?S.yellow(En(e).substring(0,7)):S.red("None")}
1499
+ ${S.bold("Git Hooks")}: ${n.installed.length>0?S.green("Installed"):S.yellow("Not Installed")}`,"blue"),console.log(""),we("Index Metrics",`${S.bold("Total Runs")}: ${S.cyan(i.index.runs.toString())}
1500
+ ${S.bold("Cache Hits")}: ${S.cyan(i.index.cacheHits.toString())}
1501
+ ${S.bold("Cache Hit Rate")}: ${S.cyan(`${m}%`)}
1502
+ ${S.bold("Last Duration")}: ${S.yellow(d)}
1503
+ ${S.bold("Last Completed")}: ${S.yellow(l)}`,"cyan"),i.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${S.bold("Last Index Run Phases:")}`),i.index.lastRunPhases.forEach(f=>{let h=`${(f.durationMs/1e3).toFixed(2)}s`;console.log(` ${S.gray(f.phase.padEnd(20))} ${S.cyan(h)}`)})),console.log(""),we("Query Metrics",`${S.bold("Total Queries")}: ${S.cyan(i.query.count.toString())}
1504
+ ${S.bold("Avg Latency")}: ${S.yellow(p)}
1505
+ ${S.bold("Last Latency")}: ${S.yellow(u)}
1506
+ ${S.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?S.red(i.query.searchHistoryFailures.toString()):S.green("0")}`,"green")})}finally{await ne(e)}}V();V();q();var zy=k.child({module:"collision-service"}),wr=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=ae(this.repoPath);if(!e)return[];let{missions:t}=L.getInstance(this.repoPath),n=t.findActive(e)??[],i=new Set(n.map(l=>l.id)),r=(t.findActive()??[]).filter(l=>!i.has(l.id)),o=[],a=new Set;for(let l of r){let d=l.git_branch||"unknown",p=[e,d].sort().join("::");zy.info({branch:d,currentBranch:e,missionId:l.id},"Checking predictive collisions"),d!==e&&!a.has(p)&&(a.add(p),Sc(this.repoPath,e,d)&&o.push({branch:d,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${d}'.`}))}let c=this.analyzeMissionOverlaps([...i]);for(let l of c)o.push({branch:e,mission_id:l.missionB.id,mission_name:l.missionB.name,type:"intent",description:`Logical conflict: Mission '${l.missionA.name}' overlaps with '${l.missionB.name}'.`,conflictingFiles:l.sharedFiles});return o}analyzeMissionOverlaps(e){let t=ae(this.repoPath);if(!t)return[];let{missions:n}=L.getInstance(this.repoPath),i=n.findActive(t)??[],r=e&&e.length>0?i.filter(a=>e.includes(a.id)):i,o=[];for(let a=0;a<r.length;a+=1){let c=r[a],l=new Set(n.getWorkingSet(c.id).map(d=>d.file_path));for(let d=a+1;d<r.length;d+=1){let p=r[d],u=n.getWorkingSet(p.id).map(f=>f.file_path),m=Array.from(new Set(u.filter(f=>l.has(f)))).sort();m.length!==0&&o.push({missionA:{id:c.id,name:c.name},missionB:{id:p.id,name:p.name},sharedFiles:m})}}return o}};V();var ia=new Set(["planned","in-progress","verifying","suspended"]),Fn=class{constructor(e){this.repoPath=e}buildPlanForParent(e){let{missions:t,claims:n}=L.getInstance(this.repoPath);if(!t.findById(e))throw new Error(`Mission ${e} not found`);let o=t.findByParentId(e).filter(u=>ia.has(u.status)).map(u=>{let m=t.getWorkingSet(u.id).map(f=>f.file_path);return{id:u.id,name:u.name,status:u.status,files:m}}),a=this.computeOverlapMatrix(o),c=this.colorIntoWaves(o,a),l=new Set(o.map(u=>u.id)),d=Array.from(new Set(o.flatMap(u=>u.files))),p=n.getClaimsByFiles(d).filter(u=>!l.has(u.mission_id)).map(u=>({file_path:u.file_path,mission_id:u.mission_id,mission_name:u.mission_name,mission_status:u.mission_status,mission_branch:u.mission_branch}));return this.composePlan(o,a,p,e)}buildPlanForMissions(e,t={}){let{includeClaimCheck:n=!0}=t,{missions:i,claims:r}=L.getInstance(this.repoPath),a=i.findByIds(e).filter(d=>ia.has(d.status)).map(d=>({id:d.id,name:d.name,status:d.status,files:i.getWorkingSet(d.id).map(p=>p.file_path)})),c=this.computeOverlapMatrix(a),l=n?this.computeExternalClaims(a,r.getClaimsByFiles(Array.from(new Set(a.flatMap(d=>d.files))))):[];return this.composePlan(a,c,l)}toHandlerPayload(e){let t=new Map(e.child_missions.map(d=>[d.id,d])),n=e.waves.map(d=>({waveIndex:d.wave,missions:d.missions.map(p=>{let u=t.get(p);return{id:p,name:u?.name??`Mission ${p}`,workingSetSize:u?.file_count??0}})})),i=e.overlap_matrix.map(d=>({missionA:d.mission_a,missionB:d.mission_b,sharedFiles:d.shared_files})),r=e.external_claims.map(d=>({filePath:d.file_path,claimedByMissionId:d.mission_id,claimedByMissionName:d.mission_name,claimedByMissionStatus:d.mission_status,claimedByMissionBranch:d.mission_branch})),o=e.child_missions.length,a=n.length,c=n[0]?.missions.length??0,l=`${o} missions in ${a} waves, ${c} parallelizable in wave 1`;return{waves:n,overlapMatrix:i,externalClaims:r,summary:l}}groupMissionsForParallelism(e){let{missions:t}=L.getInstance(this.repoPath),i=t.findByIds(e).filter(o=>ia.has(o.status)).map(o=>({id:o.id,name:o.name,status:o.status,files:t.getWorkingSet(o.id).map(a=>a.file_path)})),r=this.computeOverlapMatrix(i);return this.colorIntoWaves(i,r)}composePlan(e,t,n,i){let r=this.colorIntoWaves(e,t);return{...i!==void 0?{parent_mission_id:i}:{},mission_ids:e.map(o=>o.id),child_missions:e.map(o=>({id:o.id,name:o.name,status:o.status,file_count:o.files.length})),waves:r,overlap_matrix:t,external_claims:n}}computeExternalClaims(e,t){let n=new Set(e.map(i=>i.id));return t.filter(i=>!n.has(i.mission_id)).map(i=>({file_path:i.file_path,mission_id:i.mission_id,mission_name:i.mission_name,mission_status:i.mission_status,mission_branch:i.mission_branch}))}computeOverlapMatrix(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n],r=new Set(i.files);for(let o=n+1;o<e.length;o+=1){let a=e[o],c=a.files.filter(l=>r.has(l));c.length!==0&&t.push({mission_a:i.id,mission_b:a.id,shared_files:Array.from(new Set(c)).sort()})}}return t}colorIntoWaves(e,t){if(e.length===0)return[];let n=new Map;for(let a of e)n.set(a.id,new Set);for(let a of t)n.get(a.mission_a)?.add(a.mission_b),n.get(a.mission_b)?.add(a.mission_a);let i=[...e].sort((a,c)=>{let l=(n.get(c.id)?.size??0)-(n.get(a.id)?.size??0);return l!==0?l:a.id-c.id}),r=new Map;for(let a of i){let c=new Set;for(let d of n.get(a.id)??[]){let p=r.get(d);p!==void 0&&c.add(p)}let l=1;for(;c.has(l);)l+=1;r.set(a.id,l)}let o=new Map;for(let[a,c]of r.entries()){let l=o.get(c)??[];l.push(a),o.set(c,l)}return[...o.entries()].sort((a,c)=>a[0]-c[0]).map(([a,c])=>({wave:a,missions:c.sort((l,d)=>l-d)}))}};var Er=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),d=(i[c.id]||0)/o,p=this.computeStatusBoost(c.status),u=r.has(c.id)?1:0,m=s.WEIGHTS,f=l*m.recency+d*m.activity+p*m.statusBoost+u*m.blockerBoost;return{mission:c,score:Math.round(f*1e3)/1e3,breakdown:{recency:Math.round(l*1e3)/1e3,activity:Math.round(d*1e3)/1e3,blockerBoost:u,statusBoost:p}}}).sort((c,l)=>l.score-c.score)}computeRecency(e,t){return .5**(Math.max(0,(t-e)/3600)/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();bt();import{execSync as hd}from"child_process";import Hy from"path";var xr=k.child({module:"shadow-trace"}),gn=class{intentLogs;exports;repoPath;hologramService;constructor(e){let{intentLogs:t,exports:n}=L.getInstance(e);this.intentLogs=t,this.exports=n,this.repoPath=e,this.hologramService=new be(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=hd(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
1507
+ `).filter(o=>o.trim()!=="");if(r.length===0)return;xr.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let a=Hy.join(this.repoPath,o),l=hd(`git diff -U0 ${t} -- ${o}`,{cwd:this.repoPath,encoding:"utf-8"}).matchAll(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/g);for(let d of l){let p=parseInt(d[2],10),u=this.exports.findAtLine(a,p);u&&(this.intentLogs.create({mission_id:0,file_path:a,symbol_id:u.id,type:"discovery",content:`Shadow Trace: Modified externally in ${t}`,confidence:.8,symbol_name:u.name,signature:u.signature,commit_sha:null}),xr.debug({symbol:u.name},"Logged ghost change"),n.push({from:"external",to:`${o}:${u.name}`,pattern:"git-delta",confidence:.8}))}}n.length>0&&this.hologramService.updateGhostBridges(n),xr.info("Shadow Trace complete.")}catch(i){xr.warn({err:i.message},"Shadow Trace failed: git diff error.")}}};var vr=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:c}=e,l=a??(i==="orbit"||i==="atmosphere"),d=o??(i==="orbit"?0:i==="ground"?20:10),{missions:p,intentLogs:u}=L.getInstance(this.repoPath),m=Ne(this.repoPath),f=c??ae(this.repoPath);return n==="project"?this.getProjectBriefing({altitude:i,activeMissionsLimit:r,recentActivityLimit:d,compact:l,currentBranch:f,currentCommit:m}):this.getMissionBriefing({missionId:t,altitude:i,recentActivityLimit:d,currentBranch:f,currentCommit:m})}async getProjectBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i,claims:r}=L.getInstance(t),{altitude:o,activeMissionsLimit:a,recentActivityLimit:c,compact:l,currentBranch:d,currentCommit:p}=e,u=n.findActive(d||void 0),m=u.length;a&&u.length>a&&(u=u.slice(0,a));let f=n.findParentOnlyIds(u),h=new Set(f),y=new Map;for(let R of u){if(R.parent_id==null)continue;let T=y.get(R.parent_id)??[];T.push(R),y.set(R.parent_id,T)}let b=new Set(u.map(R=>R.id)),g=r.listClaims().filter(R=>b.has(R.mission_id)).map(R=>({file_path:R.file_path,mission_id:R.mission_id,mission_name:R.mission_name,mission_status:R.mission_status,mission_branch:R.mission_branch,claimed_at:R.claimed_at,updated_at:R.updated_at})),w=new Fn(t).groupMissionsForParallelism(u.map(R=>R.id)),A=w.length,x=new Map;for(let R of g)x.set(R.mission_id,(x.get(R.mission_id)??0)+1);let E=new Map;for(let R of u)E.set(R.id,n.getWorkingSet(R.id).length);let I=u.filter(R=>h.has(R.id)?!1:!this.isOperationalUmbrellaMission(R,y,x,E)),P=new Er(i).score(I),C=.15,W=3,j=l&&P.length>W?P.filter((R,T)=>T<W||R.score>=C):P,K=j.map(R=>R.mission),U=new Map(j.map(R=>[R.mission.id,R.score])),H=R=>({id:R.id,name:R.name,goal:R.goal,status:R.status,relevance:U.get(R.id),claimedFileCount:x.get(R.id)??0}),M=R=>({...R,claimedFileCount:x.get(R.id)??0});if(o==="orbit")return{scope:"project",altitude:"orbit",counts:{...n.getStats(),active_on_branch:m},counts_scope:s.PROJECT_COUNT_SCOPE,next_work_candidates:K.map(H),parallel_wave_count:A,claims_count:g.length,meta:{current_branch:d,activeMissionsTotal:m,ember:this.getEmberLabel(t)}};let D={},O=[];for(let R of u)R.parent_id!=null?(D[R.parent_id]||(D[R.parent_id]=[]),D[R.parent_id].push(R)):O.push(R);let Y=n.findRecentCompleted(5).map(H),z=c>0?i.findRecentDecisionActivity(c):void 0,v=f.map(R=>{let T=u.find(F=>F.id===R);return{parent:l?{...M(T),strategy_graph:void 0,verification_context:void 0}:M(T),children:(D[R]??[]).map(M)}}),_=O.filter(R=>!h.has(R.id)).map(M);return{scope:"project",altitude:o||"atmosphere",counts:{...n.getStats(),active_on_branch:m},counts_scope:s.PROJECT_COUNT_SCOPE,analytics:n.getAnalytics(),hierarchy:v.length>0?v:void 0,standalone_active:_.length>0?_:void 0,active_missions:v.length===0?l?u.map(R=>({...M(R),strategy_graph:void 0})):u.map(M):void 0,claims:g,parallel_groups:w,next_work_candidates:K.map(H),recent_completed:Y,recent_activity:z,meta:{current_branch:d,current_commit:p,activeMissionsTotal:m,active_limit_applied:!!a,relevance_filtered:j.length<P.length?{shown:j.length,total:P.length}:void 0,ember:this.getEmberLabel(t)}}}getEmberLabel(e){try{let{status:t,progress:n}=Yn(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}=L.getInstance(t),{missionId:o,altitude:a,recentActivityLimit:c,currentBranch:l,currentCommit:d}=e,p;if(o?p=n.findById(o):p=n.findActive(l||void 0)[0],!p)return null;let u=null;try{p.strategy_graph&&(u=JSON.parse(p.strategy_graph))}catch{}if(a==="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 m="No external shadow changes detected.";try{new gn(t).analyzeGhostChanges(p.commit_sha||void 0),m="Shadow Trace completed: Checked for external modifications."}catch{}let f={repaired:0,failed:0};try{f=new $e(t).detectAndRepairShifts()}catch{}let h=n.getHandoffs(p.id).map(b=>{let g=null;try{g=JSON.parse(b.metadata??"")}catch{}return{artifactId:b.id,kind:b.identifier,confidence:g?.confidence??null,findingsCount:g?.findings?.length??0,risksCount:g?.risks?.length??0,missionsCreated:g?.missionsCreated??[],createdAt:b.created_at}}),y={altitude:a||"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:h,shadow_trace:{ghost_analysis:m,symbols_repaired:f.repaired,symbols_missing:f.failed},context:{current_commit:d,working_set:n.getWorkingSet(p.id).map(b=>b.file_path)},claims:r.getClaimsForMission(p.id),parallel_groups:new Fn(t).groupMissionsForParallelism(n.findActive(l||void 0).map(b=>b.id)),strategy_snapshot:u,recent_activity:a==="ground"?i.findByMission(p.id,c||20):i.findByMissionPreferCrystal(p.id,15),ancestor_activity_summary:[],predictive_collisions:[]};try{let b=new wr(t);y.predictive_collisions=await b.analyzePotentialCollisions()}catch{}if(p.parent_id){let b=a==="ground"?i.findByMission(p.parent_id,5):i.findByMissionPreferCrystal(p.parent_id,3);y.ancestor_activity_summary=b.map(g=>({type:g.type,content:g.content,date:new Date(g.created_at*1e3).toISOString()}))}return y}};q();var gd=k.child({module:"mcp:tools:ops:briefing"});async function ys(s){let{repoPath:e,scope:t="mission"}=s;gd.info({repoPath:e,missionId:s.missionId,scope:t},"Generating briefing");try{let i=await new vr(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,c=o.active_on_branch??o.active;r=a.length===0&&c===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 gd.error({error:n,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${n instanceof Error?n.message:String(n)}`)}}q();var Sd=k.child({module:"mcp:tools:ops:graph"});async function kr(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;Sd.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(_d(),bd));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw Sd.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}V();import wd from"node:path";q();var Wn=k.child({module:"mcp:tools:ops:log"}),Uy=["in-progress","verifying"],By=5;function Gy(s){for(let e of Uy){let t=s.find(n=>n.status===e);if(t)return t.id}return s[0]?.id??null}function qy(s,e){return e?wd.isAbsolute(e)?e:wd.join(s,e):null}async function Rr(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o,standalone:a}=s;Wn.info({repoPath:e,type:n,symbolName:o,standalone:a},"Logging intent");let{missions:c,exports:l,intentLogs:d}=L.getInstance(e),p=qy(e,r);try{let u=t??null,m=ae(e)||void 0;if(a)u=null,Wn.debug("Standalone intent requested; mission auto-resolution skipped");else if(u){if(!c.findById(u))throw new Error(`Mission ${u} not found. Use shadow_ops_briefing to see available missions.`)}else{let x=c.findActive(m);x.length>0?(u=Gy(x),Wn.debug({missionId:u,currentBranch:m},"Auto-resolved to active mission on current branch")):(u=null,Wn.debug({currentBranch:m},"No active mission found on current branch; logging as system/unlinked intent"))}let f=null,h=null,y=o||null,b=p,g;if(o){let x=p?l.findByNameAndFile(o,p):l.findByName(o);if(x.length===1){let E=x[0];f=E.id,h=E.signature,y=E.name,b=E.file_path||b,g={requested:o,status:"resolved",matchCount:1,resolvedSymbolId:E.id,resolvedFilePath:b}}else x.length===0?(g={requested:o,status:"not_found",matchCount:0},Wn.warn({symbolName:o,filePath:p??r},"Symbol not found for intent linking")):(g={requested:o,status:"ambiguous",matchCount:x.length,candidates:x.slice(0,By).map(E=>({id:E.id,name:E.name,kind:E.kind,file_path:E.file_path}))},Wn.warn({symbolName:o,filePath:p??r,matchCount:x.length},"Symbol resolution was ambiguous; intent left unlinked"))}let w=d.create({mission_id:u,symbol_id:f,file_path:b,type:n,content:i,confidence:1,symbol_name:y,signature:h,commit_sha:null});u&&b&&c.addToWorkingSet(u,b,f?"symbol":"intent");let A=g?g.status==="resolved"?`Intent linked to symbol "${g.requested}"`:g.status==="ambiguous"?`Intent logged without symbol link: "${g.requested}" matched ${g.matchCount} symbols`:`Intent logged without symbol link: "${g.requested}" was not found`:"Intent logged";return{content:[{type:"text",text:JSON.stringify({logId:w,missionId:u,symbolId:f,filePath:b,symbolName:y,symbolResolution:g,status:"logged",message:A},null,2)}]}}catch(u){throw Wn.error({error:u,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${u instanceof Error?u.message:String(u)}`)}}V();import kd from"node:path";import oa from"fs";import Jy from"os";import Ed from"path";q();var Tr=k.child({module:"strategy-normalizer"}),dt=class s{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(i){return Tr.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:s.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=s.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)?s.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=s.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 s.looksLikeNaturalLanguage(e)?(Tr.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 Tr.warn({verification:e},"Stripping verification rule without target"),null;if(s.looksLikeNaturalLanguage(t.target))return Tr.warn({verification:e},"Stripping natural-language verification target (not a valid pattern)"),null;let i={type:typeof t.type=="string"&&s.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=>s.sanitizeVerificationRule(n)).filter(Boolean);return t.length>0?t.length===1?t[0]:t:void 0}return s.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=s.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();var Ky=[{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"}],Vy=[{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"}],Yy=[{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"}],xd=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:Ky},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:Vy},{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:Yy}],aa=new Map(xd.map(s=>[s.id,s])),Cr=!1;function Qy(){if(Cr)return;let s=Ed.join(Jy.homedir(),".shadow","templates");if(!oa.existsSync(s)){k.debug({templatesDir:s},"Custom templates directory does not exist"),Cr=!0;return}try{let e=oa.readdirSync(s).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=Ed.join(s,t),i=oa.readFileSync(n,"utf8"),r=JSON.parse(i);if(!r.id||!r.name||!r.defaultGoal||!r.steps){k.warn({file:t,template:r},"Invalid custom template structure - skipping");continue}if(!Array.isArray(r.steps)||r.steps.length===0){k.warn({file:t},"Template has no steps - skipping");continue}if(xd.some(o=>o.id===r.id)){k.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}aa.set(r.id,r),k.info({file:t,templateId:r.id},"Loaded custom template")}catch(n){k.warn({file:t,error:n},"Failed to load custom template")}Cr=!0}catch(e){k.warn({error:e,templatesDir:s},"Failed to read custom templates directory"),Cr=!0}}function Xy(s){return Qy(),aa.get(s)}function Zy(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function vd(s,e,t={}){let n=Xy(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(aa.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=Zy(n.defaultGoal,{...t,target:i}),a=dt.normalize({steps:n.steps}),c=dt.stringify(a);return{name:r,goal:o,strategy:c}}Hs();q();var Vs=k.child({module:"mcp:tools:ops:plan"}),eb=["name","goal","strategy","parentId","outcomeContract"],tb="Mission update requires at least one updatable field: name, goal, strategy, parentId, outcomeContract.",nb="Mission requires name and goal (or templateId with optional templateVars).";async function Ar(s){let{repoPath:e,name:t,goal:n,strategy:i,workingSet:r,missionId:o,parentId:a,outcomeContract:c,templateId:l,templateVars:d}=s,{missions:p}=L.getInstance(e),u=ae(e),m=Ne(e);Vs.info({repoPath:e,name:t,missionId:o,templateId:l},"Planning mission");try{let f=t,h=n,y=i;if(!o&&l){let x=vd(l,t,d||{});f=f??x.name,h=h??x.goal,y=y??x.strategy}let b,g,w,A;if(o){let x=p.findById(o);if(!x)throw new Error(`Mission ${o} not found.`);let E;if(i!==void 0)if(i){let N=dt.normalize(i);E=dt.stringify(N);let P=dt.validate(E);P.valid||Vs.warn({errors:P.errors,strategy:i},"Strategy validation warnings detected")}else E=null;let I={commit_sha:m};if(t!==void 0&&(I.name=t),n!==void 0&&(I.goal=n),E!==void 0&&(I.strategy_graph=E),a!==void 0&&(I.parent_id=a),c!==void 0&&(I.outcome_contract=c),Object.keys(I).length===1)throw new Error(tb);p.update(o,{...I}),b=o,g=`Mission "${t??x.name}" updated.`,w=x.status,A="updated"}else{if(!f||!h)throw new Error(nb);let x=null;if(y){let E=dt.normalize(y);x=dt.stringify(E);let I=dt.validate(x);I.valid||Vs.warn({errors:I.errors,strategy:y},"Strategy validation warnings detected")}if(b=p.create({name:f,goal:h,strategy_graph:x,status:"planned",git_branch:u,commit_sha:m,parent_id:a||null,verification_context:null,outcome_contract:c||null}),r&&r.length>0){p.clearWorkingSet(Number(b));for(let E of r){let I=kd.isAbsolute(E)?E:kd.join(e,E);p.addToWorkingSet(Number(b),I,"planned")}}g=`Mission "${f}" planned.`,w="planned",A="created"}try{await new St(e).syncMissionToGitNotes(Number(b))}catch(x){Vs.info({missionId:b,...He(x)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:b,status:w,operation:A,message:g,strategy_saved:!!y,working_set_populated:r?.length||0,working_set_seeded:r?.length||0,contract_saved:!!c,updateable_fields:eb,from_template:l??void 0,commit:m},null,2)}]}}catch(f){let h=Nn(f);throw Vs.error({repoPath:e,...He(f)},"Failed to plan mission"),new Error(`Failed to plan mission: ${h}`)}}V();q();var Rd=k.child({module:"mcp:tools:ops:synthesize"});async function Ir(s){let{repoPath:e,missionId:t}=s;Rd.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=L.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new Bt(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 Rd.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}V();import Lr from"fs";import Cd from"path";q();import*as Td from"@swc/core";import{Visitor as sb}from"@swc/core/Visitor.js";var ib=k.child({module:"verification-engine"}),ca=class extends sb{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)}},Pr=class{async verify(e,t){try{let n=await Td.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new ca(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 ib.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};Hs();q();var Be=k.child({module:"mcp:tools:ops:track"});function la(s,e){return Cd.isAbsolute(e)?e:Cd.join(s,e)}function Ad(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 Id(s,e,t){let{missions:n,intentLogs:i}=L.getInstance(s),r=n.findById(e);if(!r?.parent_id)return;let o=n.findByParentId(r.parent_id);if(!o.every(d=>d.status==="completed"))return;let c=n.findById(r.parent_id);if(!c||c.status==="completed")return;Be.info({parentId:c.id,childCount:o.length},"All children completed \u2014 cascading parent completion"),n.updateStatus(c.id,"completed",t||void 0),n.clearWorkingSet(c.id);let{claims:l}=L.getInstance(s);l.releaseAllForMission(c.id),i.create({mission_id:c.id,type:"system",content:`Parent auto-completed: all ${o.length} child missions finished`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:t});try{await new Bt(s).distillMission(c.id),Be.info({parentId:c.id},"Parent Auto-Synthesis completed")}catch(d){Be.info({parentId:c.id,...He(d)},"Parent Auto-Synthesis deferred")}try{await new St(s).syncMissionToGitNotes(c.id)}catch(d){Be.info({parentId:c.id,...He(d)},"Parent Git Notes sync deferred")}await Id(s,c.id,t)}async function Nr(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:a}=s,{missions:c,intentLogs:l}=L.getInstance(e),d=Ne(e);Be.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:a?.length},"Updating mission status");try{let p=a?.length||0,u,m=0;if(a&&Array.isArray(a))for(let y of a)c.addArtifact(t,y.type,y.identifier,y.metadata);let f=[];if(o&&Array.isArray(o)&&f.push(...o),n&&i&&f.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(u=i,c.updateStatus(t,i,d||void 0),i==="completed"){c.clearWorkingSet(t);let{claims:y}=L.getInstance(e),b=y.releaseAllForMission(t);b>0&&Be.info({missionId:t,released:b},"Auto-released file claims on completion")}if(l.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:d}),i==="completed"){try{await new Bt(e).distillMission(t),Be.info({missionId:t},"Auto-Synthesis completed successfully")}catch(y){Be.info({missionId:t,...He(y)},"Auto-Synthesis deferred or failed")}await Id(e,t,d)}if(!f.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:i,top_level_status:i,operation:p>0?"status_and_artifacts_updated":"status_updated",message:Ad({topLevelStatus:i,stepUpdatesApplied:0,artifactsAdded:p}),artifacts_added:p,step_updates_applied:0,working_set_reseeded:0,commit:d},null,2)}]}}if(f.length===0&&(!a||a.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let h=[];for(let y of f){let{stepId:b,status:g,contextPivot:w}=y,A=c.findById(t);if(!A)throw new Error(`Mission ID ${t} not found`);let x=JSON.parse(A.strategy_graph||"{}"),E=null;if(Array.isArray(x)?E=x.find(I=>I.id===b):x.nodes&&Array.isArray(x.nodes)?E=x.nodes.find(I=>I.id===b):x.steps?Array.isArray(x.steps)?E=x.steps.find(I=>I.id===b):E=x.steps[b]:x[b]&&(E=x[b]),!E)throw new Error(`Step ID "${b}" not found`);if(g==="completed"&&E.verification){let I=new Pr,N=Array.isArray(E.verification)?E.verification:[E.verification];for(let P of N){let C=P;if(typeof P=="string"){if(P.trim().split(/\s+/).length>=5){Be.warn({rule:P},"Skipping natural-language verification rule");continue}C={type:"pattern",target:P}}if(!C||!C.target){Be.warn({rule:P},"Skipping invalid verification rule (missing target)");continue}if(typeof C.target=="string"&&C.target.trim().split(/\s+/).length>=5){Be.warn({rule:C},"Skipping natural-language verification target");continue}let W=C.filePath;if(W&&(W=la(e,W)),W){if(!Lr.existsSync(W))throw new Error(`Verification failed: File not found at ${W}`);let j=await I.verify(Lr.readFileSync(W,"utf8"),C);if(!j.passed)throw new Error(`Verification failed: ${j.errors.join("")}`)}else{let j=c.getWorkingSet(t),K=!1;j.length===0&&Be.warn("No working set files to verify against for rule");for(let U of j){let H=la(e,U.file_path);if(!Lr.existsSync(H))continue;if((await I.verify(Lr.readFileSync(H,"utf8"),C)).passed){K=!0;break}}if(!K)throw new Error(`Verification failed: Rule "${C.target}" not satisfied in any working set file.`)}}}if(E.status=g,c.update(t,{strategy_graph:JSON.stringify(x),commit_sha:d}),l.create({mission_id:t,type:"system",content:`Step "${b}" updated to "${g}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:d}),w){let I=w.trim();if(I.startsWith("{")||I.startsWith("["))try{let N=JSON.parse(I);if(N.files&&Array.isArray(N.files)){c.clearWorkingSet(t);for(let P of N.files)c.addToWorkingSet(t,la(e,P));m+=N.files.length}}catch(N){Be.warn({error:N},"Failed to apply context pivot")}}h.push({stepId:b,status:g})}try{await new St(e).syncMissionToGitNotes(t)}catch(y){Be.info({missionId:t,...He(y)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,...u?{top_level_status:u}:{},updates:h,artifacts_added:p,step_updates_applied:h.length,working_set_reseeded:m,operation:u&&h.length>0&&p>0?"status_steps_and_artifacts_updated":u&&h.length>0?"status_and_steps_updated":u&&p>0?"status_and_artifacts_updated":h.length>0&&p>0?"steps_and_artifacts_updated":h.length>0?"steps_updated":p>0?"artifacts_recorded":"no_changes",message:Ad({topLevelStatus:u,stepUpdatesApplied:h.length,artifactsAdded:p}),commit:d},null,2)}]}}catch(p){let u=Nn(p);throw Be.error({repoPath:e,...He(p)},"Failed to update status"),new Error(`Failed to update status: ${u}`)}}import rb from"path";var me={...S,box:we,table:ge,list:Cp};async function pa(s){let[e,...t]=s;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${me.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${me.bold("Actions: ")}`),console.log(` ${me.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${me.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${me.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${me.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${me.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${me.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await ee(async()=>{let n=t[0]?rb.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${me.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let a=await Ar({repoPath:n,name:r,goal:o}),c=JSON.parse(a.content[0].text);console.log(` ${me.green("\u2714")} Mission planned (ID: ${c.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${me.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await Nr({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${me.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...a]=t;if(!r||!o||a.length===0){console.error(` ${me.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await Rr({repoPath:n,missionId:parseInt(r),type:o,content:a.join(" ")}),console.log(` ${me.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${me.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await Ir({repoPath:n,missionId:parseInt(r)});console.log(""),me.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await kr({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i=await ys({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(me.bold(me.cyan(` Mission Dashboard: ${o.mission.name} `))),me.box("Tactical Goal",o.mission.goal,"cyan");let a=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",c=[["Status",me.bold(me[a](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];me.table(["Field","Value"],c),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${me.bold("Recent Activity:")}`),me.list(o.recent_activity.slice(0,5).map(l=>`${me.dim(`[${l.type.toUpperCase()}]`)} ${l.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import iu from"node:fs";q();var Pd=k.child({module:"mcp:tools:ops:chronicle"});async function Ld(s){let{repoPath:e,format:t="markdown",...n}=s,i=new fn(e);Pd.info({repoPath:e,format:t,filters:n},"Generating Chronicle");try{let r=await i.generateChronicle(n),o={tool:"shadow_ops_briefing",reason:"Current backlog and next work"};return t==="json"?{content:[{type:"text",text:JSON.stringify(r,null,2)}],suggestedNext:o}:{content:[{type:"text",text:i.renderChronicleMarkdown(r)}],suggestedNext:o}}catch(r){throw Pd.error({error:r,repoPath:e},"Failed to generate chronicle"),new Error(`Failed to generate chronicle: ${r instanceof Error?r.message:String(r)}`)}}V();q();import Nd from"node:path";var Md=k.child({module:"mcp:tools:ops:claim"});function ob(s,e){return Nd.isAbsolute(e)?e:Nd.join(s,e)}function $d(s,e,t){let n=e&&e.length>0?e:t?[t]:[];return Array.from(new Set(n.map(i=>ob(s,i))))}async function Dd(s){let{repoPath:e,missionId:t}=s,n=$d(e,s.filePaths,s.filePath);if(n.length===0)throw new Error("filePaths or filePath is required");let{claims:i,missions:r}=L.getInstance(e);if(!r.findById(t))throw new Error(`Mission ${t} not found`);let a=[],c=[],l=[];for(let d of n){let p=i.claimFile(d,t);if(p.status==="claimed"){a.push(d);continue}if(p.status==="already_claimed"){c.push(d);continue}l.push({file_path:d,by_mission_id:p.claim.mission_id,by_mission_name:p.claim.mission_name,by_mission_status:p.claim.mission_status,by_mission_branch:p.claim.mission_branch})}return Md.info({repoPath:e,missionId:t,requested:n.length,claimed:a.length,alreadyOwned:c.length,alreadyClaimed:l.length},"Processed file claim request"),{content:[{type:"text",text:JSON.stringify({mission_id:t,claimed:a,alreadyOwned:c,alreadyClaimed:l,requested_count:n.length,claimed_count:a.length,already_owned_count:c.length,already_claimed_count:l.length},null,2)}]}}async function Od(s){let{repoPath:e,missionId:t}=s,n=$d(e,s.filePaths,s.filePath),{claims:i,missions:r}=L.getInstance(e);if(!r.findById(t))throw new Error(`Mission ${t} not found`);let a=[],c=0;if(n.length===0)c=i.releaseAllForMission(t);else for(let l of n){let d=i.releaseFile(l,t);d.released?c+=1:a.push({file_path:l,reason:d.reason})}return Md.info({repoPath:e,missionId:t,requested:n.length,released:c,failed:a.length},"Processed file release request"),{content:[{type:"text",text:JSON.stringify({mission_id:t,released:c,releaseFailures:a,requested_count:n.length,mode:n.length===0?"release_all":"release_selected"},null,2)}]}}Ae();V();import ab from"path";bt();var cb=50,lb=50,pb=20;function db(s,e){let t=Ei(s,5e3),n=t.indexOf(e),i=n>=0?t.slice(0,n):t;if(i.length===0)return[];let r=new Set(i),{missions:o}=L.getInstance(s);return o.findAll().filter(a=>!!a.commit_sha&&r.has(a.commit_sha)).sort((a,c)=>c.updated_at-a.updated_at).slice(0,pb).map(a=>({id:a.id,name:a.name,status:a.status,git_branch:a.git_branch,commit_sha:a.commit_sha}))}function ub(s,e){if(e.length===0)return[];let t=e.map(a=>ab.resolve(s,a)),n=Array.from(new Set([...e,...t])),{exports:i}=L.getInstance(s),r=i.findByFiles(n);return Array.from(new Set(r.map(a=>a.name))).slice(0,lb)}async function Fd(s){let{repoPath:e,compact:t=!0,branch:n,includeSessionDelta:i=!1,sinceCommit:r}=s,a=new be(e).getSnapshot();t&&a.gravity?.hotspots&&(a={...a,gravity:{...a.gravity,hotspots:a.gravity.hotspots.slice(0,10),_truncated:a.gravity.hotspots.length>10,_totalHotspots:a.gravity.hotspots.length}});let c=new fn(e),l=ae(e)||void 0,d=Ne(e),p=n||l,m={...await c.generateChronicle({limit:5,compact:t,branch:p}),initiatives:[],unattached_episodes:[]},h=(await ys({repoPath:e,branch:p,scope:"project",altitude:t?"orbit":"atmosphere",compact:t,activeMissionsLimit:t?10:void 0,recentActivityLimit:t?5:10})).content?.[0],y=h&&h.type==="text"?h.text:"{}",b={};try{b=JSON.parse(y)}catch{}let g={counts:b.counts,counts_scope:b.counts_scope,next_work_candidates:b.next_work_candidates??[],active_count:Array.isArray(b.active_missions)?b.active_missions.length:0,branch_active_count:typeof b.counts?.active_on_branch=="number"?b.counts.active_on_branch:Array.isArray(b.active_missions)?b.active_missions.length:0,coordination:{claims_count:Array.isArray(b.claims)?b.claims.length:0,parallel_group_count:Array.isArray(b.parallel_groups)?b.parallel_groups.length:0}},w={hologram:a,chronicle:m,briefing:g,coordination:{activeClaims:g.coordination.claims_count,parallelWaves:g.coordination.parallel_group_count}};if(i){let A=r||En(e),x=r?"request":"index_metadata",E=A?Array.from(wc(e,A)).sort():[],I=A?ub(e,E):[],N=A?db(e,A):[];w.session_delta={baseline_commit:A||null,current_commit:d,changed_files:{count:E.length,sample:E.slice(0,cb)},changed_symbols:{count:I.length,sample:I},changed_missions:{count:N.length,sample:N}},w.meta={drift_diagnostics:{branch_scope:p||null,baseline_source:x,baseline_commit:A||null,current_commit:d,session_delta_enabled:!0,session_delta_available:!!A}}}return{content:[{type:"text",text:JSON.stringify(w,null,2)}],suggestedNext:{tool:g.next_work_candidates.length>0?"shadow_ops_track":"shadow_ops_plan",reason:g.next_work_candidates.length>0?"Pick one from next_work_candidates and run /continue":"No open work; create a mission"}}}V();q();var Wd=k.child({module:"mcp:tools:ops:crystallize"}),mb=4,jd=140;function fb(s){let e=s.replace(/\s+/g," ").trim();return e.length<=jd?e:`${e.slice(0,jd-1).trimEnd()}...`}function hb(s){let e=new Set,t=[];for(let n of s){let i=fb(n);!i||e.has(i)||(e.add(i),t.push(i))}return t}function Ys(s,e){let t=hb(e);if(t.length===0)return null;let n=t.slice(0,mb),i=t.length-n.length,r=i>0?` (+${i} more)`:"";return`${s} (${n.length}/${t.length}${r}): ${n.join(" | ")}`}function gb(s){let e=new Map;for(let t of s)e.set(t,(e.get(t)??0)+1);return[...e.entries()].sort((t,n)=>t[0].localeCompare(n[0])).map(([t,n])=>`${t}(${n})`).join(", ")}function zd(s){let{scope:e,id:t,name:n,logs:i,structured:r}=s,o=new Set(i.map(l=>l.symbol_name).filter(Boolean)),a=[Ys("Decisions",r.decisions),Ys("Context",r.context),Ys("Consequences",r.consequences),Ys("Recommendations",r.recommendations),Ys("Other Notes",r.unclassified)].filter(l=>typeof l=="string"),c=[`[Crystal] ${e} #${t}: ${n}`];return e==="Mission"?c.push(`Summarizes ${i.length} logs across ${o.size} symbols.`):c.push(`Summarizes ${i.length} standalone insights.`),c.push(`Types: ${gb(i.map(l=>l.type))}`),a.length>0&&(c.push(""),c.push(...a)),c.join(`
1508
+ `).trim()}async function Hd(s){let{repoPath:e,missionId:t,symbolId:n}=s;Wd.info({repoPath:e,missionId:t,symbolId:n},"Crystallizing logs");let{intentLogs:i,missions:r,exports:o}=L.getInstance(e);if(typeof t=="number"){let a=r.findById(t);if(!a)throw new Error(`Mission ${t} not found`);let c=i.findCrystalByMission(t),l=i.findRawByMission(t);if(l.length===0)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:c?"already_crystallized":"no_logs",message:c?"Mission already has a crystal with no new raw logs to absorb.":"No raw intent logs found for this mission.",crystalId:c?.id??null},null,2)}]};let d=new Ut,p=i.findCrystallizableByMission(t),u=d.analyze(p),m=zd({scope:"Mission",id:t,name:a.name,logs:p,structured:u}),f=i.crystallize(t,m,c?.id);return Wd.info({missionId:t,crystalId:f,absorbed:l.length,operation:c?"updated_existing":"created"},"Crystallization complete"),{content:[{type:"text",text:JSON.stringify({missionId:t,crystalId:f,absorbed:l.length,sourceLogCount:p.length,symbolsCompressed:new Set(p.map(h=>h.symbol_name).filter(Boolean)).size,status:"crystallized",operation:c?"updated_existing":"created",existingCrystalId:c?.id??null},null,2)}]}}if(typeof n=="number"){let a=o.findHydratedById(n);if(!o.findById(n))throw new Error(`Symbol ${n} not found in index`);let l=i.findCrystalBySymbol(n),d=i.findRawBySymbol(n);if(d.length===0)return{content:[{type:"text",text:JSON.stringify({symbolId:n,status:l?"already_crystallized":"no_logs",message:l?"Symbol already has a crystal with no new raw logs to absorb.":"No raw standalone intent logs found for this symbol.",crystalId:l?.id??null},null,2)}]};let p=new Ut,u=i.findCrystallizableBySymbol(n),m=p.analyze(u),f=zd({scope:"Symbol",id:n,name:a?.name||"Unknown",logs:u,structured:m}),h=i.crystallizeBySymbol(n,f,l?.id);return{content:[{type:"text",text:JSON.stringify({symbolId:n,crystalId:h,absorbed:d.length,sourceLogCount:u.length,status:"crystallized",operation:l?"updated_existing":"created",existingCrystalId:l?.id??null},null,2)}]}}throw new Error("Must provide either missionId or symbolId to crystallize.")}V();var yb=4,Ud=180;function bb(s){let e=s.replace(/\s+/g," ").trim();return e.length<=Ud?e:`${e.slice(0,Ud-1).trimEnd()}...`}function _b(s){let e=new Set,t=[];for(let n of s){let i=bb(n);!i||e.has(i)||(e.add(i),t.push(i))}return t}function Qs(s,e){let t=_b(e);if(t.length===0)return null;let n=t.slice(0,yb),i=t.length-n.length,r=i>0?` (+${i} more)`:"";return`${s} (${n.length}/${t.length}${r}): ${n.join(" | ")}`}function Sb(s){let e=new Map;for(let t of s)e.set(t,(e.get(t)??0)+1);return[...e.entries()].sort((t,n)=>t[0].localeCompare(n[0])).map(([t,n])=>`${t}(${n})`).join(", ")}var Xs=class extends Error{constructor(t,n){super(`Found ${n} mission-scoped non-crystal log${n===1?"":"s"} for theme "${t}". At least 2 are required to create a thematic crystal.`);this.theme=t;this.matchedLogCount=n;this.name="InsufficientThematicMatchesError"}},Mr=class{constructor(e){this.repoPath=e}async crystallizeByTheme(e,t){let{generateEmbedding:n}=await Promise.resolve().then(()=>(Ge(),vt)),i=await n(e);if(!i)throw new Error("Embedding generation failed \u2014 cannot perform thematic crystallization");let{intentLogs:r}=L.getInstance(this.repoPath),o=await r.findSemanticTheme(i,t?.missionIds,t?.limit??200);if(o.length<2)throw new Xs(e,o.length);let c=new Ut().analyze(o),l=c.sourceMissions.length,d=`[Crystal:Theme] ${e}
1509
+ `;d+=`Matched ${o.length} mission-scoped logs across ${l} mission${l!==1?"s":""}.
1510
+ `,d+=`Types: ${Sb(o.map(m=>m.type))}`;let p=[Qs("Decisions",c.decisions),Qs("Context",c.context),Qs("Consequences",c.consequences),Qs("Recommendations",c.recommendations),Qs("Other Notes",c.unclassified)].filter(Boolean);return p.length>0&&(d+=`
1511
+
1512
+ ${p.join(`
1513
+ `)}`),{crystalId:r.crystallizeTheme(e,o.map(m=>m.id),d.trim()),absorbed:o.length,sourceMissions:c.sourceMissions,summary:d.trim()}}};async function Bd(s){let{repoPath:e,theme:t,missionIds:n,limit:i}=s;if(!t||typeof t!="string"||t.trim().length===0)return{isError:!0,content:[{type:"text",text:"theme must be a non-empty string"}]};try{let r=new Mr(e),{crystalId:o,absorbed:a,sourceMissions:c,summary:l}=await r.crystallizeByTheme(t.trim(),{missionIds:n,limit:i});return{content:[{type:"text",text:JSON.stringify({status:"crystallized",crystalId:o,absorbed:a,sourceMissions:c,summary:l,theme:t.trim()},null,2)}]}}catch(r){return r instanceof Xs?{content:[{type:"text",text:JSON.stringify({status:"insufficient_matches",theme:t.trim(),matchedLogCount:r.matchedLogCount,message:r.message,eligibility:"Only mission-scoped non-crystal intent logs are eligible for thematic crystallization."},null,2)}]}:{isError:!0,content:[{type:"text",text:r.message}]}}}q();var wb=k.child({module:"mcp:tools:ops:dispatch-plan"});async function Gd(s){let{repoPath:e,parentMissionId:t,missionId:n,missionIds:i,includeClaimCheck:r=!0}=s,o=t??n,a=Array.isArray(i)&&i.length>0;if(!a&&o===void 0)throw new Error("Provide parentMissionId, missionId, or a non-empty missionIds array");wb.info({repoPath:e,parentMissionId:o,missionIds:i,includeClaimCheck:r},"Building dispatch plan");let c=new Fn(e),l=a?c.buildPlanForMissions(i,{includeClaimCheck:r}):o!==void 0?c.buildPlanForParent(o):c.buildPlanForMissions([],{includeClaimCheck:r}),d=c.toHandlerPayload(l);return{content:[{type:"text",text:JSON.stringify(d,null,2)}]}}V();var Eb=["recon_report","risk_assessment","impact_map","debt_scan","custom"],qd=["low","medium","high","critical"];function xb(s){return typeof s=="number"&&Number.isFinite(s)&&s>=0&&s<=1}async function Jd(s){let{repoPath:e,missionId:t,kind:n,findings:i,risks:r=[],missionsCreated:o=[],gaps:a=[],confidence:c,agentTag:l}=s;if(!Array.isArray(i)||i.length===0)throw new Error("findings must be a non-empty array");for(let[h,y]of i.entries()){if(!y||typeof y.statement!="string"||y.statement.trim().length===0)throw new Error(`findings[${h}].statement must be a non-empty string`);if(!xb(y.confidence))throw new Error(`findings[${h}].confidence must be a number between 0 and 1`)}for(let[h,y]of r.entries()){if(!y||typeof y.description!="string"||y.description.trim().length===0)throw new Error(`risks[${h}].description must be a non-empty string`);if(!qd.includes(y.severity))throw new Error(`risks[${h}].severity must be one of ${qd.join(", ")}`)}let d=Eb.includes(n)?n:"custom",p=c!=null&&c>=0&&c<=1?c:.5,u={kind:d,findings:i.map(h=>({statement:h.statement,confidence:h.confidence,refs:h.refs})),risks:r.map(h=>({severity:h.severity,description:h.description,refs:h.refs})),missionsCreated:o,gaps:a,confidence:p,...l?{agentTag:l}:{}},{missions:m}=L.getInstance(e);if(typeof t=="number"&&!m.findById(t))throw new Error(`Mission ${t} not found`);let f=m.addHandoff(t??null,u);return{content:[{type:"text",text:JSON.stringify({status:"written",artifactId:f,missionId:t??null,kind:d,findingsCount:i.length,risksCount:r.length,missionsCreated:o,confidence:p},null,2)}]}}V();async function Kd(s){let{repoPath:e,missionId:t,kind:n,query:i,limit:r}=s,{missions:o}=L.getInstance(e),a;if(i)try{let{generateEmbedding:l}=await Promise.resolve().then(()=>(Ge(),vt)),d=await l(i);d?a=await o.findSemanticHandoffs(d,{missionId:t,kind:n,limit:r??5}):a=o.getHandoffs(t,n,r??20)}catch{a=o.getHandoffs(t,n,r??20)}else a=o.getHandoffs(t,n,r??20);let c=a.map(l=>{let d=null;try{d=JSON.parse(l.metadata??"")}catch{}return{artifactId:l.id,missionId:l.mission_id??null,kind:l.identifier,createdAt:l.created_at,payload:d,similarity:l.similarity??null}});return{content:[{type:"text",text:JSON.stringify({handoffs:c,total:c.length},null,2)}]}}Ae();import Vd from"fs";import $r from"path";q();var da=k.child({module:"mcp:tools:ops:health"});async function Yd(s){let e=s.repoPath,t=$r.isAbsolute(e)?$r.normalize(e):$r.resolve(process.cwd(),e);da.info({repoPath:t},"Health check");let n=!1,i=!1;try{n=Vd.statSync(t).isDirectory(),i=n&&Vd.existsSync($r.join(t,".git"))}catch(h){da.debug({repoPath:t,error:h},"Health: repository path check failed")}let r=!1,o=!1,a=null,c=null;if(n&&i)try{ye(t),r=!0,o=Re(t);let h=Qt(t);a=h.lastIndexedCommit,c=h.lastIndexedAt?new Date(h.lastIndexedAt).toISOString():null}catch(h){da.debug({repoPath:t,error:h},"Health: DB check failed")}let l=Xn(),d;if(r)try{let h=Yn(t);if(h.status!=="idle"){let[y,b]=h.progress.split("/").map(Number),g=b>0?Math.round(y/b*100):0,w=h.status==="done"?"symbols: fully embedded":h.status==="running"?`symbols: warming ${h.progress} (${g}%)`:`symbols: ${h.status} ${h.progress}`;d={...h,label:w}}}catch{}let p=n&&i?(()=>{let h=At(t);return{managed:Fp().length,installed:h.installed.length,missing:h.missing.length,foreign:h.foreign.length,disabled:h.disabled.length,degraded:h.notInstalled.length>0,statuses:h.statuses}})():void 0,m={status:!n||!i?"repo_unavailable":r?o?p?.degraded?"degraded":"ready":"index_pending":"db_unavailable",repository:{path:t,exists:n,is_git_repo:i},database:r,indexed:o,last_indexed_commit:a,last_indexed_at:c,...d?{ember:d}:{},...p?{hooks:p}:{},metrics_scope:"process",metrics:{index:l.index,query:l.query,uptimeMs:l.uptimeMs}},f=!n||!i||!r?{tool:"shadow_env_diagnose",reason:"Verify repository path, git, hooks, and DB health"}:o?p?.degraded?{tool:"shadow_env_hooks",reason:"Repair degraded managed git hooks"}:{tool:"shadow_recon_hologram",reason:"Architecture overview"}:{tool:"shadow_recon_onboard",reason:"Index the repo first"};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],suggestedNext:f}}Ae();V();import Pb from"node:crypto";Ae();Kt();import{spawn as vb}from"node:child_process";import{existsSync as Qd}from"node:fs";import ma from"node:os";import{dirname as kb,resolve as Rb}from"node:path";import{fileURLToPath as Tb}from"node:url";var Xd=Tb(import.meta.url),Cb=kb(Xd),Ab=ma.constants.priority.PRIORITY_LOWEST??ma.constants.priority.PRIORITY_LOW;function Ib(){if(Xd.endsWith(".ts"))return null;let s=Rb(Cb,"../../entry/tribunal/index.js");if(Qd(s))return s;let e=je("dist/entry/tribunal/index.js");return Qd(e)?e:null}function ua(s,e,t,n,i="initializing"){ye(s).prepare(`INSERT OR REPLACE INTO tribunal_state (
1514
+ session_id,
1515
+ mission_id,
1516
+ repo_path,
1517
+ status,
1518
+ phase,
1519
+ pid,
1520
+ started_at,
1521
+ completed_at
1522
+ ) VALUES (?, ?, ?, 'running', ?, ?, unixepoch(), NULL)`).run(t,e,s,i,n)}function Zd(s,e,t){let n=Ib();if(!n)return ua(s,e,t,null,"source_mode"),{launched:!1,pid:null,mode:"source_mode"};let i=vb(process.execPath,[n,s,String(e),t],{detached:!0,stdio:"ignore",env:{...process.env,TRIBUNAL_MODE:"1"}});if(i.pid==null)return ua(s,e,t,null),{launched:!1,pid:null,mode:"detached_daemon"};try{ma.setPriority(i.pid,Ab)}catch{}return i.unref(),ua(s,e,t,i.pid),{launched:!0,pid:i.pid,mode:"detached_daemon"}}function eu(s,e){try{let n=ye(s).prepare(`SELECT session_id, mission_id, status, phase, artifact_id, started_at, completed_at
1523
+ FROM tribunal_state
1524
+ WHERE session_id = ?`).get(e);return n?{sessionId:n.session_id,missionId:n.mission_id,status:n.status??"running",phase:n.phase??"initializing",artifactId:n.artifact_id??null,startedAt:n.started_at??null,completedAt:n.completed_at??null}:null}catch{return null}}function Lb(s){if(!s)return null;try{return JSON.parse(s)}catch{return null}}function Nb(s,e,t){if(t)return t;if(!e)return null;try{return ye(s).prepare(`SELECT session_id
1525
+ FROM tribunal_state
1526
+ WHERE mission_id = ?
1527
+ ORDER BY started_at DESC
1528
+ LIMIT 1`).get(e)?.session_id??null}catch{return null}}function Mb(s,e){let n=ye(s).prepare("SELECT metadata FROM mission_artifacts WHERE id = ?").get(e);return Lb(n?.metadata??null)}function $b(s){if(!s)return null;let e=Array.isArray(s.risks)?s.risks:[],t=Array.isArray(s.findings)?s.findings:[],n=s.verdict==="solid"||s.verdict==="needs_revision"?s.verdict:e.some(r=>r.severity==="high"||r.severity==="critical")?"needs_revision":"solid",i=typeof s.summary=="string"&&s.summary.trim().length>0?s.summary:t[0]?.statement??"No summary available.";return{verdict:n,confidence:s.confidence,summary:i}}function Db(s,e,t){return s==="completed"?e?"Tribunal completed and produced a risk assessment handoff.":t!=null?"Tribunal completed, but the handoff artifact metadata could not be loaded.":"Tribunal completed without a persisted risk assessment handoff artifact.":e?"Tribunal failed. Partial handoff is available with gaps.":t!=null?"Tribunal failed, and the handoff artifact metadata could not be loaded.":"Tribunal failed and did not produce a readable handoff artifact."}async function tu(s){let{repoPath:e,missionId:t}=s,{missions:n}=L.getInstance(e);if(!n.findById(t))throw new Error(`Mission ${t} not found`);let r=Pb.randomUUID(),o=Zd(e,t,r);return{content:[{type:"text",text:JSON.stringify({sessionId:r,missionId:t,status:o.launched?"running":"initialized",mode:o.mode,message:o.launched?`Tribunal convened for Mission ${t}. Running in background.`:`Tribunal session initialized for Mission ${t}. Detached spawn is unavailable in source mode, so no background daemon was launched.`},null,2)}]}}async function nu(s){let{repoPath:e,missionId:t,sessionId:n}=s;if(!n&&t==null)throw new Error("Provide sessionId or missionId for tribunal status lookup");let i=Nb(e,t,n);if(!i)return{content:[{type:"text",text:JSON.stringify({sessionId:null,missionId:t??null,status:"not_found",message:t!=null?`No tribunal session found for mission ${t}. Run shadow_ops_tribunal_submit first to start a session.`:"No tribunal session found for the provided identifier."},null,2)}]};let r=eu(e,i);if(!r)return{content:[{type:"text",text:JSON.stringify({sessionId:i,missionId:t??null,status:"not_found",message:"No tribunal session found for the provided identifier."},null,2)}]};if(r.status==="running")return{content:[{type:"text",text:JSON.stringify({sessionId:r.sessionId,missionId:r.missionId,status:r.status,phase:r.phase,message:r.phase==="source_mode"?"Tribunal session is recorded in source mode, but detached daemon execution is unavailable until the built runtime is used.":`Tribunal is currently in the ${r.phase} review phase.`},null,2)}]};let o=r.artifactId?Mb(e,r.artifactId):null,a=$b(o);return{content:[{type:"text",text:JSON.stringify({sessionId:r.sessionId,missionId:r.missionId,status:r.status,phase:r.phase,artifactId:r.artifactId,verdict:a,handoff:o,message:Db(r.status,o,r.artifactId)},null,2)}]}}V();q();import Dr from"path";var Ob=k.child({module:"mcp:tools:ops:working-set-check"});async function su(s){let{repoPath:e,filePaths:t}=s,{missions:n,claims:i}=L.getInstance(e),r=n.findActive(),o=[],a=t.map(d=>Dr.isAbsolute(d)?d:Dr.join(e,d));for(let d of r){let p=n.getWorkingSet(d.id);for(let u of p)if(t.includes(u.file_path))o.push({file_path:u.file_path,mission_id:d.id,mission_name:d.name});else{let m=Dr.isAbsolute(u.file_path)?u.file_path:Dr.join(e,u.file_path);for(let f of a)if(m===f){o.push({file_path:u.file_path,mission_id:d.id,mission_name:d.name});break}}}let l=i.getClaimsByFiles(a).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,claimed_at:d.claimed_at,updated_at:d.updated_at}));return Ob.info({repoPath:e,conflictsCount:o.length,claimConflicts:l.length},"Working set check completed"),{content:[{type:"text",text:JSON.stringify({conflicts:o,claims:l},null,2)}]}}function Lt(){Ye({command:"liquid-shadow ops",summary:"Thin CLI bridge for the MCP ops suite. This exposes the real ops tools without inventing a separate model.",usage:"liquid-shadow ops <action> [repo] [args] [--flags]",actions:[{command:"plan",description:"shadow_ops_plan"},{command:"track",description:"shadow_ops_track"},{command:"log",description:"shadow_ops_log"},{command:"briefing",description:"shadow_ops_briefing"},{command:"synthesize",description:"shadow_ops_synthesize"},{command:"chronicle",description:"shadow_ops_chronicle"},{command:"context",description:"shadow_ops_context"},{command:"health",description:"shadow_ops_health"},{command:"graph",description:"shadow_ops_graph"},{command:"crystallize",description:"shadow_ops_crystallize"},{command:"crystallize-theme",description:"shadow_ops_crystallize_theme"},{command:"claim",description:"shadow_ops_claim"},{command:"release",description:"shadow_ops_release"},{command:"dispatch-plan",description:"shadow_ops_dispatch_plan"},{command:"tribunal-submit",description:"shadow_ops_tribunal_submit"},{command:"tribunal-status",description:"shadow_ops_tribunal_status"},{command:"handoff",description:"shadow_ops_handoff"},{command:"handoff-read",description:"shadow_ops_handoff_read"},{command:"working-set-check",description:"shadow_working_set_check"}],examples:["liquid-shadow ops health .","liquid-shadow ops context . --session-delta","liquid-shadow ops claim . --mission 12 src/entry/cli/index.ts","liquid-shadow ops handoff-read . --kind risk_assessment --limit 3"],notes:["Structured inputs can be passed directly with repeated JSON flags like --finding-json and --risk-json."]})}function Te(s){console.log(""),console.log(s),console.log("")}function Or(s){return s.map(e=>JSON.parse(e))}function fa(s){return s.flatMap(e=>e.split(",")).map(e=>Number(e.trim())).filter(e=>Number.isFinite(e))}function Qe(s){return se(s,["mission","mission-id"])}function Fb(s,e,t=!0){if(e.length===0)return{repoPath:Oe(void 0),rest:[]};if(!t)return{repoPath:Oe(e[0]),rest:e.slice(1)};let[n,...i]=e;try{if(iu.existsSync(n)&&iu.statSync(n).isDirectory())return{repoPath:Oe(n),rest:i}}catch{}return(s==="health"||s==="context"||s==="briefing"||s==="chronicle"||s==="graph")&&(n.startsWith(".")||n.startsWith("/")||n.includes(Wb()))?{repoPath:Oe(n),rest:i}:{repoPath:Oe(void 0),rest:e}}function Wb(){return process.platform==="win32"?"\\":"/"}async function ru(s){let e=Ve(s),[t,...n]=e.positionals;if(!t||t==="help"||t==="--help"||t==="-h"){Lt();return}let i=Fb(t,n),r=i.repoPath,o=i.rest;await ee(async()=>{try{switch(t){case"plan":{let[a,c]=o,l=await Ar({repoPath:r,missionId:Qe(e.flags),name:a??G(e.flags,"name"),goal:c??G(e.flags,"goal"),parentId:se(e.flags,["parent","parent-id"]),outcomeContract:G(e.flags,"outcome-contract"),templateId:G(e.flags,"template"),strategy:G(e.flags,"strategy"),workingSet:Ue(e.flags,"working-set"),templateVars:Object.fromEntries(Ue(e.flags,"template-var").map(d=>{let[p,...u]=d.split("=");return[p,u.join("=")]}))});Te(l.content[0]?.text??"");return}case"track":{let a=Qe(e.flags);if(!a){Lt(),process.exitCode=1;return}let c=await Nr({repoPath:r,missionId:a,stepId:G(e.flags,"step","step-id"),status:G(e.flags,"status"),contextPivot:G(e.flags,"context-pivot"),updates:Or(Ue(e.flags,"update-json")),artifacts:Or(Ue(e.flags,"artifact-json"))});Te(c.content[0]?.text??"");return}case"log":{let a=G(e.flags,"content")??o.join(" ").trim(),c=G(e.flags,"type");if(!a||!c){Lt(),process.exitCode=1;return}let l=await Rr({repoPath:r,missionId:Qe(e.flags),type:c,content:a,filePath:G(e.flags,"file"),symbolName:G(e.flags,"symbol"),standalone:re(e.flags,["standalone"])});Te(l.content[0]?.text??"");return}case"briefing":{let a=await ys({repoPath:r,missionId:Qe(e.flags),scope:G(e.flags,"scope"),altitude:G(e.flags,"altitude"),activeMissionsLimit:se(e.flags,["active-limit","active-missions-limit"]),recentActivityLimit:se(e.flags,["recent-limit","recent-activity-limit"]),compact:re(e.flags,["compact"]),branch:G(e.flags,"branch")});Te(a.content[0]?.text??"");return}case"synthesize":{let a=Qe(e.flags)??Number(o[0]);if(!Number.isFinite(a)){Lt(),process.exitCode=1;return}let c=await Ir({repoPath:r,missionId:a});Te(c.content[0]?.text??"");return}case"chronicle":{let a=await Ld({repoPath:r,format:G(e.flags,"format"),limit:se(e.flags,["limit"]),offset:se(e.flags,["offset"]),branch:G(e.flags,"branch"),since:se(e.flags,["since"]),until:se(e.flags,["until"])});Te(a.content[0]?.text??"");return}case"context":{let a=await Fd({repoPath:r,compact:re(e.flags,["compact"],!0),branch:G(e.flags,"branch"),includeSessionDelta:re(e.flags,["session-delta","include-session-delta"]),sinceCommit:G(e.flags,"since-commit")});Te(a.content[0]?.text??"");return}case"health":{let a=await Yd({repoPath:r});Te(a.content[0]?.text??"");return}case"graph":{let a=Ip(e.flags,["json","mermaid"],"format"),c=await kr({repoPath:r,missionId:Qe(e.flags),format:a,depth:se(e.flags,["depth"]),limit:se(e.flags,["limit"])});Te(c.content[0]?.text??"");return}case"crystallize":{let a=await Hd({repoPath:r,missionId:Qe(e.flags),symbolId:se(e.flags,["symbol-id"])});Te(a.content[0]?.text??"");return}case"crystallize-theme":{let a=G(e.flags,"theme")??o.join(" ").trim();if(!a){Lt(),process.exitCode=1;return}let c=await Bd({repoPath:r,theme:a,missionIds:fa(Ue(e.flags,"missions","mission-ids")),limit:se(e.flags,["limit"])});Te(c.content[0]?.text??"");return}case"claim":{let a=Qe(e.flags);if(!a){Lt(),process.exitCode=1;return}let c=await Dd({repoPath:r,missionId:a,filePaths:o,agentTag:G(e.flags,"agent-tag")});Te(c.content[0]?.text??"");return}case"release":{let a=Qe(e.flags);if(!a){Lt(),process.exitCode=1;return}let c=await Od({repoPath:r,missionId:a,filePaths:o});Te(c.content[0]?.text??"");return}case"dispatch-plan":{let a=await Gd({repoPath:r,parentMissionId:se(e.flags,["parent","parent-mission-id"]),missionId:Qe(e.flags),missionIds:fa(Ue(e.flags,"missions","mission-ids")),includeClaimCheck:re(e.flags,["claim-check","include-claim-check"],!0)});Te(a.content[0]?.text??"");return}case"tribunal-submit":{let a=Qe(e.flags);if(!a){Lt(),process.exitCode=1;return}let c=await tu({repoPath:r,missionId:a});Te(c.content[0]?.text??"");return}case"tribunal-status":{let a=await nu({repoPath:r,missionId:Qe(e.flags),sessionId:G(e.flags,"session","session-id")});Te(a.content[0]?.text??"");return}case"handoff":{let a=G(e.flags,"kind");if(!a){Lt(),process.exitCode=1;return}let c=[...Ue(e.flags,"finding").map(p=>({statement:p,confidence:.5})),...Or(Ue(e.flags,"finding-json"))],l=[...Ue(e.flags,"risk").map(p=>{let[u,...m]=p.split(":");return{severity:u,description:m.join(":").trim()}}),...Or(Ue(e.flags,"risk-json"))],d=await Jd({repoPath:r,missionId:Qe(e.flags),kind:a,findings:c,risks:l,missionsCreated:fa(Ue(e.flags,"missions-created")),gaps:Ue(e.flags,"gap","gaps"),confidence:se(e.flags,["confidence"]),agentTag:G(e.flags,"agent-tag")});Te(d.content[0]?.text??"");return}case"handoff-read":{let a=await Kd({repoPath:r,missionId:Qe(e.flags),kind:G(e.flags,"kind"),query:G(e.flags,"query"),limit:se(e.flags,["limit"])});Te(a.content[0]?.text??"");return}case"working-set-check":{let a=await su({repoPath:r,filePaths:o});Te(a.content[0]?.text??"");return}default:Lt(),console.error(` ${S.red("\u2716")} Unknown ops action: ${t}`),console.log(""),process.exitCode=1}}finally{await ne(r)}})}bt();async function ou(s){let{repoPath:e,compact:t=!1}=s,i=new be(e).getSnapshot();if(t&&i.gravity?.hotspots){let a=i.gravity.hotspots.length;i={...i,gravity:{...i.gravity,hotspots:i.gravity.hotspots.slice(0,20),_truncated:a>20,_totalHotspots:a}}}let o=!!(i.topography||i.gravity||i.ghosts)?{tool:"shadow_ops_chronicle",reason:"Recent decisions and ADRs"}:{tool:"shadow_recon_onboard",reason:"Initialize repository intelligence to populate hologram sections"};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],suggestedNext:o}}V();Ge();import Nt from"path";bt();V();q();var yn=k.child({module:"clean-sweep"}),ha=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=L.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){yn.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();yn.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++,yn.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,yn.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 yn.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},ga=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)}))}},ya=class{missions;constructor(e){let{missions:t}=L.getInstance(e);this.missions=t}findColdMissions(){let e=Math.floor(Date.now()/1e3)-604800,t=this.missions.findColdMissions(e,10);return yn.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},bs=class{pruner;scorer;compactor;constructor(e){this.pruner=new ha(e),this.scorer=new ga,this.compactor=new ya(e)}runMaintenance(){yn.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return yn.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};en();q();async function au(s){let{repoPath:e}=s;k.info({repoPath:e},"Setting up repository..."),k.info({repoPath:e}," Ensuring index is up-to-date...");let t=Date.now();await Q(e,void 0,!1,!0,_=>{let R=_.total>0?Math.round(_.current/_.total*100):0;k.info({phase:_.phase,progress:`${_.current}/${_.total}`,percentage:`${R}%`},_.message||`Indexing progress: ${_.phase}`)});let i=((Date.now()-t)/1e3).toFixed(1);k.info({repoPath:e,indexTime:`${i}s`}," Index check complete"),await qn();let r="";try{let _=ur({repoPath:e,enableAutoRefresh:!0,enableSymbolHealing:!0});_.errors.length>0&&k.warn({repoPath:e,errors:_.errors},"Git hook install had non-fatal errors"),r=`
1529
+ ## Git Hooks
1530
+ * Installed: ${_.installed.length}, skipped: ${_.skipped.length}, errors: ${_.errors.length}
1531
+ `}catch(_){k.warn({repoPath:e,error:_ instanceof Error?_.message:String(_)},"Git hook installation failed (non-fatal)"),r=`
1532
+ ## Git Hooks
1533
+ * Installation failed (non-fatal). Run \`shadow_env_hooks\` manually.
1534
+ `}let o=L.getInstance(e);k.info({repoPath:e},"Populating Project Hologram...");let a=new be(e),c=kt(o,e);a.updateTopography(c);let l=a.computeGravityZones();a.updateGravityZones(l),k.info({repoPath:e,sections:2},"Project Hologram populated (topography + gravity)");let d=o.files.getCount(),p=o.exports.getCount(),u=o.configs.getAll(),m=o.files.getTopDirectories(e),f=[],h=[],y="Standalone",b=_=>o.files.findPackageJsonChildren(_),g=_=>{let R=Nt.join(_,"package.json"),T=u.filter(X=>X.file_path===R),$=[],F=X=>T.some(he=>he.key.startsWith("dep: ")&&he.key.includes(X));F("react")&&$.push("React"),F("vue")&&$.push("Vue"),F("next")&&$.push("Next.js"),F("fastify")&&$.push("Fastify"),F("express")&&$.push("Express"),F("nestjs")&&$.push("NestJS"),(F("prisma")||F("typeorm"))&&$.push("DB");let B=T.find(X=>X.key==="description")?.value||"";return{stack:$.join(", "),description:B.length>80?B.substring(0,77)+"...":B}},w=Nt.join(e,"apps"),A=Nt.join(e,"packages"),x=Nt.join(e,"services"),E=o.files.hasFilesPattern(w+"/%"),I=o.files.hasFilesPattern(A+"/%"),N=o.files.hasFilesPattern(x+"/%"),P=(_,R)=>{let T=b(_);T.length>0&&(f.push(`| **${R}/ (Directory)** | \uFE0F **DO NOT SUMMARIZE FULL DIR** | |`),T.forEach($=>{let F=Nt.dirname($.path),B=Nt.basename(F);if(B.startsWith("_")||B.includes("template"))return;let X=Nt.relative(e,F),he=g(F);f.push(`| \u2514\u2500 \`${X}\` | ${he.stack||"Module"} | ${he.description} |`),h.push(X)}))};E||I||N?(y="Monorepo",P(w,"apps"),P(x,"services"),P(A,"packages")):m.forEach(_=>{let R=_.root;if(!R||R.startsWith("."))return;let T=g(Nt.join(e,R));f.push(`| \`${R}/\` | ${T.stack||"Module"} | ${T.description} |`)});let C=Nt.join(e,"package.json"),j=u.find(_=>_.key==="name"&&_.kind==="Service"&&_.file_path===C)?.value||Nt.basename(e),K=u.filter(_=>_.kind==="Service"&&(_.key.startsWith("service:")||_.file==="docker-compose.yml")),U=[...new Set(K.map(_=>_.value).filter(_=>_&&typeof _=="string"&&!_.includes("[object Object]")&&!["postgres","redis","db","worker","undefined"].includes(_.toLowerCase())))],H=U.slice(0,5),M=H.length>0?`Service Cluster: ${H.join(", ")}${U.length>5?` (+${U.length-5} others)`:""}`:"",D=d<100?"small":"large",O=D==="small"?"You can safely use `shadow_recon_tree` to view the full tree.":' **AVOID summarizing large directories like `apps/` or `services/` as a whole.**\n Instead, look for a specific component in the map below and use `shadow_recon_tree({ subPath: "apps/my-app" })` on it.\n\uFE0F **Prefer Search:** Use `shadow_search_symbol` for directly finding symbols.',Y="";try{let R=new $e(e).detectAndRepairShifts(),T=new gn(e),$=o.missions.findLastMission();T.analyzeGhostChanges($?.commit_sha||void 0),o.intentLogs.countByType("heritage")===0&&new Qn(e).analyzeHeritage(20);let B=o.intentLogs.countByType("heritage"),X=o.intentLogs.countByType("discovery");B>0||X>0||R.repaired>0?Y=`
1535
+ ## Shadow Engine Insights
1536
+ `+(B>0?`* **Architectural Heritage**: Bootstrapped ${B} significant historical moves.
1537
+ `:"")+(X>0?`* **Recent Changes**: Detected ${X} external modifications.
1538
+ `:"")+(R.repaired>0?`* **Symbol Healing**: Automatically repaired ${R.repaired} orphaned intent links.
1539
+ `:""):Y=`
1540
+ ## Shadow Engine Status: **Active**
1541
+ * **Integrity**: Git River matches Symbol Index.
1542
+ * **Heritage**: Ready to track developer intent.
1543
+ `}catch(_){Y=`
1544
+ ## Shadow Engine Status: **Offline**
1545
+ * Error: ${_ instanceof Error?_.message:"Unknown"}
1546
+ `}try{let R=new bs(e).runMaintenance();(R.pruning.deleted>0||R.pruning.converted>0)&&(Y+=`
1547
+ ### Clean Sweep Cycle
1548
+ * **Pruned**: ${R.pruning.deleted} orphaned logs deleted, ${R.pruning.converted} converted to lapsed.
1549
+ `+(R.compaction.eligible>0?`* **Compaction**: ${R.compaction.eligible} cold missions eligible for briefing synthesis.
1550
+ `:""))}catch(_){k.warn({error:_},"Metabolism maintenance failed")}let z="";try{let _=o.missions.findActiveByPriority();_?z=`
1551
+ ## Active Mission: **${_.name}** (#${_.id})
1552
+ * Use \`shadow_ops_briefing\` to resume context.
1553
+ `:z=`
1554
+ ## Mission Status: **Idle**
1555
+ * No active mission. Use \`shadow_ops_plan\` to begin task tracking.
1556
+ `}catch{}return{content:[{type:"text",text:`
1557
+ # Repository Indexed: ${j}
1558
+
1559
+ \u23F1\uFE0F **Index synchronization completed in ${i}s** (full scan on first run, incremental sync on reruns)
1560
+
1561
+ ## \u{1F3D7}\uFE0F Architecture: ${y}
1562
+ ${M?`> ${M}
1563
+ `:""}
1564
+
1565
+ ${Y}
1566
+ ${r}
1567
+ ${z}
1568
+
1569
+ This is a ${D} repository with ${d} files.
1570
+
1571
+ ## System Overview
1572
+ | Statistic | Value |
1573
+ |-----------|-------|
1574
+ | Total Files | ${d} |
1575
+ | Exported Symbols | ${p} |
1576
+ | Primary Stack | ${c.primaryStack} |
1577
+
1578
+ ## Component Map
1579
+ | Component | Tech Stack | Description |
1580
+ |-----------|------------|-------------|
1581
+ ${f.length>20?f.slice(0,20).join(`
1582
+ `)+`
1583
+ | ... | ... | (*${f.length-20} more components hidden*) |`:f.join(`
1584
+ `)}
1585
+
1586
+ ## Recommended Exploration Strategy
1587
+ ${O}
1588
+
1589
+ ## \uFE0F Quick Reference
1590
+ | Goal | Tool | Example |
1591
+ |------|------|---------|
1592
+ | Search for code | \`shadow_search_symbol\` | \`shadow_search_symbol({ query: "ProductController" })\` |
1593
+ | Explore a *specific* component | \`shadow_recon_tree\` | \`shadow_recon_tree({ subPath: "apps/admin" })\` |
1594
+ | Trace data flow | \`shadow_analyze_flow\` | \`shadow_analyze_flow({ filePath: "apps/admin/src/Admin.tsx" })\` |
1595
+ | Find config/env | \`shadow_search_config\` | \`shadow_search_config({ key: "DATABASE_URL" })\` |
1596
+
1446
1597
  ---
1598
+ **Ready.** What would you like to investigate first?
1599
+ `}]}}V();import jn from"path";bt();en();function Fr(s,e){return(jn.isAbsolute(e)?jn.relative(s,e):e).replace(/^\.?[\\/]/,"")}async function cu(s){let{repoPath:e}=s;await Q(e);let t=L.getInstance(e),n=kt(t,e),r=new be(e).getSnapshot(),o=[],a=[],c=Object.values(n.layers.Entry.topFiles).map(u=>u.path),l=new Set(Object.values(n.layers.Data.topFiles).map(u=>u.path));for(let u of c){let m=jn.isAbsolute(u)?u:jn.join(e,u),f=t.imports.findByFile(m);for(let h of f)h.resolved_path&&l.has(jn.relative(e,h.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${Fr(e,u)}\` directly imports Data layer \`${Fr(e,h.resolved_path)}\`. Should go through Logic.`)}let d=r.gravity?.hotspots||[];for(let u of d){let m=vn(u.filePath,t);(m.layer==="Utility"||m.layer==="Unknown")&&u.gravity>50&&a.push(`\u{1F6A8} GRAVITY ANOMALY: \`${Fr(e,u.filePath)}\` has high gravity (${u.gravity.toFixed(0)}) but is classified as ${m.layer}. Review for boundary drift and central coupling.`)}for(let u of c){let m=jn.isAbsolute(u)?u:jn.join(e,u),f=t.exports.findTopLevelByFile(m);f.length>10&&a.push(`\u{1F388} ENTRY BLOAT: \`${Fr(e,u)}\` exports ${f.length} symbols. Entry handlers should be thin interfaces.`)}let p=`# \u{1F575}\uFE0F Architectural Scout Report
1600
+
1601
+ `;return o.length===0&&a.length===0?p+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
1602
+ `:(o.length>0&&(p+=`## \u274C Structural Violations
1603
+ `,o.forEach(u=>p+=`- ${u}
1604
+ `),p+=`
1605
+ `),a.length>0&&(p+=`## \u26A0\uFE0F Architectural Warnings
1606
+ `,a.forEach(u=>p+=`- ${u}
1607
+ `),p+=`
1608
+ `)),{content:[{type:"text",text:p}]}}V();bt();en();function lu(s){switch(s){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}";case"Unknown":return"\u2753"}}async function pu(s){let{repoPath:e}=s;await Q(e);let t=L.getInstance(e),n=kt(t,e);new be(e).updateTopography(n);let r=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],o=`# \u{1F3D7}\uFE0F Architecture Summary
1609
+
1610
+ `;if(o+=`## Detected Pattern: **${n.pattern}**
1611
+ `,o+=`Confidence: ${n.patternConfidence.toFixed(0)}%
1612
+
1613
+ `,n.insights.length>0){o+=`## Insights
1614
+ `;for(let c of n.insights)o+=`- ${c}
1615
+ `;o+=`
1616
+ `}o+=`## Layer Distribution
1617
+
1618
+ `,o+=`| Layer | Files | % of Total |
1619
+ `,o+=`|-------|------:|:----------:|
1620
+ `;let a=r.reduce((c,l)=>c+n.layers[l].count,0);for(let c of r){let l=n.layers[c],d=a>0?(l.count/a*100).toFixed(1):"0.0",p=lu(c);o+=`| ${p} ${c} | ${l.count} | ${d}% |
1621
+ `}o+=`
1622
+ ## Top Files by Layer
1623
+
1624
+ `;for(let c of r){let l=n.layers[c];if(l.count===0)continue;let d=lu(c);if(o+=`### ${d} ${c} (${l.count} files)
1625
+ `,l.topFiles.length>0)for(let p of l.topFiles)o+=`- \`${p.path}\` (${p.confidence}% conf)
1626
+ `,p.signals.length>0&&(o+=` - ${p.signals.join("; ")}
1627
+ `);else o+=`- _No files classified with high confidence_
1628
+ `;o+=`
1629
+ `}return o+=`---
1630
+ `,o+=`**Next Steps:**
1631
+ `,o+="- Use `shadow_inspect_file` to explore files in each layer\n",o+="- Use `shadow_analyze_flow` to trace execution from Entry \u2192 Logic \u2192 Data\n",o+="- Use `shadow_analyze_deps` to understand layer boundaries\n",{content:[{type:"text",text:o}],suggestedNext:{tool:"shadow_recon_tree",reason:"Explore a subPath or use shadow_inspect_file"}}}async function du(s){let{repoPath:e,subPath:t,maxDepth:n=5}=s,i=5e4,r=[{level:"signatures",depth:n},{level:"summaries",depth:n,meta:{warning:"Export lists omitted for token efficiency.",action:"Use 'shadow_inspect_file' on specific files to see exports."}},{level:"structure",depth:n,meta:{warning:"Detailed signatures omitted due to repo size.",action:"Use 'shadow_inspect_file' on specific files to see details."}},{level:"summaries",depth:2,meta:{warning:"Repository is large. Showing top 2 levels with summaries only.",action:"Use 'shadow_recon_tree' with a 'subPath' to explore deeper."}},{level:"structure",depth:2,meta:{warning:"Repository is large. Showing top 2 levels structure only.",action:"Use 'shadow_recon_tree' with a 'subPath' to explore."}},{level:"lite",depth:1,meta:{warning:"Repository is massive. Showing root files only.",action:"Use 'shadow_recon_tree' with a 'subPath' to explore."}}];for(let o of r){let a=await ms(e,5,o.level,t,o.depth);o.meta&&(a._meta=o.meta);let c=JSON.stringify(a,null,2);if(c.length<=i)return{content:[{type:"text",text:c}]}}return{content:[{type:"text",text:`Warning: The repository at ${t||"root"} is massive (exceeds ${i} chars even at minimal depth).
1632
+ Please use 'shadow_recon_tree' with a more specific 'subPath' or use 'shadow_search_symbol' to find what you need.`}]}}function jb(s){try{return JSON.parse(s)}catch{return null}}function uu(){Ye({command:"liquid-shadow recon",summary:"Thin CLI bridge for the MCP recon suite.",usage:"liquid-shadow recon <onboard|topography|scout|tree|hologram> [dir] [--flags]",actions:[{command:"onboard [dir]",description:"Initialize or refresh the repo baseline"},{command:"topography [dir]",description:"Summarize architectural layers"},{command:"scout [dir]",description:"Run drift and anomaly scouting"},{command:"tree [dir]",description:"Run the MCP tree view from the recon suite"},{command:"hologram [dir]",description:"Show a compact project snapshot for humans"}],examples:["liquid-shadow recon onboard .","liquid-shadow recon topography .","liquid-shadow recon scout .","liquid-shadow recon tree . --depth 2","liquid-shadow recon hologram . --compact"],notes:["`recon init` is kept as an alias for `recon onboard` for compatibility."]})}function Zs(s){console.log(""),console.log(s),console.log("")}function zb(s){let e=jb(s);if(!e||Array.isArray(e)){Zs(s);return}let t=typeof e.metadata=="object"&&e.metadata?e.metadata:{},n=typeof e.topography=="object"&&e.topography?e.topography:{},i=typeof e.gravity=="object"&&e.gravity?e.gravity:{},r=Array.isArray(i.hotspots)?i.hotspots:[];console.log(""),console.log(` ${S.bold(String(t.repoPath??"Project hologram"))} ${S.dim(`updated ${String(t.lastUpdated??"n/a")}`)}`),console.log(` ${S.dim("Pattern:")} ${String(n.pattern??"unknown")} ${S.dim("Confidence:")} ${String(n.patternConfidence??"n/a")}%`),r.length>0&&ge(["Hotspot","File","Gravity"],r.slice(0,10).map(o=>{let a=o;return[String(a.symbol??""),String(a.filePath??""),String(a.gravity??"")]})),console.log("")}async function ba(s){let e=Ve(s),[t,n]=e.positionals;if(!t||t==="help"||t==="--help"||t==="-h"){uu();return}let i=t==="init"?"onboard":t,r=Oe(n??G(e.flags,"dir","d"));await ee(async()=>{switch(i){case"onboard":{let o=await au({repoPath:r});Zs(o.content[0]?.text??"");return}case"topography":{let o=await pu({repoPath:r});Zs(o.content[0]?.text??"");return}case"scout":{let o=await cu({repoPath:r});Zs(o.content[0]?.text??"");return}case"tree":{let o=await du({repoPath:r,subPath:G(e.flags,"subpath","sub-path"),maxDepth:se(e.flags,["depth","max-depth"])});Zs(o.content[0]?.text??"");return}case"hologram":{let o=await ou({repoPath:r,compact:re(e.flags,["compact"],!0)});zb(o.content[0]?.text??"");return}default:uu(),process.exitCode=1}})}import zn from"path";V();V();Ge();var Hb={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},wt=class s{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?s.mapClassificationToTier(t):s.classify(e);return Hb[n]}};bt();V();q();var mu=k.child({module:"lineage-service"}),ei=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=Ei(this.repoPath,e);if(t.length===0)return[];let{missions:n}=L.getInstance(this.repoPath),r=n.findByCommitShas(t).map(o=>o.id);return r.length>0&&mu.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return mu.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var bn=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(`
1633
+ `),o=new Array(r.length).fill(0);for(let u=0;u<r.length;u++){let m=r[u].toLowerCase(),f=0,h=0;for(let y of i)m.includes(y)&&(f++,h++);(m.includes("export ")||m.includes("class ")||m.includes("function ")||m.includes("interface "))&&(f+=1),o[u]=h*10+f}let a=0,c=-1,l=5;for(let u=0;u<=r.length-l;u++){let m=0;for(let f=0;f<l;f++)m+=o[u+f];m>c&&(c=m,a=u)}if(c<=0)return e.slice(0,n).trim()+"...";let p=r.slice(a,a+l).join(`
1634
+ `).trim();return a>0&&(p=`...
1635
+ `+p),a+l<r.length&&(p=p+`
1636
+ ...`),p.length>n?p.slice(0,n)+"...":p}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}};q();var Mt=class s{constructor(e){this.repoPath=e}get filesRepo(){return L.getInstance(this.repoPath).files}get exportsRepo(){return L.getInstance(this.repoPath).exports}get intentLogsRepo(){return L.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?wt.mapClassificationToTier(i):wt.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?ze.FILTERED_QUERY_LIMIT_MULTIPLIER:1),qe.MAX_LIMIT)).map(g=>({...g,source:"path",keywordHits:this.countPathKeywordHits(g.path,a),relevance:this.scorePathResult(g.path,a,"path",c)}));r&&(l=l.filter(g=>s.matchesFilters(g.path,i,g.mtime,g.classification))),c&&a.length>=3&&(l=l.filter(g=>g.source==="symbol"||g.keywordHits>=2));let d=this.findSymbolBackedPaths(e,a,t*3),p=new Set(l.map(g=>g.path));for(let g of d){if(p.has(g))continue;let w=this.filesRepo.findByPath(g);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)}),p.add(g)))}l.sort((g,w)=>w.relevance-g.relevance),r||(l=l.slice(0,Math.min(t*4,qe.MAX_LIMIT)));let u=l.length;if(u===0)return{content:[{type:"text",text:`No indexed files match path/filename: "${e}".
1637
+
1638
+ If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`}]};let m=g=>g.replace(this.repoPath,"").replace(/^\//,"");if(o){let w=new be(this.repoPath).getSection("gravity"),A=new Map;if(w?.hotspots)for(let C of w.hotspots){let W=A.get(C.filePath)||0;A.set(C.filePath,W+C.gravity)}let x=l.map(C=>{let W=A.get(C.path)||0,j=C.classification?wt.mapClassificationToTier(C.classification):wt.classify(C.path);return{...C,gravity:W,layer:j}});x.sort((C,W)=>W.gravity!==C.gravity?W.gravity-C.gravity:W.relevance!==C.relevance?W.relevance-C.relevance:C.path.localeCompare(W.path));let E=x.slice(n,n+t),I=n+t<u;if(E.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${u}.`}]};let N=I?`
1639
+ > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"";return{content:[{type:"text",text:`# Resolved paths: "${e}" (Ranked by Gravity)
1447
1640
 
1448
- # Workspace
1641
+ Showing ${E.length} of ${u} file(s) (offset: ${n}, limit: ${t})${N}
1449
1642
 
1450
- Manage multi-repository workspaces and cross-repo mission links using the Shadow Engine.
1643
+ `+E.map((C,W)=>{let j=C.gravity>50?" \u269B\uFE0F":C.gravity>0?" \u2022":"",K=C.gravity>0?` [G:${Math.round(C.gravity)}]`:"",U=C.source==="symbol"?" [via symbol]":"";return`${n+W+1}. \`${m(C.path)}\` (${C.layer})${j}${K}${U}`}).join(`
1644
+ `)+`
1451
1645
 
1452
- ## Core calls
1646
+ > **Legend**: \u269B\uFE0F = High-gravity hotspot (>50), \u2022 = Has gravity, G = Gravity score`}]}}let f=l.slice(n,n+t),h=n+t<u;if(f.length===0)return{content:[{type:"text",text:`No results at offset ${n}. Total matches: ${u}.`}]};let y=h?`
1647
+ > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"";return{content:[{type:"text",text:`# Resolved paths: "${e}"
1453
1648
 
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? })\`
1649
+ Showing ${f.length} of ${u} file(s) (offset: ${n}, limit: ${t})${y}
1462
1650
 
1463
- ## After fusion
1651
+ `+f.map((g,w)=>{let A=g.source==="symbol"?" [via symbol]":"";return`${n+w+1}. \`${m(g.path)}\`${g.classification?` (${g.classification})`:""}${A}`}).join(`
1652
+ `)}]}}async searchByConcept(e,t,n,i,r,o=!1,a){k.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let c=await to(e),l=A=>A.replace(this.repoPath,"").replace(/^\//,""),d=bn.extractKeywords(e),p=this.classifyConceptQuery(e,d),u=this.getConceptConfidenceFloor(p.profile),m=this.getIntentConfidenceFloor(p.profile),f=Math.min(Math.max((t+n)*2,t),qe.MAX_LIMIT),h=await this.findConceptMatches(e,c,i,r,f,0),y=c?await this.findIntentLogMatches(c,5):[],b=h.filter(A=>(A.score||0)>=u),g=h.filter(A=>(A.score||0)<u),w=y.filter(A=>(A.score||0)>=m);if(b.length>0){let A=b.length,x=b.slice(n,n+t),I=n+t<A?`
1653
+ > **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",N=o?`
1654
+ > _Compact mode: snippets omitted_`:A>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",P=a&&a>0?`
1655
+ > _Adaptive compression enabled under token budget._`:"",C=g.length>0?`
1656
+ > _${g.length} lower-confidence candidate(s) were suppressed below the ${Math.round(u*100)}% evidence floor._`:"",W=`# Semantic Concept Search: "${e}"
1464
1657
 
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 })\`
1658
+ Showing ${x.length} of ${A} file(s) above the ${Math.round(u*100)}% evidence floor (offset: ${n}, limit: ${t})${I}${N}${P}${C}
1468
1659
 
1469
- ## Rules
1660
+ `,K=new be(this.repoPath).getSection("gravity"),U=new Map;if(K?.hotspots)for(let O of K.hotspots)U.set(O.filePath,O.gravity);let H=x.map((O,Y)=>{let z=l(O.path),v=Math.round((O.score||0)*100),R=U.get(O.path)?" \u269B\uFE0F":"";return`${n+Y+1}. \`${z}\`${R} (${v}% evidence) - ${O.summary||"No summary"}`}),M=x.map((O,Y)=>{let z=l(O.path),v=Math.round((O.score||0)*100),_=U.get(O.path),R=_?" \u269B\uFE0F **CORE**":"",T=_&&_>50?`
1661
+ > \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${_.toFixed(0)}). Modifications may have significant architectural impact.`:"",$=`## ${n+Y+1}. ${z}${R} (${v}% Evidence Match)
1662
+ > **Rationale**: ${O.rationale}${T}
1470
1663
 
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(`
1476
- `)?s:`${s}
1477
- `}
1478
- ${t}
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(`
1480
- `);return`${[...n.slice(0,i),...o,...n.slice(r)].join(`
1481
- `).replace(/\n{3,}/g,`
1664
+ `+(O.snippet?`**Matched Snippet**:
1665
+ \`\`\`typescript
1666
+ ${O.snippet}
1667
+ \`\`\`
1482
1668
 
1483
- `).trimEnd()}
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();
1669
+ `:"")+`**Summary**: ${O.summary||"No summary available"}
1670
+ `;return{index:n+Y+1,relativePath:z,matchPct:v,gravity:_,text:$}}),D="";if(o)D=W+H.join(`
1671
+ `);else if(a&&a>0){let O=Math.max(80,Math.floor(a*.12)),Y=this.estimateTokenCount(W),z=[],v=[];for(let _ of M){let R=this.estimateTokenCount(_.text),T=Y+R<=a-O;if(z.length<2||T)z.push(_.text),Y+=R;else{let $=_.gravity?" \u269B\uFE0F":"";v.push(`${_.index}. \`${_.relativePath}\`${$} (${_.matchPct}% Evidence Match)`)}}D=W+z.join(`
1672
+ `),v.length>0&&(D+=`
1673
+
1674
+ ### Folded Lower-Relevance Matches (${v.length})
1675
+ _Expanded blocks omitted to stay within token budget._
1676
+ `+v.join(`
1677
+ `))}else D=W+M.map(O=>O.text).join(`
1678
+ `);if(w.length>0){let O=`
1679
+
1680
+ ---
1681
+ ## Intent Vectors (${w.length} matching decision(s))
1682
+
1683
+ `+w.map((z,v)=>{let _=Math.round((z.score||0)*100),R=z.symbolName?` \`${z.symbolName}\``:"",T=z.missionId?` [Mission #${z.missionId}]`:"",$=z.content.length>200?z.content.slice(0,200)+"...":z.content;return o?`${v+1}. **[${z.type}]**${R}${T} (${_}%) - ${$}`:`### ${v+1}. [${z.type}]${R}${T} (${_}% Evidence Match)
1684
+ > ${$}
1685
+ `}).join(`
1686
+ `),Y=`
1687
+
1688
+ ---
1689
+ ## Intent Vectors (${w.length} matching decision(s))
1690
+
1691
+ `+w.slice(0,2).map((z,v)=>{let _=Math.round((z.score||0)*100),R=z.symbolName?` \`${z.symbolName}\``:"",T=z.missionId?` [Mission #${z.missionId}]`:"";return`${v+1}. **[${z.type}]**${R}${T} (${_}%)`}).join(`
1692
+ `)+(w.length>2?`
1693
+ > Additional intent matches folded by token budget.`:"");a&&a>0&&this.estimateTokenCount(D+O)>a?D+=Y:D+=O}return{content:[{type:"text",text:D}]}}if(n===0){let A=this.filesRepo.getStats(),x=e.toLowerCase().split(/\s+/),E=this.filesRepo.findByPathKeywords(x,t);if(r&&(E=E.filter(I=>s.matchesFilters(I.path,i,I.mtime,I.classification))),E.length>0)return{content:[{type:"text",text:`# Concept Search: "${e}"
1694
+
1695
+ \u26A0\uFE0F No semantic matches cleared the ${Math.round(u*100)}% evidence floor (${A.withSummary}/${A.total} summaries indexed).
1696
+
1697
+ Found ${E.length} file(s) with matching paths:
1698
+
1699
+ `+E.map((N,P)=>`${P+1}. \`${l(N.path)}\` (${N.classification||"Unknown"})`).join(`
1700
+ `)}]};if(g.length>0){let I=g.slice(0,Math.min(3,t)).map((N,P)=>{let C=Math.round((N.score||0)*100);return`${P+1}. \`${l(N.path)}\` (${C}% evidence) - ${N.summary||"No summary"}`}).join(`
1701
+ `);return{content:[{type:"text",text:`# Semantic Concept Search: "${e}"
1702
+
1703
+ No semantic matches cleared the evidence floor (${Math.round(u*100)}% required for ${p.profile} queries).
1704
+
1705
+ Low-confidence candidates were suppressed instead of being presented as relevant matches:
1706
+ ${I?`
1707
+ ${I}
1708
+
1709
+ `:`
1710
+ `}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}"
1711
+
1712
+ Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}async searchBySymbol(e,t,n,i,r,o="any"){let a=e.toLowerCase(),c=C=>C.replace(this.repoPath,"").replace(/^\//,""),l=this.buildFtsQuery(e,o),d;try{d=this.exportsRepo.findFts(l,t+50)}catch{d=this.exportsRepo.findByPartialName(e,t+50)}if(d.length===0){let C=this.exportsRepo.getAllNames(5e3),W=e.trim().split(/\s+/).filter(K=>K.length>0);if(W.length>1){let K=new Map;for(let H of W){let M=Ks(H,C,40,20);for(let D of M){let O=K.get(D.match);O?(O.terms.push(H),O.bestScore=Math.max(O.bestScore,D.score)):K.set(D.match,{terms:[H],bestScore:D.score})}}let U=Array.from(K.entries()).sort((H,M)=>M[1].terms.length!==H[1].terms.length?M[1].terms.length-H[1].terms.length:M[1].bestScore-H[1].bestScore).slice(0,10);if(U.length>0){let H=U.map(([M,D])=>{let O=D.terms.join(", ");return` \u2022 \`${M}\` (matches: ${O}, ${Math.round(D.bestScore)}%)`}).join(`
1713
+ `);return{content:[{type:"text",text:`No symbols found matching all terms: "${e}"
1714
+
1715
+ **Partial matches:**
1716
+ ${H}
1717
+
1718
+ \u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let K=Ks(e,C,50,5);if(K.length>0){let U=K.map(H=>` \u2022 \`${H.match}\` (${Math.round(H.score)}% ${H.matchType} match)`).join(`
1719
+ `);return{content:[{type:"text",text:`No symbols found matching: "${e}"
1720
+
1721
+ **Did you mean?**
1722
+ ${U}
1723
+
1724
+ \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}"
1725
+
1726
+ \u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(d=d.filter(C=>{let W=this.filesRepo.findByPath(C.file_path);return s.matchesFilters(C.file_path,i,W?.mtime,W?.classification)}));let p=new ei(this.repoPath),u=new be(this.repoPath),m=p.getAncestorMissionIds(),f=ae(this.repoPath)||void 0,h=this.exportsRepo.getGravityMap(m,f),y=u.getSection("gravity"),b=new Map;if(y?.hotspots)for(let C of y.hotspots)b.set(`${C.filePath}::${C.symbol}`,C.gravity);let g="\u{1F525}",w="\u26A1",A="\u269B\uFE0F",x=d.map((C,W)=>{let j=h[C.id],K=b.get(`${C.file_path}::${C.name}`),U=this.filesRepo.findByPath(C.file_path),H=wt.getMultiplier(C.file_path,U?.classification),M=(ze.SCORE_BASE-W)*H;j&&(M+=j.score*ze.SCORE_BASE),K&&(M+=K*ze.SCORE_BASE*ze.GRAVITY_STRUCTURAL_WEIGHT),C.name.toLowerCase()===a&&(M+=ze.EXACT_MATCH_BONUS*H);let D=U?.mtime;if(D!=null){let Y=D>1e10?D/1e3:D,z=(Date.now()/1e3-Y)/io.SECONDS_PER_DAY;z<ze.RECENT_FILE_THRESHOLD_DAYS?M+=ze.RECENT_FILE_BOOST:z<ze.OLDER_FILE_THRESHOLD_DAYS&&(M+=ze.OLDER_FILE_BOOST)}let O=[];return j&&O.push(...j.reasons),K&&O.push(`Structural Hotspot (Gravity: ${K.toFixed(1)})`),{...C,activeGravity:j,structuralGravity:K,sortScore:M,reasons:O}}).sort((C,W)=>W.sortScore-C.sortScore).slice(n,n+t),E=d.length,I=n+t<E,N=x.map((C,W)=>{let j=c(C.file_path),K=this.filesRepo.getContent(C.file_path),U="";if(K){let D=K.split(`
1727
+ `);U=D.slice(Math.max(0,C.start_line-2),Math.min(D.length,C.start_line+3)).join(`
1728
+ `).trim()}let H=[];C.activeGravity&&(C.activeGravity.reasons.some(D=>D.includes("Working Set"))?H.push(g):C.activeGravity.reasons.some(D=>D.includes("Recent Intent"))&&H.push(w)),C.structuralGravity&&H.push(A);let M=H.length>0?` ${H.join("")}`:"";return{relPath:j,name:C.name,kind:C.kind,symbolId:gr({symbolName:C.name,kind:C.kind,signature:C.signature,filePath:j,startLine:C.start_line}),signature:C.signature,line:C.start_line,snippet:U,badgeStr:M,gravityReasons:C.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
1729
+
1730
+ Showing ${N.length} matching symbol(s)${I?` (use offset=${n+t} for more)`:""}:
1731
+
1732
+ `+N.map((C,W)=>{let j=`## ${n+W+1}. \`${C.name}\` (${C.kind})${C.badgeStr}
1733
+ **File**: \`${C.relPath}:${C.line}\`
1734
+ `;return j+=`**Symbol ID**: \`${C.symbolId}\`
1735
+ `,C.gravityReasons.length>0&&(j+=`> *${C.gravityReasons.join(", ")}*
1736
+ `),C.signature&&(j+=`**Signature**: \`${C.signature}\`
1737
+ `),C.snippet&&(j+=`
1738
+ \`\`\`typescript
1739
+ ${C.snippet}
1740
+ \`\`\`
1741
+ `),j}).join(`
1742
+ `)}]}}async findConceptMatches(e,t,n,i,r,o=0){let a=ae(this.repoPath)||void 0,l=new bs(this.repoPath).getScorer(),p=new ei(this.repoPath).getAncestorMissionIds(),u=this.filesRepo.getGravityMap(p,a),m=bn.extractKeywords(e),f=m.length>=3,h=this.extractOrderedConceptTerms(e),y=this.buildNgrams(h,2,3),b=this.classifyConceptQuery(e,m),g=f?this.collectConceptSymbolHintPaths(m,Math.max(r*10,100)):new Set,w=Math.min(Math.max((r+o)*b.channelMultiplier,ze.FILTERED_QUERY_LIMIT_MULTIPLIER*20),qe.MAX_LIMIT),A=Math.min(Math.max(w*4,200),4e3),[x,E,I]=await Promise.all([Promise.resolve(t?this.filesRepo.findWithEmbeddings():[]),Promise.resolve(this.filesRepo.findContentFts(e,w)),Promise.resolve(t?this.exportsRepo.findWithEmbeddings(A):[])]),N=[];if(t){for(let v of x)try{let _=JSON.parse(v.embedding),R=li(t,_);N.push({row:v,similarity:R,vectorRank:0})}catch{}N.sort((v,_)=>_.similarity-v.similarity);for(let v=0;v<N.length;v++)N[v].vectorRank=v+1}let P=[];if(t){for(let v of I)if(v.embedding)try{let _=JSON.parse(v.embedding),R=li(t,_);if(R<=0)continue;P.push({row:v,similarity:R,symbolVectorRank:0})}catch{}P.sort((v,_)=>_.similarity-v.similarity);for(let v=0;v<P.length;v++)P[v].symbolVectorRank=v+1}let C=new Map;for(let v of x)C.set(v.path,v);for(let v of E)C.has(v.path)||C.set(v.path,v);let W=new Map,j=[],K=new Set;for(let v of P.slice(0,A)){let _=v.row.file_path,R=W.get(_);if((!R||v.similarity>R.similarity)&&W.set(_,{similarity:v.similarity,symbolRank:v.symbolVectorRank,symbolName:v.row.name}),K.has(_))continue;let T=C.get(_);T||(T=this.filesRepo.findByPath(_),T&&C.set(_,T)),T&&(j.push({path:_,rank:v.symbolVectorRank,score:v.similarity,row:T,symbolName:v.row.name}),K.add(_))}let U=this.rrfMerge(N.slice(0,w).map(v=>({path:v.row.path,rank:v.vectorRank,score:v.similarity,row:v.row})),E.slice(0,w).map((v,_)=>({path:v.path,rank:_+1,bm25Rank:v.bm25_rank,row:v})),b.rrfK,{vectorWeight:b.vectorWeight,ftsWeight:b.ftsWeight,symbolWeight:b.symbolWeight,symbolResults:j.slice(0,w)});if(U.length===0)return[];let H=new Map;for(let v of N)H.set(v.row.path,v.similarity);let M=Math.min(U.length,Math.max(r*b.lexicalWindowMultiplier,40)),D=new Set(U.slice(0,M).map(v=>v.path)),O=[],Y=new Map;for(let v of U){let _=v.row,R=H.get(_.path)||0,T=W.get(_.path),$=T?.similarity||0,F=Math.max(R,$),B=v.ftsRank!==null,X=v.symbolVectorRank!==null||!!T,he=v.vectorRank!==null||X,Ce=g.has(_.path),it=D.has(_.path)||B||Ce||X;if(!it&&v.fusedScore<b.earlyRejectThreshold&&F<.18&&!i)continue;let _e=it?this.filesRepo.getContent(_.path):null,rt=ze.ENABLE_LEXICAL_SCORING&&_e?bn.calculateLexicalScore(_e,e):0,ot=_e?bn.calculateKeywordCoverageFromKeywords(_e,m):0,Me=m.length>0?Math.round(ot*m.length):0,te=this.calculatePhraseCoverage(`${_.path}
1743
+ ${_.summary||""}
1744
+ ${_e||""}`,y),pe=this.calculatePathKeywordCoverage(_.path,m),Et=this.isBroadOrchestrationConceptPath(_.path,_.classification,_.summary||""),ut=1;if(_e){let We=/\b(class|function|const|let|var|enum)\s+\w+/.test(_e);if(/export\s+/.test(_e)&&!We){let Ur=_e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");/\b(class|function|const|let|var|enum)\s+\w+/.test(Ur)||(ut=.1)}}let mt=Ce?.08:X?.1:rt>0||te>0||B?.14:f?.22:.18;if(he&&F<=mt&&!B)continue;if(m.length>0&&rt===0&&!B){if(f){if(!Ce&&(Me===0&&te===0&&F<.4||Me<=1&&te===0&&F<.34||Me===1&&F<.3))continue}else if(Me===0&&F<.24)continue}if(f&&!Ce&&te===0&&Me<=1&&F<.3&&!B||i&&!s.matchesFilters(_.path,n,_.mtime,_.classification))continue;let Dt=_.mtime>2e9?Math.floor(_.mtime/1e3):_.mtime,_n=Math.floor(Date.now()/1e3)-io.SECONDS_PER_YEAR,Es=wt.getMultiplier(_.path,_.classification),Sn=he?l.calculateScore(F,Dt||_n):0,J=(v.fusedScore*60+Sn*.2)*Es,xe=u[_.path],Fe=_.classification?wt.mapClassificationToTier(_.classification):wt.classify(_.path,{content:_e??void 0}),ie=`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: ${b.profile} | Similarity: ${(F*100).toFixed(0)}%, Tier: ${Fe}${Es!==1?` (${Es}x)`:""}`;if(Ce&&(ie+=" | SymbolHint"),T&&(ie+=` | SymbolVec: ${T.symbolName}`),rt>0&&(J+=rt*ze.LEXICAL_WEIGHT,ie+=` | Lexical: +${rt.toFixed(1)}`),m.length>0)if(ot>0){let We=f?ot*.45:ot*.35;J+=We,ie+=` | Keywords: ${(ot*100).toFixed(0)}%`}else ie+=" | Keywords: 0%",f&&!B&&(J*=.55,ie+=" (penalty)");if(y.length>0)if(te>0){let We=f?te*.8:te*.35;J+=We,ie+=` | Phrases: ${(te*100).toFixed(0)}%`}else f&&!B&&(J*=.72,ie+=" | Phrases: 0% (penalty)");if(pe>0){let We=f?pe*.7:pe*.25;J+=We,ie+=` | Path: ${(pe*100).toFixed(0)}%`}else f&&Et&&pe<.2&&te<.15&&F<.32&&!X&&(J*=.82,ie+=" | Path: low specificity (orchestration penalty)");xe&&(J+=xe.score,ie+=` | \u{1F525} Gravity: +${xe.score.toFixed(1)} (${xe.reasons.join(", ")})`),f&&this.isGenericConceptPath(_.path)&&Me<=1&&te===0&&!B&&(J*=.75,ie+=" | Generic path penalty"),ut<1&&(J*=ut,ie+=` | \u{1F4C9} Barrel: x${ut}`);let at=_e?bn.extractSnippet(_e,e):void 0;O.push({path:_.path,summary:_.summary||"",score:F,fusedScore:v.fusedScore,vectorRank:v.vectorRank,ftsRank:v.ftsRank,decayedScore:J,rationale:ie,snippet:at}),Y.set(_.path,{lexicalScore:rt,keywordCoverage:ot,matchedKeywordCount:Me,phraseCoverage:te,pathCoverage:pe,similarity:F,hasFtsSignal:B,hasSymbolHint:Ce,hasSymbolVectorSignal:X,lexicalConfirm:0,identifierOverlap:0,isGenericPath:this.isGenericConceptPath(_.path),isBroadOrchestrationPath:Et})}if(O.length>0&&m.length>0){let v=this.exportsRepo.findByFiles(O.map(R=>R.path)),_=new Map;for(let R of v){let T=_.get(R.file_path)??[];T.push(R.name),_.set(R.file_path,T)}for(let R of O){let T=this.calculateIdentifierOverlap(m,_.get(R.path)??[]),$=Y.get(R.path);if($&&($.identifierOverlap=T),T>0){let F=f?T*.8:T*.25;R.decayedScore=(R.decayedScore||0)+F,R.rationale+=` | Symbols: ${(T*100).toFixed(0)}%`}else f&&this.isGenericConceptPath(R.path)?(R.decayedScore=(R.decayedScore||0)*.82,R.rationale+=" | Symbols: 0% (generic penalty)"):f&&$?.isBroadOrchestrationPath&&$.pathCoverage<.2&&$.phraseCoverage<.15&&(R.decayedScore=(R.decayedScore||0)*.84,R.rationale+=" | Symbols: 0% (broad penalty)")}}let z=new Map;for(let v of O){let _=v.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();_&&_.length>3&&(z.has(_)||z.set(_,[]),z.get(_).push(v))}for(let[v,_]of z.entries())if(new Set(_.map(T=>T.path.split(".").pop())).size>1)for(let T of _)T.decayedScore=(T.decayedScore||0)+.15,T.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${v}')`;if(f&&O.length>1){let v=Math.min(Math.max(r*4,ze.FILTERED_QUERY_LIMIT_MULTIPLIER*20),O.length),_=[...O].sort((T,$)=>($.decayedScore||0)-(T.decayedScore||0)).slice(0,v),R=this.computeBm25LikeConfirmation(_.map(T=>T.path),m);for(let T of _){let $=R.get(T.path)||0,F=Y.get(T.path);if(F&&(F.lexicalConfirm=$),$>0){let B=Math.min(.95,$*.18);T.decayedScore=(T.decayedScore||0)+B,T.rationale+=` | LexConfirm: +${B.toFixed(2)}`}else F&&F.matchedKeywordCount<=1&&F.phraseCoverage===0&&F.lexicalScore===0&&(T.decayedScore=(T.decayedScore||0)*.85,T.rationale+=" | LexConfirm: 0 (penalty)")}}for(let v of O){let _=Y.get(v.path);_&&(v.score=this.calculateConceptEvidenceScore({profile:b.profile,queryKeywordCount:m.length,..._}),v.rankingScore=this.calculateConceptRankingScore({profile:b.profile,decayedScore:v.decayedScore||0,evidenceScore:v.score,pathCoverage:_.pathCoverage,phraseCoverage:_.phraseCoverage,identifierOverlap:_.identifierOverlap,hasSymbolVectorSignal:_.hasSymbolVectorSignal,isBroadOrchestrationPath:_.isBroadOrchestrationPath}),v.rationale+=` | Rank: ${(v.rankingScore||0).toFixed(2)}`,v.rationale+=` | Evidence: ${(v.score*100).toFixed(0)}%`)}return O.sort((v,_)=>(_.rankingScore||_.decayedScore||0)-(v.rankingScore||v.decayedScore||0)),O.slice(o,o+Math.min(r,qe.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(),d=0;l===i&&(d+=6),l.startsWith(i)&&(d+=4),l.includes(i)&&(d+=3);for(let u of t)u.length>=3&&l.includes(u)&&(d+=1);if(d===0)continue;let p=a.get(c.file_path)||0;d>p&&a.set(c.file_path,d)}return Array.from(a.entries()).sort((c,l)=>l[1]-c[1]).slice(0,Math.min(n,qe.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 d of e){let p=r.get(d.path)||{path:d.path,row:d.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};p.vectorRank=d.rank,p.fusedScore+=o/(n+d.rank),r.set(d.path,p)}for(let d of t){let p=r.get(d.path)||{path:d.path,row:d.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};p.ftsRank=d.rank,p.fusedScore+=a/(n+d.rank),r.set(d.path,p)}for(let d of l){let p=r.get(d.path)||{path:d.path,row:d.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};p.symbolVectorRank=d.rank,p.symbolName=d.symbolName,p.fusedScore+=c/(n+d.rank),r.set(d.path,p)}return Array.from(r.values()).sort((d,p)=>p.fusedScore-d.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.profile==="lexical-heavy"||e.profile==="identifier-heavy"?.14:.08,a=e.similarity*n+Math.min(1,e.lexicalScore)*.08+e.keywordCoverage*.1+e.phraseCoverage*i+e.pathCoverage*o+e.identifierOverlap*r+t*.08;return e.hasFtsSignal&&(a+=.04),e.hasSymbolHint?a+=.03:e.hasSymbolVectorSignal&&(a+=.02),e.matchedKeywordCount===0&&e.phraseCoverage===0&&e.lexicalScore===0?a*=e.hasFtsSignal||e.hasSymbolVectorSignal?.72:.6:e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(a*=.88),e.isGenericPath&&e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(a*=.85),e.isBroadOrchestrationPath&&e.pathCoverage<.2&&e.phraseCoverage<.15&&e.identifierOverlap===0&&!e.hasSymbolVectorSignal&&(a*=.82),e.queryKeywordCount===0&&(a*=.75),Math.max(0,Math.min(.97,a))}calculateConceptRankingScore(e){let t=e.profile==="lexical-heavy"?4.5:e.profile==="identifier-heavy"?4.2:3.6,n=e.decayedScore+e.evidenceScore*t;return e.pathCoverage>0&&(n+=e.pathCoverage*1.1),e.phraseCoverage>0&&(n+=e.phraseCoverage*.6),e.identifierOverlap>0&&(n+=e.identifierOverlap*.9),e.isBroadOrchestrationPath&&e.evidenceScore<.4&&e.pathCoverage<.2&&e.phraseCoverage<.15&&e.identifierOverlap<.2&&!e.hasSymbolVectorSignal&&(n*=.78),n}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}calculatePathKeywordCoverage(e,t){let n=Array.from(new Set(t.filter(a=>a.length>=4&&!this.isLowSignalConceptKeyword(a))));if(n.length===0)return 0;let i=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase(),r=i.split("/").pop()||i,o=0;for(let a of n)(r.includes(a)||new RegExp(`(^|[^a-z0-9_])${a}([^a-z0-9_]|$)`).test(i))&&(o+=1);return o/n.length}isGenericConceptPath(e){let t=e.toLowerCase();return/(?:^|\/)(index|utils?|helpers?|common|shared|types?|constants?|models?)(?:\/|\.|$)/.test(t)}isBroadOrchestrationConceptPath(e,t,n){let i=`${e}
1745
+ ${n||""}`.toLowerCase(),r=t?.toLowerCase()||"";return/(workflow|orchestrat|routes?|controller|admin|service|handler|pipeline)/.test(i)||["controller","service","handler","component"].includes(r)}computeBm25LikeConfirmation(e,t){let n=Array.from(new Set(t.map(p=>p.toLowerCase()).filter(p=>p.length>=3)));if(e.length===0||n.length===0)return new Map;let i=new Set(n),r=[],o=new Map;for(let p of e){let m=(this.filesRepo.getContent(p)??"").toLowerCase().split(/[^a-z0-9_]+/).map(h=>h.trim()).filter(Boolean),f=new Map;for(let h of m)i.has(h)&&f.set(h,(f.get(h)||0)+1);for(let h of n)(f.get(h)||0)>0&&o.set(h,(o.get(h)||0)+1);r.push({path:p,frequencies:f,length:Math.max(m.length,1)})}let a=r.reduce((p,u)=>p+u.length,0)/Math.max(r.length,1),c=1.2,l=.75,d=new Map;for(let p of r){let u=0;for(let m of n){let f=p.frequencies.get(m)||0;if(f===0)continue;let h=o.get(m)||0,y=Math.log(1+(r.length-h+.5)/(h+.5)),b=f*(c+1)/(f+c*(1-l+l*(p.length/Math.max(a,1))));u+=y*b}d.set(p.path,u)}return d}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,qe.MAX_LIMIT)).map(([r])=>r))}isLowSignalConceptKeyword(e){return new Set(["type","types","data","update","create","list","item","value","model","helper","flow","workflow","service","services","route","routes","controller","admin","chain","pipeline"]).has(e.toLowerCase())}};function _s(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}}q();async function fu(s){let e=ts(s.query??""),t={...s,query:e},n=nn();try{let{repoPath:i}=de(t),{query:r,limit:o=qe.DEFAULT_LIMIT,offset:a=0,compact:c=!1,tokenBudget:l}=t;await Q(i);let{filters:d,hasFilters:p}=_s(t),m=await new Mt(i).searchByConcept(r,o,a,d,p,c,l);try{let y=Yn(i);if(y.status==="running"){let[b,g]=y.progress.split("/").map(Number),w=g>0?Math.round(b/g*100):0,A=`\u26A0\uFE0F Symbol embeddings still warming (${y.progress}, ${w}%) \u2014 symbol-level results may be incomplete. File-level results are fully available.
1746
+
1747
+ `;m.content?.[0]?.type==="text"&&(m.content[0].text=A+m.content[0].text)}}catch{}Ub(i,r,"concept");let f=m.content?.[0]?.text??"",h=Jt("shadow_search_concept",f);return m.content?.[0]?.type==="text"&&(m.content[0].text=hs(f,h)),n({toolName:h.toolName,outputTokens:h.outputTokens,estimatedCostUsd:h.estimatedCostUsd}),m}catch(i){return k.error({error:i,args:s},"Concept Search failed"),n({toolName:"shadow_search_concept"}),await Ft(),{content:[{type:"text",text:`Concept Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Ub(s,e,t){try{let n=L.getInstance(s),i=ae(s);n.searchHistory.record(e,t,i)}catch(n){let i=ae(s);k.debug({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();import Ss from"path";q();function hu(s,e){let t=s.findContentByToken(e,100);return{count:t.length,files:t}}function gu(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 yu(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 Q(e);let c=L.getInstance(e),{configs:l,files:d}=c;if(a){k.info({repoPath:e,key:a},"Searching for config key in DB...");let f=l.findByKey(a,r);if(f.length===0)return{content:[{type:"text",text:`No configuration found for key: ${a}`}]};if(o){let b=f.map(E=>{let I=hu(d,E.key),N=I.count>0?"in-use":gu({file_path:E.file_path,kind:E.kind}),P=N==="in-use"?`\u2713 ${I.count} usage(s)`:N==="external-wiring"?"\u2699\uFE0F NO IN-REPO CODE REFERENCES":"\u26A0\uFE0F ORPHANED";return{file:Ss.relative(e,E.file_path),key:E.key,value:E.value,kind:E.kind,usageCount:I.count,usageFiles:I.files.slice(0,5).map(C=>Ss.relative(e,C)),status:P,disposition:N}});b.sort((E,I)=>{let N=P=>P==="orphaned"?0:P==="external-wiring"?1:2;return N(E.disposition)!==N(I.disposition)?N(E.disposition)-N(I.disposition):E.usageCount-I.usageCount});let g=b.filter(E=>E.disposition==="orphaned").length,w=b.filter(E=>E.disposition==="external-wiring").length;return{content:[{type:"text",text:(g>0?`# Configuration Search: "${a}" (with Usage Analysis)
1748
+
1749
+ \u26A0\uFE0F **${g} likely orphaned setting(s)** (no in-repo code references detected in code-backed config)
1750
+
1751
+ Found ${f.length} match(es):
1752
+
1753
+ `:`# Configuration Search: "${a}" (with Usage Analysis)
1754
+
1755
+ Found ${f.length} match(es).
1756
+ ${w>0?`
1757
+ ${w} item(s) have no in-repo code references but appear to be infrastructure/runtime wiring.
1758
+ `:`
1759
+ `}`)+b.map(E=>{let I=`## ${E.file} (${E.kind}) ${E.status}
1760
+ **${E.key}**: \`${E.value}\``;return E.usageCount>0&&E.usageFiles.length>0?I+=`
1761
+ > Used in: ${E.usageFiles.map(N=>`\`${N}\``).join(", ")}${E.usageCount>5?` (+${E.usageCount-5} more)`:""}`:E.disposition==="external-wiring"&&(I+=`
1762
+ > No in-repo code references detected. This entry likely belongs to deployment, CI, or runtime wiring.`),I}).join(`
1763
+
1764
+ `)}]}}let h=f.map(b=>({file:Ss.relative(e,b.file_path),key:b.key,value:b.value,kind:b.kind}));return{content:[{type:"text",text:`# Configuration Search: "${a}"
1765
+
1766
+ Found ${f.length} match(es):
1767
+
1768
+ `+h.map(b=>`## ${b.file} (${b.kind})
1769
+ **${b.key}**: \`${b.value}\``).join(`
1770
+
1771
+ `)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let p=l.findByKind(i||null,r);if(o){let f=p.map(w=>{let A=hu(d,w.key),x=A.count>0?"in-use":gu({file_path:w.file_path,kind:w.kind});return{file:Ss.relative(e,w.file_path),key:w.key,value:w.value,kind:w.kind,usageCount:A.count,usageFiles:A.files.slice(0,3).map(E=>Ss.relative(e,E)),disposition:x}});f.sort((w,A)=>{let x=E=>E==="orphaned"?0:E==="external-wiring"?1:2;return x(w.disposition)!==x(A.disposition)?x(w.disposition)-x(A.disposition):w.usageCount-A.usageCount});let h=f.filter(w=>w.disposition==="orphaned").length,y=f.filter(w=>w.disposition==="external-wiring").length,b=f.length,g=`# Config Discovery (${i||"all"}) with Usage Analysis
1772
+
1773
+ `;return g+=`**Summary**: ${b} config(s) found, ${h} likely orphaned, ${y} external/runtime-only
1774
+
1775
+ `,h>0&&(g+=`## \u26A0\uFE0F Orphaned (${h})
1776
+ `,g+=f.filter(w=>w.disposition==="orphaned").map(w=>`- \`${w.key}\` in ${w.file}`).join(`
1777
+ `),g+=`
1778
+
1779
+ `),y>0&&(g+=`## \u2699\uFE0F No In-Repo Code References (${y})
1780
+ `,g+=f.filter(w=>w.disposition==="external-wiring").map(w=>`- \`${w.key}\` in \`${w.file}\` (likely deployment, CI, or runtime wiring rather than application code)`).join(`
1781
+ `),g+=`
1782
+
1783
+ `),g+=`## \u2713 In Use (${f.filter(w=>w.disposition==="in-use").length})
1784
+ `,g+=f.filter(w=>w.disposition==="in-use").map(w=>{let A=w.usageFiles.length>0?`, used in ${w.usageFiles.map(x=>`\`${x}\``).join(", ")}${w.usageCount>3?` (+${w.usageCount-3} more)`:""}`:"";return`- \`${w.key}\`=\`${w.value}\` in \`${w.file}\` (${w.usageCount} usages${A})`}).join(`
1785
+ `),p.length===r&&(g+=`
1786
+
1787
+ > Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:g}]}}let u=p.map(f=>({...f,file:Ss.relative(e,f.file_path)})),m=JSON.stringify(u,null,2);return p.length===r&&(m=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
1788
+
1789
+ `+m),m+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:m}]}}V();q();async function bu(s){let e=ts(s.query??""),t={...s,query:e},n=nn();try{let{repoPath:i}=de(t),{query:r,limit:o=qe.DEFAULT_LIMIT,offset:a=0,ranked:c=!1}=t;await Q(i);let{filters:l,hasFilters:d}=_s(t),u=await new Mt(i).searchByPath(r,o,a,l,d,c);Bb(i,r,"path");let m=u.content?.[0]?.text??"",f=Jt("shadow_search_path",m);return u.content?.[0]?.type==="text"&&(u.content[0].text=hs(m,f)),n({toolName:f.toolName,outputTokens:f.outputTokens,estimatedCostUsd:f.estimatedCostUsd}),u}catch(i){return k.error({error:i,args:s},"Path Search failed"),n({toolName:"shadow_search_path"}),await Ft(),{content:[{type:"text",text:`Path Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Bb(s,e,t){try{let n=L.getInstance(s),i=ae(s);n.searchHistory.record(e,t,i)}catch(n){let i=ae(s);k.debug({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();async function _a(s){let e=ts(s.query??""),t={...s,query:e},n=nn();try{let{repoPath:i}=de(t),{query:r,limit:o=qe.DEFAULT_LIMIT,offset:a=0,matchMode:c="any"}=t;await Q(i);let{filters:l,hasFilters:d}=_s(t),u=await new Mt(i).searchBySymbol(r,o,a,l,d,c);Gb(i,r,"symbol");let m=u.content?.[0]?.text??"",f=Jt("shadow_search_symbol",m);return u.content?.[0]?.type==="text"&&(u.content[0].text=hs(m,f)),n({toolName:f.toolName,outputTokens:f.outputTokens,estimatedCostUsd:f.estimatedCostUsd}),u}catch(i){return k.error({error:i,args:s},"Symbol Search failed"),n({toolName:"shadow_search_symbol"}),await Ft(),{content:[{type:"text",text:`Symbol Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Gb(s,e,t){try{let n=L.getInstance(s),i=ae(s);n.searchHistory.record(e,t,i)}catch(n){let i=ae(s);k.debug({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),Ft()}}async function _u(s,e){let t=zn.resolve(e.dir);await ee(async()=>{ke("Semantic Concept Search");let n=st();n.start(`Analyzing intent: "${S.bold(s)}"...`);try{let i=await fu({repoPath:t,query:s,limit:e.limit,offset:e.offset});n.stop("Analysis complete.");let r=i.content[0].text;if(r.includes("Found")){let a=r.split("## ").slice(1).map(c=>{let[l,...d]=c.split(`
1790
+
1791
+ `),[p,u]=l.split(" ( "),m=(p??"").replace(/^\d+\.\s*/,"").trim(),f=d.find(h=>h.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:m,matchPct:u??"",summaryLine:f}});if(a.forEach(({name:c,matchPct:l,summaryLine:d})=>{we(`${S.green(c)} ${S.dim("("+(l||""))}`,d,"blue"),console.log("")}),e.interactive&&a.length>1){let c=await Bs("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:zn.join(t,c.name),d=await Js({repoPath:t,filePath:l});d.content?.[0]&&(console.log(""),we(S.bold("File summary"),d.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function Su(s,e){let t=zn.resolve(e.dir);await ee(async()=>{ke("Path Search");let n=st();n.start(`Resolving paths for "${S.bold(s)}"...`);try{let i=await bu({repoPath:t,query:s,ranked:e.ranked,limit:e.limit,offset:e.offset,fileType:e.fileType,layer:e.layer});n.stop("Search complete.");let r=i.content[0]?.text??"",o=r.split(`
1792
+ `).filter(a=>/^\d+\.\s+`/.test(a)).map(a=>{let c=a.match(/^\d+\.\s+`([^`]+)`(?:\s+\(([^)]+)\))?(?:\s+[^[]*)?(?:\s+\[G:([^\]]+)\])?(?:\s+\[(via symbol)\])?/)??[];return{path:c[1]??a.trim(),layer:c[2]??"",gravity:c[3]??"",source:c[4]??""}});if(o.length>0){if(console.log(""),ge(["Path","Layer","Gravity","Source"],o.map(a=>[S.cyan(a.path),a.layer||"",a.gravity||"",a.source||""])),console.log(""),e.interactive&&o.length>1){let a=await Bs("Inspect file",o.map(c=>({value:c,label:c.path,hint:`${c.layer||"file"} ${c.gravity?`G:${c.gravity}`:""}`.trim()})),{limit:15});if(a){let c=await Js({repoPath:t,filePath:zn.join(t,a.path)});c.content?.[0]&&console.log(c.content[0].text)}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function wu(s,e){let t=zn.resolve(e.dir);await ee(async()=>{ke("Symbol Search");let n=st();n.start(`Searching symbols: "${S.bold(s)}"...`);try{let i=await _a({repoPath:t,query:s,limit:e.limit,offset:e.offset,matchMode:e.matchMode});n.stop("Search complete.");let r=i.content[0].text;try{let o=JSON.parse(r);if(Array.isArray(o)){if(console.log(""),ge(["Symbol","Kind","File","Line"],o.map(a=>[S.bold(S.green(a.name)),S.dim(a.kind??""),S.cyan(a.file??""),S.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 Bs("Inspect symbol",a,{limit:15});if(c){let l=await gs({repoPath:t,symbolName:c.name});l.content?.[0]&&(console.log(""),we(S.bold(c.name),l.content[0].text,"cyan"))}}}else console.log(r)}catch{console.log(r)}}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function Eu(s,e){let t=zn.resolve(e.dir);await ee(async()=>{ke("Fuzzy Symbol Search");let n=st();n.start(`Fuzzy matching: "${S.bold(s)}"...`);try{let i=await _a({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(`
1793
+ `),d=l[0],p=l.find(b=>b.startsWith("**Match**:"))||"",u=l.find(b=>b.startsWith("**File**:"))||"",m=d.match(/`([^`]+)`/),f=m?m[1]:"",h=p.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),y=u.match(/`([^:]+):(\d+)`/);return{symbolName:f,file:y?y[1]:"",line:y?y[2]:"",matchType:h?h[1]:"",confidence:h?h[2]:""}});if(console.log(""),console.log(S.dim(`Found ${a.length} fuzzy match(es):`)),console.log(""),a.forEach((c,l)=>{console.log(`${S.dim(`${l+1}.`)} ${S.bold(S.green(c.symbolName))} ${S.dim(`(${c.matchType}, ${c.confidence}% match)`)}`),console.log(` ${S.cyan(c.file)}:${S.yellow(c.line)}`),console.log("")}),e.interactive&&a.length>1){let c=await Bs("Inspect symbol",a.map(l=>({value:l,label:l.symbolName,hint:`${l.file}:${l.line}`})),{limit:15});if(c){let l=await gs({repoPath:t,symbolName:c.symbolName});l.content?.[0]&&(console.log(""),we(S.bold(c.symbolName),l.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await ne(t)}})}async function xu(s,e){let t=zn.resolve(e.dir);await ee(async()=>{ke("Config Search");let n=st();n.start(`Searching config: ${S.bold(s||"all")}...`);try{let i=await yu({repoPath:t,key:s,kind:e.kind,showUsage:e.showUsage});n.stop("Search complete."),we("\u2699\uFE0F Results",i.content[0].text,"yellow")}finally{await ne(t)}})}V();import qb from"path";async function vu(s){let e=qb.resolve(s);try{await ee(async()=>{ke("\u{1F311} Liquid Shadow: Scouting Report");let t=L.getInstance(e),n=Ot(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);we("Intelligence Summary",`${S.bold("\u{1F4E1} Topology")}: ${S.cyan(r.toString())} files mapped
1794
+ ${S.bold("\u{1F9E9} Symbols")}: ${S.cyan(o.toString())} exports detected
1795
+ ${S.bold("\u{1F552} Last Sync")}: ${a?S.yellow(new Date(a).toLocaleString()):S.red("Never")}
1796
+ ${S.bold("\u2699\uFE0F Config")}: ${i?S.green("Custom Intelligence"):S.gray("Standard Sieve")}`,"blue"),c.length>0&&(console.log(""),console.log(` ${S.bold("Symbol Distribution (Top 5)")}`),lr(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),30)),console.log(""),console.log(` ${S.dim("Pro-tip: Try")} ${S.bold(S.cyan("liquid-shadow dashboard"))} ${S.dim("for the full tactical view.")}`),console.log(""),_t("Scouting complete.")})}finally{await ne(e)}}bt();async function ku(s){let{repoPath:e}=de(s),{deep:t,enableContextPivot:n,enableMergeSentinel:i}=s;try{let r=t===!0;await Q(e,5,r,r);let o=new $e(e),a=o.detectAndRepairShifts(),c=o.syncLifecycle({enableContextPivot:n,enableMergeSentinel:i}),l=new be(e);l.refreshTopography();let d=l.computeGravityZones();l.updateGravityZones(d);let p=`Repository at ${e} has been ${t?"deeply ":""}re-indexed.`;return a.repaired>0&&(p+=`
1797
+ \u2728 Nano-Repair: Fixed ${a.repaired} links.`),p+=`
1798
+ \u{1F9ED} Lifecycle: contextPivot=${c.contextPivotEnabled?"on":"off"}, mergeSentinel=${c.mergeSentinelEnabled?"on":"off"}, suspended=${c.suspended}, resumed=${c.resumed}, completed=${c.completed}.`,p+=`
1799
+ \u269B\uFE0F Hologram: Refreshed architectural map (${d.length} hotspots).`,{content:[{type:"text",text:p}]}}catch(r){return{content:[{type:"text",text:`Error: ${r.message}`}],isError:!0}}}async function Ru(s){let{repoPath:e}=de(s);try{let n=new $e(e).detectAndRepairShifts();return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(t){return{content:[{type:"text",text:`Error tracing shifts: ${t.message}`}],isError:!0}}}V();en();async function Tu(s){let{repoPath:e}=de(s),{enableContextPivot:t,enableMergeSentinel:n}=s;try{await Q(e),new gn(e).analyzeGhostChanges();let r=new $e(e),o=r.detectAndRepairShifts(),a=r.syncLifecycle({enableContextPivot:t,enableMergeSentinel:n}),l=await new St(e).recoverFromGitNotes(),{HologramService:d}=await Promise.resolve().then(()=>(bt(),dp)),p=new d(e),u=kt(L.getInstance(e),e);p.updateTopography(u);let m=p.computeGravityZones();p.updateGravityZones(m);let f="Shadow Sync complete. Code changes indexed and intent logs updated.";return f+=`
1800
+ \u269B\uFE0F Hologram: Refreshed architectural map (${m.length} hotspots).`,o.repaired>0&&(f+=`
1801
+ \u2728 Nano-Repair: Fixed ${o.repaired} links.`),f+=`
1802
+ \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||l.logsRecovered>0)&&(f+=`
1803
+ \u{1F9EC} Re-hydration: Recovered ${l.missionsRecovered} missions and ${l.logsRecovered} logs.`),l.notesFailed>0&&(f+=`
1804
+ \u26A0\uFE0F Re-hydration: ${l.notesFailed} Git Note entries failed recovery (see logs).`),{content:[{type:"text",text:f}]}}catch(i){return{content:[{type:"text",text:`Error: ${i.message}`}],isError:!0}}}function Jb(s){try{let e=JSON.parse(s);return["NanoRepair complete.",`Repaired links: ${e.repaired??0}`,`Failed repairs: ${e.failed??0}`].join(`
1805
+ `)}catch{return s}}function Kb(){Ye({command:"liquid-shadow sync",summary:"Refresh repo intelligence intentionally: trace for full lifecycle, index for re-indexing, repair for NanoRepair only.",usage:"liquid-shadow sync [trace|index|repair] [dir] [--flags]",actions:[{command:"trace [dir]",description:"Lifecycle sync: index drift, repair shifts, re-hydrate notes"},{command:"index [dir]",description:"Re-index and refresh hologram/topography"},{command:"repair [dir]",description:"Run NanoRepair only"}],examples:["liquid-shadow sync .","liquid-shadow sync trace . --context-pivot","liquid-shadow sync index . --deep --merge-sentinel","liquid-shadow sync repair ."]})}async function Sa(s){let e=Ve(s),[t,n]=e.positionals;if(!t||t==="help"||t==="--help"||t==="-h"){Kb();return}["trace","index","repair"].includes(t)||(n=t,t="trace");let i=Oe(n??G(e.flags,"dir","d"));await ee(async()=>{ke("Shadow Sync");let r=st();r.start(`Running sync ${t} for ${S.bold(i)}...`);try{let o="";if(t==="trace")o=(await Tu({repoPath:i,enableContextPivot:re(e.flags,["context-pivot"]),enableMergeSentinel:re(e.flags,["merge-sentinel"])})).content[0]?.text??"";else if(t==="index")o=(await ku({repoPath:i,deep:re(e.flags,["deep"]),enableContextPivot:re(e.flags,["context-pivot"]),enableMergeSentinel:re(e.flags,["merge-sentinel"])})).content[0]?.text??"";else{let a=await Ru({repoPath:i});o=Jb(a.content[0]?.text??"")}r.stop(`Sync ${t} complete.`),console.log(""),console.log(o),console.log("")}catch(o){let a=o instanceof Error?o.message:String(o);throw r.stop(`Sync ${t} failed.`),new Error(a)}finally{await ne(i)}})}import Wr from"path";async function Cu(s,e){let t=Wr.resolve(e.dir),n=Wr.isAbsolute(s)?s:Wr.resolve(t,s);await ee(async()=>{ke("Execution Trace");let i=st();i.start(`Tracing ${S.cyan(e.symbolName||Wr.basename(n))}...`);try{let r=await rr({repoPath:t,filePath:n,symbolName:e.symbolName});i.stop("Trace complete."),r.isError?console.error(S.red(r.content[0].text)):we("Flow Results",r.content[0].text,"magenta")}catch(r){throw i.stop(`Trace failed: ${r.message}`),r}finally{await ne(t)}})}import Vb from"path";async function Au(s,e){let t=Vb.resolve(s);try{await ee(async()=>{ke("\u{1F311} Liquid Shadow: Topological Mapping");let n=parseInt(e.depth,10),i=await ms(t,n,"detailed",e.subPath);console.log(` ${S.bold("Root")}: ${S.cyan(t)}`),e.subPath&&console.log(` ${S.bold("Subpath")}: ${S.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)});zo([r(i)]),console.log(""),_t("Mapping concluded.")})}finally{await ne(t)}}import Yb from"fs";import Qb from"path";var Xb=2e3;async function Iu(s){let e=Qb.resolve(s);await ee(async()=>{ke("Watch mode");let t=Ot(e),n=null,i=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(S.dim(" Changes detected, reindexing...")),await Q(e,5,!1,!0),console.log(S.green(" Reindex complete."))}catch(r){console.error(S.red(" Reindex failed:"),r instanceof Error?r.message:r)}},Xb)};try{Yb.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&i()}),console.log(S.cyan(` Watching ${e}`)),console.log(S.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),_t("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)}})}var Zb=[{title:"Start Here",items:[{command:"status [dir]",description:"See index health, symbol counts, and recent sync state"},{command:"recon onboard [dir]",description:"Build or refresh the repo intelligence baseline"},{command:"sync [trace|index|repair] [dir]",description:"Refresh index state and repair drift intentionally"},{command:"dashboard [dir]",description:"Open the TUI when you want a broader operational view"}]},{title:"Search & Inspect",items:[{command:"search-path <query>",description:"Find files and packages by path keywords, optionally ranked"},{command:"search-symbol <query>",description:"Find exported symbols with match and pagination controls"},{command:"search-concept <query>",description:"Semantic file search for intent-level discovery"},{command:"search-config [key]",description:"Find config keys and optionally show in-repo usage"},{command:"inspect <symbol|file> ...",description:"Read a symbol or file with the shared inspection logic"}]},{title:"Analyze",items:[{command:"analyze <mode> ...",description:"Impact, deps, flow, mesh, debt, type graph, and diff analysis"},{command:"tree [dir]",description:"Show a structural tree for a repo or subpath"},{command:"chronicle [dir]",description:"Read the repo narrative and ADR-style feed"}]},{title:"Workspace, Ops & Env",items:[{command:"workspace <action> ...",description:"Status, ensure, repair, gc, list, fuse, and link workspaces"},{command:"ops <action> ...",description:"Expose the MCP ops suite directly from the CLI"},{command:"env <action> ...",description:"Expose env diagnose/hooks from the CLI"},{command:"mission <action> ...",description:"Alias-oriented mission helpers for core ops flows"},{command:"hooks <action> [path]",description:"Alias for env hooks"},{command:"init",description:"Install skills and local integration config for operators/agents"}]}],e_=["liquid-shadow status .","liquid-shadow sync trace .","liquid-shadow search-path workspace --ranked","liquid-shadow analyze impact RepositoryFactory --file src/data/factory.ts","liquid-shadow ops health .","liquid-shadow workspace status . ../another-repo"];function Pu(s){console.log(""),console.log(` ${S.bold(`liquid-shadow v${s.version}`)} ${S.dim("Human-first repository intelligence CLI")}`),console.log(` ${s.description}`),console.log(""),console.log(` ${S.bold("Usage:")} liquid-shadow <command> [args]`),console.log(` ${S.dim("Run")} ${S.cyan("liquid-shadow <command> --help")} ${S.dim("for command-specific flags where supported.")}`);for(let e of Zb){console.log(""),console.log(` ${S.bold(e.title)}`);for(let t of e.items)console.log(` ${S.cyan(t.command.padEnd(32))} ${t.description}`)}console.log(""),console.log(` ${S.bold("Examples")}`);for(let e of e_)console.log(` ${e}`);console.log(""),console.log(` ${S.bold("Notes")}`),console.log(" The CLI is the human operator surface; MCP tools remain available for skills and agents."),console.log(` The dashboard is optional now. Running ${S.cyan("liquid-shadow")} without a command shows this guide instead of opening the TUI.`),console.log("")}import $t from"path";async function Lu(s){let e=await lp(s);return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}q();var t_=k.child({module:"mcp:tools:workspace:fuse"});async function Nu(s){let{repoPaths:e,name:t}=s;t_.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=tr();for(let c of e)await Q(c);let i=t||Rt(e),r=Ws({repoPaths:e,name:i});r.recordWorkspaceAccess(t?"custom":"auto"),r.refreshAll();let o=r.scanEdges(),a=r.getStatus();return{content:[{type:"text",text:JSON.stringify({message:"Fused index ready",status:a,fused_index:a,scan:o,cleanup:n,instructions:"Use shadow_analyze_mesh({ repoPath, topic, includeCrossRepo: true }) or shadow_analyze_impact(...) to inspect cross-repo edges."},null,2)}]}}catch(n){let i=t||Rt(e);throw Vl({name:i,dbPath:Ie(i),repoPaths:e,error:n.message,managedKind:t?"custom":"auto"}),new Error(`Failed to fuse: ${n.message}`)}}async function Mu(s){let e=pp(s);return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}V();q();import $u from"path";var n_=k.child({module:"mcp:tools:workspace:link"});async function Du(s){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:i,relationship:r="related"}=s;n_.info({parentRepoPath:e,childRepoPath:n},"Linking cross-repo missions");let o=$u.resolve(e),a=$u.resolve(n),{missions:c}=L.getInstance(o),{missions:l}=L.getInstance(a);try{if(o===a&&t===i)throw new Error("Cannot link a mission to itself");let d=c.findById(t),p=l.findById(i);if(!d)throw new Error(`Parent mission ${t} not found`);if(!p)throw new Error(`Child mission ${i} not found`);let u=c.getLink(t,a,i,"parent"),m=l.getLink(i,o,t,"child"),f=!!u,h=!!m,y=u?.relationship===r,b=m?.relationship===r;if(y&&b)return{content:[{type:"text",text:JSON.stringify({status:"already_linked",relationship:r},null,2)}]};let g=!1;try{g=c.upsertLink(t,a,i,r,"parent")>0&&!f,l.upsertLink(i,o,t,r,"child")}catch(A){throw u?c.upsertLink(t,a,i,u.relationship??r,"parent"):g&&c.deleteLink(t,a,i,"parent"),A}return{content:[{type:"text",text:JSON.stringify({status:f||h?"repaired":"linked",relationship:r},null,2)}]}}catch(d){return{content:[{type:"text",text:`Error: Failed to link: ${d.message}`}],isError:!0}}}Ae();V();import Ou from"fs";import jr from"path";q();var wa=k.child({module:"mcp:tools:workspace:list"});async function Fu(s){let{repoPaths:e,status:t,limit:n,summarize:i=!1}=s;wa.info({repoCount:e.length,status:t,summarize:i},"Getting workspace missions");let r=e.map(p=>jr.resolve(p)),o=tr(),a=[],c=r.map(p=>({repo_path:p,repo_name:jr.basename(p),exists:Ou.existsSync(p),indexed:!1,current_branch:null,head_commit:null,last_indexed_commit:null,last_indexed_at:null,has_index_drift:!1,drift_reason:null,mission_count:0,error:null}));for(let p of r){let u=c.find(m=>m.repo_path===p);if(!u.exists){u.error="missing";continue}try{u.indexed=Re(p);let m=u.indexed?Qt(p):{lastIndexedCommit:null,lastIndexedAt:null};u.last_indexed_commit=m.lastIndexedCommit,u.last_indexed_at=m.lastIndexedAt;let f=jr.join(p,".git");Ou.existsSync(f)&&(u.current_branch=ae(p),u.head_commit=Ne(p)),u.indexed&&m.lastIndexedCommit&&u.head_commit&&(u.head_commit!==m.lastIndexedCommit?(u.has_index_drift=!0,u.drift_reason="head_commit_differs"):Jn(p,m.lastIndexedCommit)&&(u.has_index_drift=!0,u.drift_reason="working_tree_changed"))}catch(m){u.error=m instanceof Error?m.message:String(m),wa.error({error:m,repoPath:p},"Failed to collect repo health metadata")}try{let{missions:m}=L.getInstance(p),f=m.findAll(t);u.mission_count=f.length;for(let h of f){let y=m.getLinks(h.id);a.push({...h,repo_path:p,repo_name:jr.basename(p),cross_repo_links:y})}}catch(m){u.error??=m instanceof Error?m.message:String(m),wa.error({error:m,repoPath:p},"Failed to query repo missions")}}let l=Po().filter(p=>p.repoPaths.some(u=>r.includes(u)));if(a.sort((p,u)=>{let m=g=>g==="in-progress"?0:g==="verifying"?1:g==="planned"?2:g==="suspended"?3:g==="completed"?4:5,f=m(p.status),h=m(u.status);if(f!==h)return f-h;let y=p.updated_at||p.created_at||0;return(u.updated_at||u.created_at||0)-y}),i||a.length>50&&!n){let p=n||20,u=a.slice(0,p),m=a.reduce((h,y)=>(h[y.status]=(h[y.status]||0)+1,h),{}),f=a.reduce((h,y)=>(h[y.repo_name]=(h[y.repo_name]||0)+1,h),{});return{content:[{type:"text",text:JSON.stringify({summary:{total_missions:a.length,by_status:m,by_repo:f,showing_top:p},repo_health:c,workspaces:l,cleanup:o,top_missions:u,hint:`Showing top ${p} of ${a.length} missions. Use limit to adjust or summarize:false for full list.`},null,2)}]}}let d=n?a.slice(0,n):a;return{content:[{type:"text",text:JSON.stringify({total_missions:a.length,showing:d.length,repo_health:c,workspaces:l,cleanup:o,missions:d},null,2)}]}}async function Wu(s){let e=await No(s);return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async function ju(s){let e=ln(s);return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function zr(s){try{return JSON.parse(s)}catch{return null}}function ws(){Ye({command:"liquid-shadow workspace",summary:"Operator-facing workspace lifecycle tools backed by the shared workspace status, ensure, repair, gc, fuse, and link logic.",usage:"liquid-shadow workspace <action> [paths...] [--flags]",actions:[{command:"list <paths...>",description:"List missions plus repo/workspace health across repos"},{command:"status <paths...>",description:"Explain workspace state, confidence, and next safe action"},{command:"ensure <paths...>",description:"Reuse, refresh, repair, or rebuild a workspace as needed"},{command:"repair <paths...>",description:"Repair stale registry/db/lock workspace state"},{command:"gc [paths...]",description:"Dry-run or apply cleanup for obsolete fused workspaces"},{command:"fuse <paths...>",description:"Create a fused index explicitly"},{command:"link <parentRepo> <parentId> <childRepo> <childId>",description:"Link missions across repos"}],examples:["liquid-shadow workspace list . ../platform --summarize","liquid-shadow workspace status . ../platform","liquid-shadow workspace ensure . ../platform --repair-policy safe","liquid-shadow workspace gc --older-than-days 30"]})}function ti(s){console.log(""),console.log(s),console.log("")}function s_(s){return s.exists===!1?S.red("missing"):s.indexed===!1?S.yellow("unindexed"):s.has_index_drift?S.yellow("stale"):S.green("ready")}function i_(s){let e=zr(s);if(!e||Array.isArray(e)){ti(s);return}let t=Array.isArray(e.repo_health)?e.repo_health:[],n=Array.isArray(e.missions)?e.missions:Array.isArray(e.top_missions)?e.top_missions:[],i=Array.isArray(e.workspaces)?e.workspaces:[],r=typeof e.summary=="object"&&e.summary?e.summary:null;console.log(""),console.log(` ${S.bold("Workspace overview")}`),r&&console.log(` ${S.dim("Missions:")} ${String(r.total_missions??n.length)} ${S.dim("Showing:")} ${String(r.showing_top??n.length)}`),t.length>0&&ge(["Repo","Status","Branch","Indexed","Drift"],t.map(o=>{let a=o;return[String(a.repo_name??a.repo_path??""),s_(a),String(a.current_branch??"n/a"),String(a.last_indexed_commit??"n/a").slice(0,12),String(a.drift_reason??"")]})),n.length>0?ge(["ID","Status","Repo","Branch","Mission"],n.map(o=>{let a=o;return[String(a.id??""),String(a.status??""),String(a.repo_name??""),String(a.git_branch??"n/a"),String(a.name??"")]})):console.log(` ${S.dim("No missions matched the current filters.")}`),i.length>0&&ge(["Workspace","State","Repos","Edges"],i.map(o=>{let a=o;return[String(a.name??""),String(a.state??""),String(a.attachedRepos??""),String(a.virtualEdgesCount??"")]})),console.log("")}function r_(s){let e=zr(s);if(!e||Array.isArray(e)){ti(s);return}let t=typeof e.workspace=="object"&&e.workspace?e.workspace:{},n=typeof e.recommendedAction=="object"&&e.recommendedAction?e.recommendedAction:{},i=typeof e.freshness=="object"&&e.freshness?e.freshness:{},r=typeof e.repoHealth=="object"&&e.repoHealth?e.repoHealth:{},o=Array.isArray(e.causes)?e.causes:[],a=Array.isArray(t.relatedWorkspaces)?t.relatedWorkspaces:[];if(console.log(""),console.log(` ${S.bold(String(t.canonicalName??t.name??"workspace"))} ${S.dim(`(${String(e.state??"unknown")})`)}`),console.log(` ${S.dim("Confidence:")} ${String(e.confidence??"n/a")} ${S.dim("Recommended action:")} ${String(n.type??"none")}`),console.log(` ${S.dim("Selected by:")} ${String(t.selectedBy??"unknown")} ${S.dim("Path:")} ${String(t.path??"n/a")}`),console.log(` ${S.dim("Repo health:")} ${String(r.total??0)} total, ${String(r.stale??0)} stale, ${String(r.unindexed??0)} unindexed, ${String(r.missing??0)} missing`),i.isEdgeScanStale&&console.log(` ${S.yellow("\u26A0")} Edge scan is stale ${String(i.edgeScanAgeMs??"")}ms after the last scan.`),o.length>0){console.log(` ${S.bold("Causes")}`);for(let c of o.slice(0,8)){let l=c;console.log(` ${String(l.severity??"info").toUpperCase()} ${String(l.code??"")}: ${String(l.message??"")}`)}}a.length>0&&ge(["Related workspace","Kind","State","Last used"],a.map(c=>{let l=c;return[String(l.name??""),String(l.managedKind??""),String(l.state??""),String(l.lastAccessedAt??"")]})),console.log("")}function zu(s,e,t,n){let i=zr(e);if(!i||Array.isArray(i)){ti(e);return}let r=Array.isArray(i[t])?i[t]:[],o=n&&Array.isArray(i[n])?i[n]:[],a=typeof i.workspace=="object"&&i.workspace?i.workspace:{};console.log(""),console.log(` ${S.bold(s)} ${S.dim(`${String(i.initialState??"unknown")} -> ${String(i.finalState??"unknown")}`)}`),console.log(` ${S.dim("Workspace:")} ${String(a.canonicalName??a.name??"n/a")} ${S.dim("Confidence:")} ${String(i.confidence??"n/a")}`),r.length>0?ge(["Applied action","Details"],r.map(c=>{let l=c;return[String(l.type??l.action??"action"),JSON.stringify(l).slice(0,90)]})):console.log(` ${S.dim("No corrective actions were needed.")}`),o.length>0&&ge(["Skipped repair","Details"],o.map(c=>{let l=c;return[String(l.type??l.reason??"skip"),JSON.stringify(l).slice(0,90)]})),console.log("")}function o_(s){let e=zr(s);if(!e||Array.isArray(e)){ti(s);return}let t=Array.isArray(e.candidates)?e.candidates:[],n=Array.isArray(e.retained)?e.retained:[];console.log(""),console.log(` ${S.bold("Workspace GC")} ${S.dim(e.dryRun?"(dry run)":"(applied)")}`),t.length>0?ge(["Workspace","Classification","Safety","Repos"],t.map(i=>{let r=i;return[String(r.name??""),String(r.classification??""),String(r.safety??""),String(r.repoPaths?.length??0)]})):console.log(` ${S.dim("No cleanup candidates found.")}`),n.length>0&&ge(["Retained","Safety","State"],n.map(i=>{let r=i;return[String(r.name??""),String(r.safety??""),String(r.state??"")]})),console.log("")}function Ea(s,e){return e.length===0?(ws(),console.error(` ${S.red("\u2716")} workspace ${s} needs at least one repository path.`),console.log(""),process.exitCode=1,!1):!0}async function xa(s){let e=Ve(s),[t,...n]=e.positionals;if(!t||t==="help"||t==="--help"||t==="-h"){ws();return}await ee(async()=>{switch(t){case"missions":case"list":{let i=n.map(o=>$t.resolve(o));if(!Ea("list",i))return;let r=await Fu({repoPaths:i,status:G(e.flags,"status"),limit:se(e.flags,["limit"]),summarize:re(e.flags,["summarize"])});i_(r.content[0]?.text??"");return}case"status":{let i=n.map(a=>$t.resolve(a)),r=G(e.flags,"name");if(!r&&i.length===0){ws(),console.error(` ${S.red("\u2716")} workspace status needs repo paths or --name.`),console.log(""),process.exitCode=1;return}let o=await ju({...r?{name:r}:{},...i.length>0?{repoPaths:i}:{}});r_(o.content[0]?.text??"");return}case"ensure":{let i=n.map(o=>$t.resolve(o));if(!Ea("ensure",i))return;let r=await Lu({repoPaths:i,name:G(e.flags,"name"),repairPolicy:G(e.flags,"repair-policy"),rebuildPolicy:G(e.flags,"rebuild-policy")});zu("Workspace ensure",r.content[0]?.text??"","actionsTaken");return}case"repair":{let i=n.map(a=>$t.resolve(a)),r=G(e.flags,"name");if(!r&&i.length===0){ws(),console.error(` ${S.red("\u2716")} workspace repair needs repo paths or --name.`),console.log(""),process.exitCode=1;return}let o=await Wu({...r?{name:r}:{},...i.length>0?{repoPaths:i}:{},rebuildPolicy:G(e.flags,"rebuild-policy")});zu("Workspace repair",o.content[0]?.text??"","repairsApplied","repairsSkipped");return}case"gc":{let i=n.map(o=>$t.resolve(o)),r=await Mu({...i.length>0?{repoPaths:i}:{},name:G(e.flags,"name"),apply:re(e.flags,["apply"]),olderThanDays:se(e.flags,["older-than-days"]),includeCustom:re(e.flags,["include-custom"])});o_(r.content[0]?.text??"");return}case"link":{if(n.length<4){ws(),process.exitCode=1;return}let[i,r,o,a]=n,c=G(e.flags,"relationship")??"depends_on";await Du({parentRepoPath:$t.resolve(i),parentMissionId:Number(r),childRepoPath:$t.resolve(o),childMissionId:Number(a),relationship:c}),console.log(""),console.log(` ${S.green("\u2714")} Linked ${$t.basename(i)}#${r} -> ${$t.basename(o)}#${a} ${S.dim(`(${c})`)}`),console.log("");return}case"fuse":{let i=n.map(o=>$t.resolve(o));if(!Ea("fuse",i))return;let r=await Nu({repoPaths:i,name:G(e.flags,"name")});ti(r.content[0]?.text??"");return}default:ws(),process.exitCode=1}})}function Xe(s){let e=process.cwd();return Ma(e,s.flags)}var c_=new Map([["analyze",Bo],["workspace",xa],["recon",ba],["sync",Sa],["inspect",sa],["ops",ru],["env",fr],["mission",pa],["hooks",Vo],["skills",async s=>{let e=s[0];if(!e||e==="help"||e==="--help"||e==="-h"){console.log(""),console.log(" liquid-shadow skills update"),console.log("");return}if(e==="update"){await Qo();return}console.error(`Unknown skills action: ${e}. Available: update`),process.exitCode=1}]]);process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),ne().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),ne().then(()=>process.exit(1))});var Hr=Hn;try{Hr=Oa()}catch(s){console.error("Failed to parse package.json, using defaults",s)}var fe=a_().name("liquid-shadow").version(Hr.version).description(Hr.description).scriptName("liquid-shadow");fe.command("index","Build or refresh repository intelligence index",{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=Xe(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 Vp(s.parameters.dir||e.dir,t)});fe.command("status","Show operator-facing repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=Xe(s);await vu(s.parameters.dir||e.dir)});fe.command("dashboard","Operational intelligence dashboard (TUI)",{parameters:["[dir]"]}).on("dashboard",async s=>{let e=Xe(s);await zp(s.parameters.dir||e.dir)});fe.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=Xe(s);await fd(s.parameters.dir||e.dir)});fe.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=Xe(s);await Mp(s.parameters.dir||e.dir)});fe.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=Xe(s);await Au(s.parameters.dir||e.dir,{...s.flags,dir:s.flags.dir??e.dir})});fe.command("recon","Onboard and inspect repository architecture",{parameters:["[mode]","[args...]"]}).on("recon",async s=>{await ba([s.parameters.mode,...s.parameters.args||[]].filter(Boolean))});fe.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=Xe(s);await Cu(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});fe.command("sync","Refresh repo intelligence (trace, index, or repair)",{parameters:["[action]","[args...]"],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=[s.parameters.action,...s.parameters.args||[]].filter(Boolean);s.flags.contextPivot&&e.push("--context-pivot"),s.flags.mergeSentinel&&e.push("--merge-sentinel"),s.flags.deep&&e.push("--deep"),await Sa(e)});fe.command("search-config","Search configuration keys and usage",{parameters:["[key]"],flags:{dir:{type:String,alias:"d",default:"."},kind:{type:String,description:"Filter by config kind"},showUsage:{type:Boolean,description:"Show in-repo usage counts and orphaned hints",default:!1}}}).on("search-config",async s=>{let e=Xe(s);await xu(s.parameters.key,{...s.flags,dir:s.flags.dir??e.dir})});fe.command("search-path","Search files and packages by path keywords",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a file to inspect",default:!1},ranked:{type:Boolean,description:"Rank results by gravity score",default:!1},limit:{type:Number,description:"Max results to show",default:10},offset:{type:Number,description:"Result offset for pagination",default:0},fileType:{type:String,description:"Filter by extension, e.g. ts,tsx"},layer:{type:String,description:"Filter by layer tier"}}}).on("search-path",async s=>{let e=Xe(s);await Su(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});fe.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},limit:{type:Number,description:"Max results to show",default:10},offset:{type:Number,description:"Result offset for pagination",default:0}}}).on("search-concept",async s=>{let e=Xe(s);await _u(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});fe.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},limit:{type:Number,description:"Max results to show",default:10},offset:{type:Number,description:"Result offset for pagination",default:0},matchMode:{type:String,description:"Match strategy: any, all, or exact"}}}).on("search-symbol",async s=>{let e=Xe(s);await wu(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});fe.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=Xe(s);await Eu(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});fe.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["[action]","[path]"]}).on("hooks",async s=>{await Vo([s.parameters.action,s.parameters.path])});fe.command("workspace","Workspace lifecycle and cross-repo orchestration",{parameters:["[action]","[args...]"]}).on("workspace",async s=>{await xa([s.parameters.action,...s.parameters.args])});fe.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["[action]","[args...]"]}).on("mission",async s=>{await pa([s.parameters.action,...s.parameters.args])});fe.command("inspect","Inspect files or symbols using indexed intelligence",{parameters:["[mode]","[args...]"]}).on("inspect",async s=>{await sa([s.parameters.mode,...s.parameters.args])});fe.command("analyze","Run impact, deps, flow, mesh, debt, or diff analysis",{parameters:["[mode]","[args...]"]}).on("analyze",async s=>{await Bo([s.parameters.mode,...s.parameters.args||[]].filter(Boolean))});fe.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=Xe(s);await Iu(s.parameters.dir||e.dir)});fe.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=Xe(s);await $p(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})});fe.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=Xp(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 Zp(s.flags.force,s.flags.yes,s.flags.mcpCommand,e)});fe.command("skills","Manage Liquid Shadow reasoning skills",{parameters:["[action]"]}).on("skills",async s=>{let e=s.parameters.action;e==="update"?await Qo():(console.error(`Unknown skills action: ${e}. Available: update`),process.exit(1))});fe.command("completion","Generate shell completion script (bash or zsh)",{parameters:["[shell]"]}).on("completion",async s=>{await Op(s.parameters.shell||"")});var va=process.argv.slice(2),Hu=va[0]?c_.get(va[0]):void 0;process.argv.length<=2||process.argv.length===3&&["--help","-h","help"].includes(process.argv[2]??"")?Pu(Hr):Hu?Promise.resolve(Hu(va.slice(1))):fe.parse();