@precisionutilityguild/liquid-shadow 1.0.9 → 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.
- package/README.md +279 -62
- package/dist/data/migrations/000_baseline.sql +17 -0
- package/dist/data/migrations/014_tribunal_state.sql +24 -0
- package/dist/data/migrations/015_repo_level_handoffs_nullable.sql +52 -0
- package/dist/data/migrations/016_repair_tribunal_artifact_fk.sql +58 -0
- package/dist/entry/cli/index.js +1296 -928
- package/dist/entry/ember/index.js +313 -254
- package/dist/entry/mcp/server.js +1031 -808
- package/dist/entry/tribunal/index.js +685 -0
- package/dist/index.js +1008 -785
- package/dist/logic/domain/embeddings/worker.js +1 -1
- package/dist/logic/parser/index.js +16 -16
- package/dist/logic/parser/worker.js +1 -1
- package/dist/skills/shadow_audit/SKILL.md +22 -30
- package/dist/skills/shadow_chronicle/SKILL.md +16 -29
- package/dist/skills/shadow_continue/SKILL.md +37 -53
- package/dist/skills/shadow_coordinate/SKILL.md +46 -0
- package/dist/skills/shadow_crystallize/SKILL.md +13 -27
- package/dist/skills/shadow_mission/SKILL.md +27 -41
- package/dist/skills/shadow_onboard/SKILL.md +26 -35
- package/dist/skills/shadow_research/SKILL.md +15 -23
- package/dist/skills/shadow_sync/SKILL.md +18 -9
- package/dist/skills/shadow_synthesize/SKILL.md +14 -36
- package/dist/skills/shadow_trace_impact/SKILL.md +30 -50
- package/dist/skills/shadow_understand/SKILL.md +37 -52
- package/dist/skills/shadow_workspace/SKILL.md +44 -22
- package/dist/web-manifest.json +18 -7
- package/package.json +2 -1
- package/skills/shadow_audit/SKILL.md +22 -30
- package/skills/shadow_chronicle/SKILL.md +16 -29
- package/skills/shadow_continue/SKILL.md +37 -53
- package/skills/shadow_coordinate/SKILL.md +46 -0
- package/skills/shadow_crystallize/SKILL.md +13 -27
- package/skills/shadow_mission/SKILL.md +27 -41
- package/skills/shadow_onboard/SKILL.md +26 -35
- package/skills/shadow_research/SKILL.md +15 -23
- package/skills/shadow_sync/SKILL.md +18 -9
- package/skills/shadow_synthesize/SKILL.md +14 -36
- package/skills/shadow_trace_impact/SKILL.md +30 -50
- package/skills/shadow_understand/SKILL.md +37 -52
- package/skills/shadow_workspace/SKILL.md +44 -22
package/dist/entry/cli/index.js
CHANGED
|
@@ -1,103 +1,83 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
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
|
|
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
|
|
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
|
|
15
|
-
SELECT
|
|
16
|
-
WHERE
|
|
17
|
-
ORDER BY path ASC
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
FROM
|
|
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
|
-
|
|
32
|
-
|
|
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
|
-
|
|
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 l of o){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.status==="in-progress"||l.status==="verifying"?1:.5;n[l.file_path].score+=p;let u=l.status==="in-progress"||l.status==="verifying"?"Working Set":"Lineage Bleed";n[l.file_path].reasons.push(`${u}: ${l.mission_name}`)}let a=Math.floor(Date.now()/1e3)-86400,c=this.all(`
|
|
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 l of c){n[l.file_path]||(n[l.file_path]={score:1,reasons:[]});let p=l.mission_id?e.includes(l.mission_id):!1,u=p?.1:.2;n[l.file_path].score<5&&(n[l.file_path].score+=u);let d=p?`Lineage Intent: ${l.type}`:`Recent Intent: ${l.type}`;!n[l.file_path].reasons.includes(d)&&n[l.file_path].reasons.length<5&&n[l.file_path].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
|
|
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 = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),l=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),p=this.db.prepare("DELETE FROM type_graph_edges WHERE file_path = ?"),u=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),h=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),f=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),S=this.db.prepare("INSERT INTO type_graph_edges (file_path, source_symbol_id, source_symbol_name, target_symbol_name, relationship, line_number, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)"),y=this.db.prepare(`
|
|
91
|
-
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
|
-
`),_=this.db.transaction(R=>{for(let T of R){let{meta:k,exports:F,imports:B,configs:M,events:v,content:I,classification:$,summary:P,embedding:U,contentHash:A}=T;r.run(k.path),o.run(k.path),a.run(k.path),c.run(k.path),l.run(k.path),p.run(k.path);let H=A??(I&&n?n(I):null);if(y.run(k.path,k.mtime,Date.now(),$||"Unknown",P||"",U?JSON.stringify(U):null,H),F){let L=(D,J,z)=>{for(let g of J){let x=g.embedding?JSON.stringify(g.embedding):null,O=u.run(D,g.name,g.kind,g.signature,g.doc||"",g.line,g.endLine||g.line,g.classification||"Other",g.capabilities||"[]",z,x),C=Number(O.lastInsertRowid);if(Number.isFinite(C)){let W=Mr(g.signature);for(let j of W)j.targetName!==g.name&&S.run(D,C,g.name,j.targetName,j.relationship,g.line,j.metadata||null)}g.members&&g.members.length>0&&L(D,g.members,O.lastInsertRowid)}};L(k.path,F,null)}if(B)for(let L of B){let D=L.resolved_path!==void 0?L.resolved_path:i?.(L.module,k.path,t)??"";d.run(k.path,L.module,L.name,D)}if(M)for(let L of M)h.run(k.path,L.key,L.value,L.kind);if(I!==void 0&&m.run(k.path,I),v)for(let L of v)f.run(k.path,L.type,L.name,L.direction,L.line,L.snippet)}}),E=500;for(let R=0;R<e.length;R+=E)_(e.slice(R,R+E))}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}buildContentFtsQuery(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>=2).slice(0,12);if(t.length===0)return"";if(t.length===1)return`${t[0]}*`;let n=`"${t.join(" ")}"`,i=t.map(r=>`${r}*`).join(" OR ");return`${n} OR ${i}`}}});var Hn,Pr=ee(()=>{"use strict";Ge();Hn=class s extends pe{static HTTP_METHOD_EXPORTS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]);findByNameAndFile(e,t){return this.all("SELECT * FROM exports WHERE file_path = ? AND name = ?",t,e)}findByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ?",e)}findAtLine(e,t){return this.get(`
|
|
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 sl=Object.create;var as=Object.defineProperty;var rl=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,c=[];n||(c.push("e.file_path NOT LIKE '%/test/%'"),c.push("e.file_path NOT LIKE '%/tests/%'"),c.push("e.file_path NOT LIKE '%/__tests__/%'"),c.push("e.file_path NOT LIKE '%.spec.%'"),c.push("e.file_path NOT LIKE '%.test.%'")),i||(c.push("e.file_path NOT LIKE '%/migrations/%'"),c.push("e.file_path NOT LIKE '%/migration/%'"),c.push("e.file_path NOT LIKE '%Migration.%'")),r||(c.push("e.file_path NOT LIKE '%/__fixtures__/%'"),c.push("e.file_path NOT LIKE '%/__mocks__/%'"),c.push("e.file_path NOT LIKE '%/fixtures/%'"),c.push("e.file_path NOT LIKE '%/mocks/%'"),c.push("e.file_path NOT LIKE '%.fixture.%'"),c.push("e.file_path NOT LIKE '%.mock.%'"));for(let
|
|
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 (
|
|
@@ -215,7 +195,7 @@ var sl=Object.create;var as=Object.defineProperty;var rl=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(
|
|
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 sl=Object.create;var as=Object.defineProperty;var rl=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 l of o){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let
|
|
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 l of c){n[l.symbol_id]||(n[l.symbol_id]={score:1,reasons:[]});let
|
|
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 != ''
|
|
@@ -257,7 +237,7 @@ var sl=Object.create;var as=Object.defineProperty;var rl=Object.getOwnPropertyDe
|
|
|
257
237
|
'outbound' AS direction
|
|
258
238
|
FROM type_graph_edges
|
|
259
239
|
WHERE source_symbol_name = ?
|
|
260
|
-
`,
|
|
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 sl=Object.create;var as=Object.defineProperty;var rl=Object.getOwnPropertyDe
|
|
|
270
250
|
'inbound' AS direction
|
|
271
251
|
FROM type_graph_edges
|
|
272
252
|
WHERE target_symbol_name = ?
|
|
273
|
-
`,
|
|
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
|
|
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,28 +419,137 @@ 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(
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
created_at
|
|
355
|
-
|
|
356
|
-
WHERE
|
|
357
|
-
ORDER BY
|
|
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)}
|
|
360
|
-
|
|
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.
|
|
363
|
-
SELECT
|
|
364
|
-
FROM
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
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(`
|
|
444
|
+
SELECT id, file_path, symbol_name, signature
|
|
445
|
+
FROM intent_logs
|
|
446
|
+
WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
|
|
447
|
+
`)}findOrphans(){return this.all(`
|
|
448
|
+
SELECT il.id, il.symbol_id, il.file_path, il.symbol_name
|
|
449
|
+
FROM intent_logs il
|
|
450
|
+
WHERE (il.symbol_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM exports e WHERE e.id = il.symbol_id))
|
|
451
|
+
OR (il.symbol_id IS NULL AND il.type != 'lapsed' AND il.type != 'system' AND il.type != 'adr')
|
|
452
|
+
`)}findLogsForMissingFiles(){return this.all(`
|
|
453
|
+
SELECT il.id
|
|
454
|
+
FROM intent_logs il
|
|
455
|
+
WHERE il.file_path IS NOT NULL
|
|
456
|
+
AND NOT EXISTS (
|
|
457
|
+
SELECT 1 FROM files f WHERE f.path = il.file_path
|
|
458
|
+
)
|
|
459
|
+
`)}markAsLapsed(e){this.run(`
|
|
460
|
+
UPDATE intent_logs
|
|
461
|
+
SET symbol_id = NULL,
|
|
462
|
+
type = 'lapsed',
|
|
463
|
+
content = 'Lapsed: ' || content
|
|
464
|
+
WHERE id = ?
|
|
465
|
+
`,e)}importHeritage(e,t,n,i){this.run(`
|
|
466
|
+
INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
|
|
467
|
+
VALUES ('heritage', ?, ?, ?, ?, NULL)
|
|
468
|
+
`,e,t,n,i)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}findRawByMission(e){return this.all(`SELECT
|
|
469
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
470
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
471
|
+
created_at
|
|
472
|
+
FROM intent_logs
|
|
473
|
+
WHERE mission_id = ? AND is_crystallized = 0
|
|
474
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
475
|
+
ORDER BY created_at ASC`,e)}findCrystallizableByMission(e){return this.all(`SELECT
|
|
476
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
477
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
478
|
+
created_at
|
|
479
|
+
FROM intent_logs
|
|
480
|
+
WHERE mission_id = ?
|
|
481
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
482
|
+
ORDER BY created_at ASC`,e)}findCrystalByMission(e){return this.get(`SELECT
|
|
483
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
484
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
485
|
+
created_at
|
|
486
|
+
FROM intent_logs
|
|
487
|
+
WHERE mission_id = ? AND type = 'crystal'
|
|
488
|
+
ORDER BY created_at DESC LIMIT 1`,e)}findCrystalBySymbol(e){return this.get(`SELECT
|
|
489
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
490
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
491
|
+
created_at
|
|
492
|
+
FROM intent_logs
|
|
493
|
+
WHERE symbol_id = ? AND mission_id IS NULL AND type = 'crystal'
|
|
494
|
+
ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t,n){return this.transaction(()=>{let i=n;return typeof i=="number"?this.run(`UPDATE intent_logs
|
|
495
|
+
SET content = ?, confidence = 1.0
|
|
496
|
+
WHERE id = ? AND mission_id = ? AND type = 'crystal'`,t,i,e):i=Number(this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
|
|
497
|
+
VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
|
|
498
|
+
SET is_crystallized = 1, crystal_id = ?
|
|
499
|
+
WHERE mission_id = ? AND is_crystallized = 0 AND id != ?
|
|
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
|
|
501
|
+
WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0
|
|
502
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
503
|
+
ORDER BY created_at ASC`,e)}findCrystallizableBySymbol(e){return this.all(`SELECT
|
|
504
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
505
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
506
|
+
created_at
|
|
507
|
+
FROM intent_logs
|
|
508
|
+
WHERE symbol_id = ? AND mission_id IS NULL
|
|
509
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
510
|
+
ORDER BY created_at ASC`,e)}crystallizeBySymbol(e,t,n){return this.transaction(()=>{let i=n;return typeof i=="number"?this.run(`UPDATE intent_logs
|
|
511
|
+
SET content = ?, confidence = 1.0
|
|
512
|
+
WHERE id = ? AND symbol_id = ? AND mission_id IS NULL AND type = 'crystal'`,t,i,e):i=Number(this.insert(`INSERT INTO intent_logs (mission_id, symbol_id, type, content, confidence, is_crystallized, file_path, symbol_name, signature, commit_sha)
|
|
513
|
+
VALUES (NULL, ?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
|
|
514
|
+
SET is_crystallized = 1, crystal_id = ?
|
|
515
|
+
WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0 AND id != ?
|
|
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
|
|
517
|
+
FROM intent_logs
|
|
518
|
+
WHERE mission_id IN (${t})
|
|
519
|
+
AND type NOT IN ('system', 'adr', 'lapsed')
|
|
520
|
+
GROUP BY mission_id`,...e),i={};for(let r of n)i[r.mission_id]=r.cnt;return i}findMissionsWithBlockers(e){if(e.length===0)return new Set;let t=e.map(()=>"?").join(","),n=this.all(`SELECT DISTINCT mission_id
|
|
521
|
+
FROM intent_logs
|
|
522
|
+
WHERE mission_id IN (${t})
|
|
523
|
+
AND type = 'blocker'`,...e);return new Set(n.map(i=>i.mission_id))}findByMissionPreferCrystal(e,t=50){let n=this.findCrystalByMission(e);if(n){let i=this.all(`SELECT
|
|
524
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
525
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
526
|
+
created_at
|
|
527
|
+
FROM intent_logs
|
|
528
|
+
WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
529
|
+
AND created_at > ?
|
|
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
|
|
539
|
+
LIMIT ?
|
|
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 = ?
|
|
372
553
|
|
|
373
554
|
UNION ALL
|
|
374
555
|
|
|
@@ -413,13 +594,49 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
413
594
|
SELECT AVG(updated_at - created_at) AS avg_duration
|
|
414
595
|
FROM missions
|
|
415
596
|
WHERE status = 'completed' AND updated_at > created_at
|
|
416
|
-
`),i=n?.avg_duration!=null?Math.round(n.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,o=Math.floor(Date.now()/1e3)-720*3600,a=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),l=a?.n??0,
|
|
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
|
|
417
598
|
SET status = 'suspended', updated_at = unixepoch()
|
|
418
599
|
WHERE git_branch = ? AND status IN ('in-progress', 'verifying')`,e)}resumeByBranch(e){return this.run(`UPDATE missions
|
|
419
600
|
SET status = 'in-progress', updated_at = unixepoch()
|
|
420
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
|
|
421
602
|
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.
|
|
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(`
|
|
423
640
|
CREATE TABLE IF NOT EXISTS cross_repo_links (
|
|
424
641
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
425
642
|
mission_id INTEGER NOT NULL,
|
|
@@ -431,240 +648,25 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
431
648
|
FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
|
|
432
649
|
);
|
|
433
650
|
CREATE INDEX IF NOT EXISTS idx_cross_repo_mission ON cross_repo_links(mission_id);
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
`,e,t,n,i,r)}getLinks(e){try{return this.all(`
|
|
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(`
|
|
438
654
|
SELECT linked_repo_path, linked_mission_id, relationship, direction
|
|
439
655
|
FROM cross_repo_links
|
|
440
656
|
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=
|
|
442
|
-
|
|
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=>{w.debug({err:n,intentLogId:t},"Failed to generate intent log embedding")}),t}static EMBEDDABLE_TYPES=new Set(["decision","discovery","fix","blocker","note","heritage","crystal"]);static buildEmbeddingText(e){let t=[`[${e.type}]`];return e.symbol_name&&t.push(`symbol: ${e.symbol_name}`),e.file_path&&t.push(`file: ${e.file_path.split("/").pop()}`),t.push(e.content),t.join(" ")}async generateAndStoreEmbedding(e,t){let{generateEmbedding:n}=await Promise.resolve().then(()=>(qe(),Et)),i=s.buildEmbeddingText(t),r=await n(i);r&&this.run("UPDATE intent_logs SET embedding = ? WHERE id = ?",JSON.stringify(r),e)}findWithEmbeddings(){return this.all("SELECT * FROM intent_logs WHERE embedding IS NOT NULL AND type NOT IN ('system', 'lapsed')")}async findSemanticMatches(e,t,n){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(qe(),Et)),r=this.findWithEmbeddings();if(r.length>5e3)return w.warn({count:r.length},"Intent log count exceeds brute-force vector scan limit (5000). Skipping semantic recall."),[];let o=[];for(let a of r)if(!(n&&a.symbol_id===n))try{let c=JSON.parse(a.embedding),l=i(e,c);l>.25&&o.push({id:a.id,mission_id:a.mission_id,type:a.type,content:a.content,symbol_name:a.symbol_name,file_path:a.file_path,similarity:l,created_at:a.created_at})}catch{}return o.sort((a,c)=>c.similarity-a.similarity).slice(0,t)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${i} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
|
|
463
|
-
SELECT id, file_path, symbol_name, signature
|
|
464
|
-
FROM intent_logs
|
|
465
|
-
WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
|
|
466
|
-
`)}findOrphans(){return this.all(`
|
|
467
|
-
SELECT il.id, il.symbol_id, il.file_path, il.symbol_name
|
|
468
|
-
FROM intent_logs il
|
|
469
|
-
WHERE (il.symbol_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM exports e WHERE e.id = il.symbol_id))
|
|
470
|
-
OR (il.symbol_id IS NULL AND il.type != 'lapsed' AND il.type != 'system' AND il.type != 'adr')
|
|
471
|
-
`)}findLogsForMissingFiles(){return this.all(`
|
|
472
|
-
SELECT il.id
|
|
473
|
-
FROM intent_logs il
|
|
474
|
-
WHERE il.file_path IS NOT NULL
|
|
475
|
-
AND NOT EXISTS (
|
|
476
|
-
SELECT 1 FROM files f WHERE f.path = il.file_path
|
|
477
|
-
)
|
|
478
|
-
`)}markAsLapsed(e){this.run(`
|
|
479
|
-
UPDATE intent_logs
|
|
480
|
-
SET symbol_id = NULL,
|
|
481
|
-
type = 'lapsed',
|
|
482
|
-
content = 'Lapsed: ' || content
|
|
483
|
-
WHERE id = ?
|
|
484
|
-
`,e)}importHeritage(e,t,n,i){this.run(`
|
|
485
|
-
INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
|
|
486
|
-
VALUES ('heritage', ?, ?, ?, ?, NULL)
|
|
487
|
-
`,e,t,n,i)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}findRawByMission(e){return this.all(`SELECT
|
|
488
|
-
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
489
|
-
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
490
|
-
created_at
|
|
491
|
-
FROM intent_logs
|
|
492
|
-
WHERE mission_id = ? AND is_crystallized = 0
|
|
493
|
-
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
494
|
-
ORDER BY created_at ASC`,e)}findCrystalByMission(e){return this.get(`SELECT
|
|
495
|
-
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
496
|
-
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
497
|
-
created_at
|
|
498
|
-
FROM intent_logs
|
|
499
|
-
WHERE mission_id = ? AND type = 'crystal'
|
|
500
|
-
ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t){return this.transaction(()=>{let n=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
|
|
501
|
-
VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
|
|
502
|
-
SET is_crystallized = 1, crystal_id = ?
|
|
503
|
-
WHERE mission_id = ? AND is_crystallized = 0 AND id != ?
|
|
504
|
-
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),n})}findRawBySymbol(e){return this.all(`SELECT * FROM intent_logs
|
|
505
|
-
WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0
|
|
506
|
-
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
507
|
-
ORDER BY created_at ASC`,e)}crystallizeBySymbol(e,t){return this.transaction(()=>{let n=this.insert(`INSERT INTO intent_logs (mission_id, symbol_id, type, content, confidence, is_crystallized, file_path, symbol_name, signature, commit_sha)
|
|
508
|
-
VALUES (NULL, ?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
|
|
509
|
-
SET is_crystallized = 1, crystal_id = ?
|
|
510
|
-
WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0 AND id != ?
|
|
511
|
-
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),n})}countByMissions(e){if(e.length===0)return{};let t=e.map(()=>"?").join(","),n=this.all(`SELECT mission_id, COUNT(*) as cnt
|
|
512
|
-
FROM intent_logs
|
|
513
|
-
WHERE mission_id IN (${t})
|
|
514
|
-
AND type NOT IN ('system', 'adr', 'lapsed')
|
|
515
|
-
GROUP BY mission_id`,...e),i={};for(let r of n)i[r.mission_id]=r.cnt;return i}findMissionsWithBlockers(e){if(e.length===0)return new Set;let t=e.map(()=>"?").join(","),n=this.all(`SELECT DISTINCT mission_id
|
|
516
|
-
FROM intent_logs
|
|
517
|
-
WHERE mission_id IN (${t})
|
|
518
|
-
AND type = 'blocker'`,...e);return new Set(n.map(i=>i.mission_id))}findByMissionPreferCrystal(e,t=50){let n=this.findCrystalByMission(e);if(n){let i=this.all(`SELECT
|
|
519
|
-
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
520
|
-
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
521
|
-
created_at
|
|
522
|
-
FROM intent_logs
|
|
523
|
-
WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
524
|
-
AND created_at > ?
|
|
525
|
-
ORDER BY created_at DESC LIMIT ?`,e,n.created_at,t-1);return[n,...i]}return this.findByMission(e,t)}async findSemanticTheme(e,t,n=200){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(qe(),Et)),r=this.findWithEmbeddings(),o=[];for(let a of r)if(s.EMBEDDABLE_TYPES.has(a.type)&&!(t&&a.mission_id!==null&&!t.includes(a.mission_id)))try{let c=JSON.parse(a.embedding),l=i(e,c);l>.35&&o.push({...a,_similarity:l})}catch{}return o.sort((a,c)=>c._similarity-a._similarity).slice(0,n).map(({_similarity:a,...c})=>c)}crystallizeTheme(e,t,n){return this.transaction(()=>{let i=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
|
|
526
|
-
VALUES (NULL, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,n);if(t.length>0){let r=t.map(()=>"?").join(",");this.run(`UPDATE intent_logs SET is_crystallized = 1, crystal_id = ? WHERE id IN (${r})`,i,...t)}return i})}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:n}=await Promise.resolve().then(()=>(qe(),Et)),i=[...s.EMBEDDABLE_TYPES].map(p=>`'${p}'`).join(","),r=this.all(`SELECT * FROM intent_logs WHERE embedding IS NULL AND type IN (${i})`);if(r.length===0)return 0;let o=r.map(p=>s.buildEmbeddingText(p)),a=await n(o,e,t),c=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),l=0;return this.transaction(()=>{for(let p=0;p<r.length;p++)a[p]&&(c.run(JSON.stringify(a[p]),r[p].id),l++)}),w.info({total:r.length,embedded:l},"Intent log embedding backfill complete"),l}}});var Yn,Qr=ee(()=>{"use strict";Ge();Yn=class extends pe{findByKey(e,t=20){return this.all(`
|
|
527
|
-
SELECT file_path, key, value, kind
|
|
528
|
-
FROM configs
|
|
529
|
-
WHERE key LIKE ? OR value LIKE ?
|
|
530
|
-
LIMIT ?
|
|
531
|
-
`,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",i=[];return e&&(n+=" WHERE kind = ?",i.push(e)),n+=" LIMIT ?",i.push(t),this.all(n,...i)}findEnvValue(e){return this.get("SELECT value FROM configs WHERE key LIKE ? OR key = ? LIMIT 1",`%:env:${e}`,e)?.value}countByKind(e){return this.get("SELECT COUNT(*) as count FROM configs WHERE kind = ?",e)?.count||0}getAll(){return this.all("SELECT key, value, kind, file_path FROM configs")}}});var Kn,Zr=ee(()=>{"use strict";Ge();Kn=class extends pe{search(e,t=10){return this.all(`
|
|
532
|
-
SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
|
|
533
|
-
FROM content_fts
|
|
534
|
-
WHERE content_fts MATCH ?
|
|
535
|
-
LIMIT ?
|
|
536
|
-
`,e,t)}}});var Xr,Qn,eo=ee(()=>{"use strict";Ge();Xr=500,Qn=class extends pe{record(e,t,n=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,n),this.pruneIfNeeded()}findRecent(e=20){return this.all("SELECT id, query, mode, branch, created_at FROM search_history ORDER BY created_at DESC LIMIT ?",e)}findRecentByQueryPrefix(e,t=10){return e.trim()?this.all(`SELECT id, query, mode, branch, created_at FROM search_history
|
|
537
|
-
WHERE query LIKE ? ORDER BY created_at DESC LIMIT ?`,`${e}%`,t):this.findRecent(t)}pruneIfNeeded(){(this.get("SELECT COUNT(*) as count FROM search_history")?.count??0)<=Xr||this.run(`DELETE FROM search_history WHERE id NOT IN (
|
|
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 (
|
|
538
659
|
SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
|
|
539
|
-
)`,Xr)}}});var Zn,to=ee(()=>{"use strict";Ge();Zn=class extends pe{getSection(e){return this.get("SELECT section, data, updated_at FROM hologram_snapshot WHERE section = ?",e)}getAllSections(){return this.all("SELECT section, data, updated_at FROM hologram_snapshot ORDER BY section")}upsertSection(e,t){this.run(`
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
`,e,t);let n=this.getClaim(e);if(!n)throw new Error(`Failed to hydrate claim after insert for file ${e}`);return{status:"claimed",claim:n}}catch{let n=this.getClaim(e);if(!n)throw new Error(`Failed to read existing claim for file ${e}`);return n.mission_id===t?(this.run("UPDATE file_claims SET updated_at = unixepoch() WHERE file_path = ?",e),{status:"already_claimed",claim:this.getClaim(e)??n}):{status:"conflict",claim:n}}}releaseFile(e,t){let n=this.getClaim(e);return n?t!==void 0&&n.mission_id!==t?{released:!1,reason:"not_owner",claim:n}:(this.run("DELETE FROM file_claims WHERE file_path = ?",e),{released:!0}):{released:!1,reason:"not_found"}}releaseAllForMission(e){return this.run("DELETE FROM file_claims WHERE mission_id = ?",e)}getClaim(e){return this.get(`
|
|
549
|
-
SELECT
|
|
550
|
-
fc.file_path,
|
|
551
|
-
fc.mission_id,
|
|
552
|
-
fc.claimed_at,
|
|
553
|
-
fc.updated_at,
|
|
554
|
-
m.name AS mission_name,
|
|
555
|
-
m.status AS mission_status,
|
|
556
|
-
m.git_branch AS mission_branch
|
|
557
|
-
FROM file_claims fc
|
|
558
|
-
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
559
|
-
WHERE fc.file_path = ?
|
|
560
|
-
`,e)}getClaimsForMission(e){return this.all(`
|
|
561
|
-
SELECT
|
|
562
|
-
fc.file_path,
|
|
563
|
-
fc.mission_id,
|
|
564
|
-
fc.claimed_at,
|
|
565
|
-
fc.updated_at,
|
|
566
|
-
m.name AS mission_name,
|
|
567
|
-
m.status AS mission_status,
|
|
568
|
-
m.git_branch AS mission_branch
|
|
569
|
-
FROM file_claims fc
|
|
570
|
-
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
571
|
-
WHERE fc.mission_id = ?
|
|
572
|
-
ORDER BY fc.file_path ASC
|
|
573
|
-
`,e)}listClaims(){return this.all(`
|
|
574
|
-
SELECT
|
|
575
|
-
fc.file_path,
|
|
576
|
-
fc.mission_id,
|
|
577
|
-
fc.claimed_at,
|
|
578
|
-
fc.updated_at,
|
|
579
|
-
m.name AS mission_name,
|
|
580
|
-
m.status AS mission_status,
|
|
581
|
-
m.git_branch AS mission_branch
|
|
582
|
-
FROM file_claims fc
|
|
583
|
-
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
584
|
-
ORDER BY fc.updated_at DESC, fc.file_path ASC
|
|
585
|
-
`)}getClaimsByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`
|
|
586
|
-
SELECT
|
|
587
|
-
fc.file_path,
|
|
588
|
-
fc.mission_id,
|
|
589
|
-
fc.claimed_at,
|
|
590
|
-
fc.updated_at,
|
|
591
|
-
m.name AS mission_name,
|
|
592
|
-
m.status AS mission_status,
|
|
593
|
-
m.git_branch AS mission_branch
|
|
594
|
-
FROM file_claims fc
|
|
595
|
-
LEFT JOIN missions m ON m.id = fc.mission_id
|
|
596
|
-
WHERE fc.file_path IN (${t})
|
|
597
|
-
ORDER BY fc.file_path ASC
|
|
598
|
-
`,...e)}}});var N,Y=ee(()=>{"use strict";ut();$r();Pr();Or();Yr();Kr();Qr();Zr();eo();to();no();N=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=De(e),o=t.files?.database,c=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram||!t.claims;if(o===r&&r.open&&!c)return t;this.repositoryCache.delete(e)}let n=De(e),i={files:new zn(n),exports:new Hn(n),imports:new Bn(n),missions:new Vn(n),intentLogs:new Jn(n),configs:new Yn(n),content:new Kn(n),searchHistory:new Qn(n),hologram:new Zn(n),claims:new Xn(n)};return this.repositoryCache.set(e,i),i}static closeInstance(e){this.repositoryCache.delete(e),Wn(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var ro=pl((Oh,_s)=>{var ti=process||{},io=ti.argv||[],ei=ti.env||{},Yl=!(ei.NO_COLOR||io.includes("--no-color"))&&(!!ei.FORCE_COLOR||io.includes("--color")||ti.platform==="win32"||(ti.stdout||{}).isTTY&&ei.TERM!=="dumb"||!!ei.CI),Kl=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+Ql(i,e,t,r)+e:s+i+e},Ql=(s,e,t,n)=>{let i="",r=0;do i+=s.substring(r,n)+t,r=n+e.length,n=s.indexOf(e,r);while(~n);return i+s.substring(r)},so=(s=Yl)=>{let e=s?Kl:()=>String;return{isColorSupported:s,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};_s.exports=so();_s.exports.createColors=so});var Ei,Si,Xo,wi,ea,ta,na,ia,sa,ra,oa,aa,ca,la,Rn,xi,pa,ua,$s=ee(()=>{"use strict";Ei=[/\/pages\/(?!_)[^/]+\.(tsx?|jsx?)$/i,/\/pages\/.*\/index\.(tsx?|jsx?)$/i,/\/app\/.*\/page\.(tsx?|jsx?)$/i,/\/app\/.*\/layout\.(tsx?|jsx?)$/i,/\/app\/api\/.*\/route\.(ts|js)$/i,/\/pages\/api\/.*\.(ts|js)$/i],Si=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],Xo=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],wi=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],ea=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],ta=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],na=[/\/commands?\/[^/]+\.(ts|js|py|php)$/i,/\/cli\/[^/]+\.(ts|js|py|php)$/i,/\/bin\/[^/]+\.(ts|js|py|php)$/i,/cli\.(ts|js|py|php)$/i,/main\.(ts|js|py|php)$/i],ia=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],sa=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],ra=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],oa=[/\/stores?\//i,/\/slices?\//i,/\/reducers?\//i,/\/atoms?\//i,/\/selectors?\//i,/\.(store|slice|reducer|atom|selector)\.(ts|js)$/i,/.*Slice\.(ts|js)$/i,/.*Store\.(ts|js)$/i],aa=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],ca=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],la=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],Rn=[/\.(model|entity|schema|repository|repo|dao|migration|query|mutation|resolver|connection|db)\.(ts|js)$/i,/queries\.(ts|js)$/i,/mutations\.(ts|js)$/i,/resolvers\.(ts|js)$/i,/connection\.(ts|js)$/i,/\/models?\//i,/\/entities?\//i,/\/repositories?\//i,/\/repos?\//i,/\/data\//i,/\/database\//i,/\/prisma\//i,/\/drizzle\//i,/\/api\/.*client\.(ts|js|tsx)$/i,/(^|\/)[A-Z0-9_-]*API\.(tsx?|js|jsx)$/],xi=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],pa=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],ua=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var vi,ma,Ri,ha,Ps=ee(()=>{"use strict";vi=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],ma=[/views\.py$/i,/forms\.py$/i,/serializers\.py$/i,/admin\.py$/i,/apps\.py$/i,/tasks\.py$/i,/middlewares?\.py$/i,/signals?\.py$/i,/context_processors\.py$/i],Ri=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],ha=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var Ti,ga,ki,ya,Ns=ee(()=>{"use strict";Ti=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],ga=[/\/services?\/.*\.php$/i,/\/providers?\/.*\.php$/i,/\/middleware\/.*\.php$/i,/\/jobs?\/.*\.php$/i,/\/listeners?\/.*\.php$/i,/\/events?\/.*\.php$/i,/\/observers?\/.*\.php$/i,/\/console\/commands\/.*\.php$/i,/\/actions?\/.*\.php$/i,/\/traits?\/.*\.php$/i,/\/concerns?\/.*\.php$/i,/\/contracts?\/.*\.php$/i],ki=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],ya=["laravel","symfony","slim","cakephp","codeigniter"]});import _a from"path";function Bt(s,e,t){let n=[],i="Unknown",r=0;t||(t=Vp(s,e));let{inDegree:o,outDegree:a}=t,c=(d,h,m,f)=>{for(let S of d)if(S.test(s))return n.push(`${f}: ${S.source}`),i=h,r+=m,!0;return!1},l=!1;if(l||(l=c(Ei,"Entry",45,"Next.js entry")),l||(l=c(ea,"Entry",40,"MCP handler")),l||(l=c(na,"Entry",40,"CLI command")),l||(l=c(Rn,"Data",45,"Data layer/Repository")),l||(l=c(oa,"Data",35,"State management")),l||(l=c(Xo,"Logic",40,"React component")),l||(l=c(wi,"Logic",35,"Logic pattern")),l||(l=c(ia,"Logic",35,"Parser/AST")),l||(l=c(sa,"Logic",35,"Core module")),l||(l=c(ra,"Logic",30,"UI layer")),l||(l=c(la,"Types",35,"Type definition")),l||(l=c(vi,"Entry",40,"Python Entry")),l||(l=c(Ri,"Data",40,"Python Data")),l||(l=c(ma,"Logic",35,"Python Logic")),l||(l=c(Ti,"Entry",40,"PHP Entry")),l||(l=c(ki,"Data",40,"PHP Data")),l||(l=c(ga,"Logic",35,"PHP Logic")),l||(l=c(aa,"Logic",35,"Hook/Context")),!l){for(let d of ta)if(d.test(s)){n.push(`MCP utility: ${d.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,l=!0;break}}l||c(ca,"Data",35,"Schema definition")&&(l=!0),l||(c(Rn,"Data",30,"Path matches data pattern")||c(xi,"Utility",25,"Path matches utility pattern")||c(Si,"Entry",30,"Path matches entry pattern"))&&(l=!0);for(let d of Ds)if(d.test(s)){n.push(`Test file: ${d.source}`),i="Test",r=50,l=!0;break}l||c(Os,"Infrastructure",40,"Infrastructure")&&(l=!0);for(let d of qp)d.test(s)&&(n.push(`Monorepo component: ${d.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let u=e.imports.getImportsForFile(s).map(d=>d.module_specifier.toLowerCase());for(let d of ua)if(u.some(h=>h.includes(d))){n.push(`Imports JS data library: ${d}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let d of ha)if(u.some(h=>h.includes(d))){n.push(`Imports Python framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of ya)if(u.some(h=>h.includes(d))){n.push(`Imports PHP framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let d of pa)if(u.some(h=>h.includes(d))){n.push(`Imports JS framework: ${d}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}if(o===0&&a>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),i==="Unknown"?(i="Entry",r+=30):i==="Entry"&&(r+=15)),o>5&&a<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),i==="Unknown"?(i="Utility",r+=25):i==="Utility"&&(r+=10)),i==="Unknown"&&o>0&&a>0){let d=o/(o+a);d>.3&&d<.7&&(n.push(`Balanced traffic: in=${o}, out=${a} (likely Logic layer)`),i="Logic",r+=25)}return i==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:i,confidence:r,signals:n}}function Vp(s,e){let t=e.imports.countDependents(s),n=e.imports.countByFile(s);return{inDegree:t,outDegree:n}}function kt(s,e){let t=s.files.getAllPaths().map(m=>({path:m})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let m of t){let f=Bt(m.path,s);n.set(m.path,f),i[f.layer].push({path:m.path,classification:f})}let r={Entry:Tt(i.Entry,e),Logic:Tt(i.Logic,e),Data:Tt(i.Data,e),Utility:Tt(i.Utility,e),Infrastructure:Tt(i.Infrastructure,e),Test:Tt(i.Test,e),Types:Tt(i.Types,e),Unknown:Tt(i.Unknown,e)},o={};t.forEach(m=>{let f=_a.extname(m.path).toLowerCase();f&&(o[f]=(o[f]||0)+1)});let a={".ts":"TypeScript",".tsx":"Typescript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".php":"PHP",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".vue":"Vue"},c={};Object.entries(o).forEach(([m,f])=>{let S=a[m];S&&(c[S]=(c[S]||0)+f)});let l=Object.entries(c).sort((m,f)=>f[1]-m[1]),p=l.length>0?l[0][0]:"Unknown",{pattern:u,patternConfidence:d,insights:h}=Jp(r,t.length,s);return{pattern:u,patternConfidence:d,layers:r,insights:h,primaryStack:p}}function Tt(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:_a.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function Jp(s,e,t){let n=[],i="Unknown",r=0,o=s.Entry.count/e*100,a=s.Logic.count/e*100,c=s.Data.count/e*100,l=s.Utility.count/e*100,p=s.Unknown.count/e*100;o>5&&a>10&&c>5&&p<40?(i="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${a.toFixed(1)}%), Data (${c.toFixed(1)}%)`)):l>20?(i="Modular",r=50+l/2,n.push(`High shared module usage: ${l.toFixed(1)}% utility files`)):p>60&&(i="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let u=t.configs.countByKind("Service");return u>3&&(i="Microservices",r=55+u*5,n.push(`Detected ${u} service definitions (likely microservices)`)),s.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),s.Data.count===0&&n.push("\u26A0\uFE0F No data layer detected - repository may not use traditional ORM patterns"),l>30&&n.push(`High utility concentration (${l.toFixed(1)}%) - good reusability`),{pattern:i,patternConfidence:Math.min(100,r),insights:n}}var Ds,Os,qp,Ut=ee(()=>{"use strict";$s();Ps();Ns();Ds=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],Os=[/Dockerfile/i,/docker-compose/i,/\.ya?ml$/i,/nginx\.conf/i,/\/infra\//i,/\/deploy\//i,/\/k8s\//i,/\/kubernetes\//i,/\/terraform\//i,/\/ansible\//i,/package\.json/i,/tsconfig.*\.json/i,/\.env/i],qp=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});function Uu(s){try{return JSON.stringify(s)}catch{return String(s)}}function qt(s){if(s instanceof Error)return s.message;if(typeof s=="string")return s;if(s&&typeof s=="object"&&"message"in s){let e=s.message;if(typeof e=="string"&&e.trim())return e}return Uu(s)}function Re(s){if(s instanceof Error){let e;return"cause"in s&&s.cause!==void 0&&(e=qt(s.cause)),{errorName:s.name||"Error",errorMessage:s.message,errorStack:s.stack,...e?{errorCause:e}:{}}}return s&&typeof s=="object"?{errorName:s.constructor?.name||"Object",errorMessage:qt(s)}:{errorName:typeof s,errorMessage:qt(s)}}var Cn=ee(()=>{"use strict"});var Va={};cs(Va,{HologramService:()=>Ae});var Qe,Ae,rn=ee(()=>{"use strict";Y();Ut();G();Cn();Qe=w.child({module:"hologram"}),Ae=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=N.getInstance(e)}updateTopography(e){Qe.debug({repoPath:this.repoPath},"Updating topography snapshot");let t=Object.values(e.layers).reduce((r,o)=>r+o.count,0),n={};for(let[r,o]of Object.entries(e.layers)){let a=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(a*10)/10,topFiles:o.topFiles.slice(0,3).map(c=>({path:c.path,confidence:c.confidence}))}}let i={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(i)),Qe.info({repoPath:this.repoPath},"Topography snapshot updated")}refreshTopography(){let e=kt(this.repos,this.repoPath);this.updateTopography(e)}updateGravityZones(e){Qe.debug({repoPath:this.repoPath,count:e.length},"Updating gravity zones");let t={hotspots:e.slice(0,50),updatedAt:Date.now()};this.repos.hologram.upsertSection("gravity",JSON.stringify(t)),Qe.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){Qe.debug({repoPath:this.repoPath,count:e.length},"Updating ghost bridges");let t={bridges:e.slice(0,20),updatedAt:Date.now()};this.repos.hologram.upsertSection("ghosts",JSON.stringify(t)),Qe.info({repoPath:this.repoPath},"Ghost bridges updated")}getSnapshot(){let e=this.repos.hologram.getAllSections(),t={metadata:{repoPath:this.repoPath,lastUpdated:Date.now(),version:"1.0.0"}};for(let n of e)try{let i=JSON.parse(n.data);switch(n.section){case"topography":t.topography=i;break;case"gravity":t.gravity=i;break;case"ghosts":t.ghosts=i;break}}catch(i){Qe.debug({repoPath:this.repoPath,section:n.section,...Re(i)},"Skipping malformed hologram section")}return t}getSection(e){let t=this.repos.hologram.getSection(e);if(!t)return null;try{return JSON.parse(t.data)}catch(n){return Qe.debug({repoPath:this.repoPath,section:e,...Re(n)},"Skipping malformed hologram section"),null}}computeGravityZones(){Qe.debug({repoPath:this.repoPath},"Computing gravity zones from import graph");let e=this.repos.files.getAllPaths(),t=new Map;for(let i of e){let r=Bt(i,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(i);if(o.length===0)continue;let a=this.repos.imports.countDependents(i),c=this.repos.imports.countByFile(i),l=a*2+c;if(l>0){let p=o.find(d=>d.kind!=="TsTypeAliasDeclaration"&&d.kind!=="TsInterfaceDeclaration")||o[0],u=`${i}::${p.name}`;t.set(u,{symbol:p.name,filePath:i,inDegree:a,outDegree:c,gravity:l})}}let n=Array.from(t.values()).sort((i,r)=>r.gravity-i.gravity).slice(0,50);return Qe.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),Qe.info({repoPath:this.repoPath},"Hologram cleared")}}});var Dc={};cs(Dc,{GraphExporterService:()=>pr});var Nc,pr,Oc=ee(()=>{"use strict";Y();G();Nc=w.child({module:"graph-exporter"}),pr=class{constructor(e){this.repoPath=e;this.repos=N.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;Nc.info({focusMissionId:i,depth:r,format:n,includeCompleted:t},"Generating mission graph");let a=this.buildMissionTree(i,t,r,o);return n==="json"?JSON.stringify(a,null,2):this.generateMermaidDiagram(a)}buildMissionTree(e,t,n,i){let r;if(e){let c=this.repos.missions.findById(e);r=c?[c]:[]}else r=this.repos.missions.findAll().filter(l=>!l.parent_id),t||(r=r.filter(l=>l.status!=="completed"));let o=0,a=[];for(let c of r){if(o>=i)break;let l=this.buildNode(c,t,n,1,{count:o,max:i});l&&(a.push(l),o+=this.countNodes(l))}return a}buildNode(e,t,n,i,r){if(i>n||r.count>=r.max)return null;let o;if(e.strategy_graph)try{let p=JSON.parse(e.strategy_graph);o=this.parseStrategySteps(p)}catch(p){Nc.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let a={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},c=this.repos.missions.findByParentId(e.id),l=t?c:c.filter(p=>p.status!=="completed");for(let p of l){if(r.count>=r.max)break;let u=this.buildNode(p,t,n,i+1,r);u&&(a.children.push(u),r.count++)}return a}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,i)=>({id:n.id||`step-${i}`,description:n.description||n.content||n.name||`Step ${i+1}`,status:n.status,dependencies:n.dependencies||n.deps})):e.steps&&Array.isArray(e.steps)?this.parseStrategySteps(e.steps):typeof e=="object"?Object.entries(e).map(([n,i])=>({id:n,description:i.description||i.content||n,status:i.status,dependencies:i.dependencies||i.deps})):t}countNodes(e){let t=1;for(let n of e.children)t+=this.countNodes(n);return t}generateMermaidDiagram(e){let t=["graph TD"];for(let n of e)this.addMermaidNode(n,t);return t.join(`
|
|
599
|
-
`)}addMermaidNode(e,t,n){let i=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),a=`${r} ${e.name}`;if(t.push(` ${i}["${this.escapeMermaid(a)}"]:::${o}`),n&&t.push(` ${n} --> ${i}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let c of e.steps){let l=`S${e.id}_${c.id}`,p=c.status||"pending",u=this.getStatusIcon(p),d=this.getStatusClass(p),h=`${u} ${c.description}`;if(t.push(` ${l}["${this.escapeMermaid(h)}"]:::${d}`),t.push(` ${i} -.-> ${l}`),c.dependencies&&c.dependencies.length>0)for(let m of c.dependencies){let f=`S${e.id}_${m}`;t.push(` ${f} --> ${l}`)}}for(let c of e.children)this.addMermaidNode(c,t,i);n||(t.push(""),t.push(" classDef completed fill:#90EE90,stroke:#2E8B57,stroke-width:2px"),t.push(" classDef inProgress fill:#87CEEB,stroke:#4682B4,stroke-width:2px"),t.push(" classDef planned fill:#FFE4B5,stroke:#DAA520,stroke-width:2px"),t.push(" classDef suspended fill:#D3D3D3,stroke:#808080,stroke-width:2px"),t.push(" classDef failed fill:#FFB6C1,stroke:#DC143C,stroke-width:2px"),t.push(" classDef pending fill:#FFF8DC,stroke:#B8860B,stroke-width:1px"))}getStatusIcon(e){return{completed:"\u2713","in-progress":"\u26A1",planned:"\u{1F4CB}",suspended:"\u23F8",failed:"\u2717",pending:"\u25CB",verifying:"\u{1F50D}"}[e]||"\u25CB"}getStatusClass(e){return{completed:"completed","in-progress":"inProgress",planned:"planned",suspended:"suspended",failed:"failed",pending:"pending",verifying:"inProgress"}[e]||"pending"}escapeMermaid(e){return e.replace(/"/g,"#quot;").replace(/\n/g," ").replace(/\[/g,"#91;").replace(/]/g,"#93;").slice(0,100)}}});import"dotenv/config";import{Cli as fm}from"clerc";G();import wr from"fs";import gl from"path";import xr from"js-yaml";var vr={ignore:[],include:[],maxDepth:10},yl=[{name:".liquid-shadow.yaml",parse:s=>xr.load(s)??{}},{name:".liquid-shadow.yml",parse:s=>xr.load(s)??{}},{name:".ls.json",parse:s=>JSON.parse(s)},{name:".liquid-shadow.json",parse:s=>JSON.parse(s)},{name:".ls.rc",parse:s=>JSON.parse(s)},{name:".liquid-shadow.rc",parse:s=>JSON.parse(s)}];function ct(s){for(let{name:e,parse:t}of yl){let n=gl.join(s,e);if(wr.existsSync(n))try{let i=wr.readFileSync(n,"utf8"),r=t(i);return w.debug({repoPath:s,configFile:e},"Loaded repository configuration"),{...vr,...r}}catch(i){w.error({repoPath:s,file:e,err:i},"Failed to parse configuration file")}}return vr}function ls(s,e){let n=ct(s).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}Y();import Xl from"path";var ye=dl(ro(),1);import*as et from"@clack/prompts";var te={red:ye.default.red,green:ye.default.green,yellow:ye.default.yellow,blue:ye.default.blue,magenta:ye.default.magenta,cyan:ye.default.cyan,white:ye.default.white,gray:ye.default.gray,bold:ye.default.bold,dim:ye.default.dim,italic:ye.default.italic,underline:ye.default.underline,inverse:ye.default.inverse},St=s=>s.replace(/\x1b\[[0-9;]*m/g,""),ge=s=>et.intro(ye.default.bgCyan(ye.default.black(ye.default.bold(` ${s} `)))),Ve=s=>et.outro(ye.default.cyan(s)),ue=(s,e,t="blue")=>{let n=e.split(`
|
|
600
|
-
`),i=St(s),r=Math.max(i.length+4,...n.map(c=>St(c).length))+2,o="\u2500".repeat(r),a=te[t];console.log(a(`\u250C${o}\u2510`)),console.log(a("\u2502 ")+te.bold(s).padEnd(r+(s.length-i.length)-1)+a("\u2502")),console.log(a(`\u251C${o}\u2524`)),n.forEach(c=>{let l=St(c),p=" ".repeat(r-l.length-1);console.log(a("\u2502 ")+c+p+a("\u2502"))}),console.log(a(`\u2514${o}\u2518`))},ni=(s,e)=>{let t=s.map((i,r)=>Math.max(St(i).length,...e.map(o=>St(o[r]||"").length))+2),n=te.cyan("\u2502");console.log(n),console.log(n+" "+s.map((i,r)=>te.bold(te.cyan(i)).padEnd(t[r]+(i.length-St(i).length))).join(te.gray(" "))+" "),e.forEach(i=>{console.log(n+" "+i.map((r,o)=>(r||"").padEnd(t[o]+(r.length-St(r).length))).join(te.gray(" "))+" ")}),console.log(n)},oo=(s,e="\u2022")=>{s.forEach(t=>{console.log(`${te.cyan("\u2502")} ${te.cyan(e)} ${t}`)})},ii=(s,e=40)=>{let t=Math.max(...s.map(i=>i.value)),n=Math.max(...s.map(i=>St(i.label).length));console.log(te.cyan("\u2502")),s.forEach(i=>{let r=Math.round(i.value/t*e),o="\u2588".repeat(r)+te.dim("\u2591".repeat(e-r)),a=i.color?te[i.color]:te.cyan,c=i.label.padEnd(n);console.log(`${te.cyan("\u2502")} ${te.bold(c)} ${a(o)} ${te.white(i.value.toString())}`)}),console.log(te.cyan("\u2502"))},Es=(s,e="")=>{s.forEach((t,n)=>{let i=n===s.length-1,r=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?te[t.color]:t.children?te.blue:te.white,a=t.info?` ${te.gray(`(${t.info})`)}`:"";if(console.log(`${te.cyan("\u2502")} ${e}${te.gray(r)}${o(t.name)}${a}`),t.children&&t.children.length>0){let c=e+(i?" ":"\u2502 ");Es(t.children,c)}})},Oe=()=>et.spinner();async function si(s,e,t){if(e.length===0)return;let n=await et.select({message:s,options:e.map(i=>({value:i.value,label:i.label,...i.hint!=null&&{hint:i.hint}})),...t?.limit!=null&&{maxItems:t.limit}});if(!et.isCancel(n))return n}var Zl=s=>{console.error("");let e=s instanceof Error?s.message:String(s);console.error(` ${te.red("\u2716")} ${te.bold("Error: ")} ${e}`),s instanceof Error&&"cause"in s&&console.error(` ${te.dim("Cause: "+String(s.cause))}`),console.error(""),process.exit(1)},Q=async s=>{try{await s()}catch(e){Zl(e)}},b=te;qe();ut();G();async function ne(s){w.debug("Performing graceful shutdown...");try{await Un()}catch(e){w.error({err:e},"Error shutting down worker pool")}try{s&&Wn(s)}catch(e){w.error({err:e},"Error closing database")}w.debug("Shutdown complete")}async function ao(s){let e=Xl.resolve(s);try{await Q(async()=>{ge("\u{1F311} Liquid Shadow: Scouting Report");let t=N.getInstance(e),n=ct(e),i=n.ignore&&n.ignore.length>0,r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);ue("Intelligence Summary",`${b.bold("\u{1F4E1} Topology")}: ${b.cyan(r.toString())} files mapped
|
|
601
|
-
${b.bold("\u{1F9E9} Symbols")}: ${b.cyan(o.toString())} exports detected
|
|
602
|
-
${b.bold("\u{1F552} Last Sync")}: ${a?b.yellow(new Date(a).toLocaleString()):b.red("Never")}
|
|
603
|
-
${b.bold("\u2699\uFE0F Config")}: ${i?b.green("Custom Intelligence"):b.gray("Standard Sieve")}`,"blue"),c.length>0&&(console.log(""),console.log(` ${b.bold("Symbol Distribution (Top 5)")}`),ii(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),30)),console.log(""),console.log(` ${b.dim("Pro-tip: Try")} ${b.bold(b.cyan("liquid-shadow dashboard"))} ${b.dim("for the full tactical view.")}`),console.log(""),Ve("Scouting complete.")})}finally{await ne(e)}}Y();ut();import fo from"path";var Ss=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];searchHistoryFailureCount=0;recordIndexStart(){this.indexRuns+=1}recordIndexCacheHit(){this.indexCacheHits+=1}recordIndexEnd(e){this.lastIndexDurationMs=e,this.lastIndexCompletedAt=Date.now()}recordIndexPhase(e,t){this.lastRunPhases.push({phase:e,durationMs:t})}clearIndexPhases(){this.lastRunPhases=[]}recordQueryStart(){let e=performance.now();return()=>{this.queryCount+=1;let t=performance.now()-e;if(this.lastQueryLatencyMs=t,this.recentLatencies.push(t),this.recentLatencies.length>100){let n=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-n+t}else this.recentLatencySumMs+=t,this.recentLatencyCount=this.recentLatencies.length}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((n,i)=>n+i,0)/e:null;return{index:{runs:this.indexRuns,cacheHits:this.indexCacheHits,lastDurationMs:this.lastIndexDurationMs,lastCompletedAt:this.lastIndexCompletedAt,lastRunPhases:[...this.lastRunPhases]},query:{count:this.queryCount,lastLatencyMs:this.lastQueryLatencyMs,recentLatencySumMs:this.recentLatencySumMs,recentLatencyCount:e,avgLatencyMs:t,searchHistoryFailures:this.searchHistoryFailureCount},uptimeMs:Date.now()-this.startTime}}reset(){this.indexRuns=0,this.indexCacheHits=0,this.lastIndexDurationMs=null,this.lastIndexCompletedAt=null,this.lastRunPhases=[],this.queryCount=0,this.lastQueryLatencyMs=null,this.recentLatencySumMs=0,this.recentLatencyCount=0,this.recentLatencies=[],this.searchHistoryFailureCount=0}},wt=new Ss;function co(){wt.recordIndexStart()}function ws(){wt.recordIndexCacheHit()}function lo(s){wt.recordIndexEnd(s)}function _n(s,e){wt.recordIndexPhase(s,e)}function po(){wt.clearIndexPhases()}function ri(){return wt.recordQueryStart()}function Qt(){wt.recordSearchHistoryFailure()}function oi(){return wt.getSnapshot()}G();Nt();import se from"fs";import ep from"os";import tt from"path";var Dt=w.child({module:"git-hooks"}),tp="Generated by liquid-shadow",np=1e6,uo=["post-merge","post-checkout","post-commit"];function ip(){let s=process.env.LIQUID_SHADOW_CLI_ENTRY;if(s){let t=tt.resolve(s);if(se.existsSync(t))return t}let e=Le("dist/entry/cli/index.js");return se.existsSync(e)?e:null}function xs(s){return s.includes("liquid-shadow")||s.includes("mcp-liquid-shadow")||s.includes(tp)}function sp(){let s=tt.join(ep.homedir(),".mcp-liquid-shadow","logs"),e=tt.join(s,"post-checkout.log");try{if(!se.existsSync(e)||se.statSync(e).size<=np)return null;se.mkdirSync(s,{recursive:!0});let n=`${e}.1`;return se.existsSync(n)&&se.unlinkSync(n),se.renameSync(e,n),null}catch(t){return`Failed to rotate post-checkout.log: ${t}`}}function rp(s,e){return{"post-merge":`#!/bin/sh
|
|
604
|
-
# Liquid Shadow: Auto-refresh index after merge/pull
|
|
605
|
-
# Generated by liquid-shadow
|
|
606
|
-
|
|
607
|
-
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
608
|
-
|
|
609
|
-
# Run liquid-shadow sync in background to avoid blocking git operations
|
|
610
|
-
nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
611
|
-
|
|
612
|
-
exit 0
|
|
613
|
-
`,"post-checkout":`#!/bin/sh
|
|
614
|
-
# Liquid Shadow: Auto-refresh index after branch checkout
|
|
615
|
-
# Generated by liquid-shadow
|
|
616
|
-
|
|
617
|
-
# Only run on branch checkouts, not file checkouts
|
|
618
|
-
# $3 is 1 for branch checkout, 0 for file checkout
|
|
619
|
-
[ "$3" = "1" ] || exit 0
|
|
620
|
-
|
|
621
|
-
# Skip no-op checkouts where HEAD does not change
|
|
622
|
-
[ "$1" = "$2" ] && exit 0
|
|
623
|
-
|
|
624
|
-
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
625
|
-
LOG_DIR="$HOME/.mcp-liquid-shadow/logs"
|
|
626
|
-
LOG_FILE="$LOG_DIR/post-checkout.log"
|
|
627
|
-
|
|
628
|
-
mkdir -p "$LOG_DIR"
|
|
629
|
-
|
|
630
|
-
# Run incremental index in background (force=false default preserves fast-path)
|
|
631
|
-
nohup "${s}" "${e}" index "$REPO_PATH" --deep >> "$LOG_FILE" 2>&1 &
|
|
632
|
-
|
|
633
|
-
exit 0
|
|
634
|
-
`,"post-commit":`#!/bin/sh
|
|
635
|
-
# Liquid Shadow: Trigger symbol shift detection after commit
|
|
636
|
-
# Generated by liquid-shadow
|
|
637
|
-
|
|
638
|
-
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
639
|
-
|
|
640
|
-
# Run liquid-shadow sync in background
|
|
641
|
-
nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
642
|
-
|
|
643
|
-
exit 0
|
|
644
|
-
`}}function mo(s){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=s,i=tt.join(e,".git","hooks"),r=[],o=[],a=[];if(!se.existsSync(tt.join(e,".git")))return a.push("Not a git repository"),{installed:r,skipped:o,errors:a};se.existsSync(i)||se.mkdirSync(i,{recursive:!0});let c=ip();if(!c)return a.push(`Unable to resolve CLI entry at install time. Expected ${Le("dist/entry/cli/index.js")} to exist.`),{installed:r,skipped:o,errors:a};let l=rp(process.execPath,c),p=new Set;if(t&&(p.add("post-merge"),p.add("post-checkout")),n&&p.add("post-commit"),p.has("post-checkout")){let u=sp();u&&(a.push(u),Dt.warn({rotationError:u},"Post-checkout log rotation failed"))}for(let u of p){let d=tt.join(i,u),h=l[u];if(!h){a.push(`No template found for hook: ${u}`);continue}try{if(se.existsSync(d)){let m=se.readFileSync(d,"utf-8"),f=xs(m);if(f&&m===h){se.chmodSync(d,493),o.push(u),Dt.info({hookName:u},"Hook already installed, skipping");continue}if(!f){let S=`${d}.backup-${Date.now()}`;se.copyFileSync(d,S),Dt.info({hookName:u,backupPath:S},"Backed up existing hook")}}se.writeFileSync(d,h,{mode:493}),se.chmodSync(d,493),r.push(u),Dt.info({hookName:u},"Installed git hook")}catch(m){a.push(`Failed to install ${u}: ${m}`),Dt.error({hookName:u,err:m},"Failed to install hook")}}return{installed:r,skipped:o,errors:a}}function ho(s){let e=tt.join(s,".git","hooks"),t=[],n=[];if(!se.existsSync(e))return{removed:t,errors:n};for(let i of uo){let r=tt.join(e,i);try{if(se.existsSync(r)){let o=se.readFileSync(r,"utf-8");xs(o)&&(se.unlinkSync(r),t.push(i),Dt.info({hookName:i},"Removed git hook"))}}catch(o){n.push(`Failed to remove ${i}: ${o}`),Dt.error({hookName:i,err:o},"Failed to remove hook")}}return{removed:t,errors:n}}function op(s,e){let t=tt.join(s,".git","hooks"),n=tt.join(t,e);if(!se.existsSync(t)||!se.existsSync(n))return"missing";try{let i=se.readFileSync(n,"utf-8");return xs(i)?(se.statSync(n).mode&73)!==0?"installed":"disabled":"foreign"}catch{return"foreign"}}function Zt(s){let e=[],t=[],n=[],i=[],r={};for(let a of uo){let c=op(s,a);r[a]=c,c==="installed"&&e.push(a),c==="missing"&&t.push(a),c==="foreign"&&n.push(a),c==="disabled"&&i.push(a)}let o=[...t,...n,...i];return{installed:e,notInstalled:o,missing:t,foreign:n,disabled:i,statuses:r}}async function vs(s){let e=fo.resolve(s);try{await Q(async()=>{ge("Liquid Shadow Intelligence Dashboard");let t=N.getInstance(e),n=oi(),i=Zt(e),r=t.files.getCount(),o=t.exports.getCount(),a=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);if(ue("Operational Core",`${b.bold("State")}: ${pt(e)?b.green("IDENTIFIED (Stable)"):b.red("UNKNOWN (Needs Index)")}
|
|
645
|
-
${b.bold("Repository")}: ${b.cyan(fo.basename(e))}
|
|
646
|
-
${b.bold("Infrastructure")}: ${i.installed.length>0?b.green("Git-Hooked"):b.yellow("Standalone")}
|
|
647
|
-
${b.bold("Last Sync")}: ${a?b.yellow(new Date(a).toLocaleString()):b.red("Never")}`,"blue"),console.log(""),ue("Intelligence Density",`${b.bold("Files Target")}: ${b.cyan(r.toString())}
|
|
648
|
-
${b.bold("Symbols Mapped")}: ${b.cyan(o.toString())}
|
|
649
|
-
${b.bold("Graph Edges")}: ${b.cyan(t.imports.getCount().toString())}
|
|
650
|
-
${b.bold("Hotspots")}: ${b.yellow(c.length.toString())}`,"cyan"),n.query.count>0||n.index.runs>0){console.log("");let l=n.index.runs>0?(n.index.cacheHits/n.index.runs*100).toFixed(1):"0.0";ue("Reasoning Efficiency",`${b.bold("Query Count")}: ${b.cyan(n.query.count.toString())}
|
|
651
|
-
${b.bold("Avg Latency")}: ${b.yellow(`${n.query.avgLatencyMs?.toFixed(2)||0}ms`)}
|
|
652
|
-
${b.bold("Cache Hit Rate")}: ${b.green(`${l}%`)}`,"green")}c.length>0&&(console.log(""),console.log(` ${b.bold("Intelligence Landscape")}`),ii(c.map(l=>({label:l.kind,value:l.c,color:"cyan"})),35)),console.log(""),Ve("Liquid Shadow is observing.")})}finally{await ne(e)}}Y();ut();import ap from"path";async function go(s){let e=ap.resolve(s);try{await Q(async()=>{let t=N.getInstance(e),n=Zt(e),i=oi(),r=Math.floor(i.uptimeMs/1e3),o=Math.floor(r/60),a=Math.floor(o/60),c=a>0?`${a}h ${o%60}m`:o>0?`${o}m ${r%60}s`:`${r}s`,l=i.index.lastCompletedAt?new Date(i.index.lastCompletedAt).toLocaleString():"Never",p=i.index.lastDurationMs?`${(i.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",u=i.query.avgLatencyMs?`${i.query.avgLatencyMs.toFixed(2)}ms`:"N/A",d=i.query.lastLatencyMs?`${i.query.lastLatencyMs.toFixed(2)}ms`:"N/A",h=i.index.runs>0?(i.index.cacheHits/i.index.runs*100).toFixed(1):"0.0";ue("Performance Metrics",`${b.bold("Uptime")}: ${b.cyan(c)}
|
|
653
|
-
${b.bold("Indexed")}: ${pt(e)?b.green("Yes"):b.red("No")}
|
|
654
|
-
${b.bold("Files")}: ${b.cyan(t.files.getCount().toString())}
|
|
655
|
-
${b.bold("Exports")}: ${b.cyan(t.exports.getCount().toString())}
|
|
656
|
-
${b.bold("Imports")}: ${b.cyan(t.imports.getCount().toString())}
|
|
657
|
-
${b.bold("Last Indexed Commit")}: ${fn(e)?b.yellow(fn(e).substring(0,7)):b.red("None")}
|
|
658
|
-
${b.bold("Git Hooks")}: ${n.installed.length>0?b.green("Installed"):b.yellow("Not Installed")}`,"blue"),console.log(""),ue("Index Metrics",`${b.bold("Total Runs")}: ${b.cyan(i.index.runs.toString())}
|
|
659
|
-
${b.bold("Cache Hits")}: ${b.cyan(i.index.cacheHits.toString())}
|
|
660
|
-
${b.bold("Cache Hit Rate")}: ${b.cyan(`${h}%`)}
|
|
661
|
-
${b.bold("Last Duration")}: ${b.yellow(p)}
|
|
662
|
-
${b.bold("Last Completed")}: ${b.yellow(l)}`,"cyan"),i.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${b.bold("Last Index Run Phases:")}`),i.index.lastRunPhases.forEach(m=>{let f=`${(m.durationMs/1e3).toFixed(2)}s`;console.log(` ${b.gray(m.phase.padEnd(20))} ${b.cyan(f)}`)})),console.log(""),ue("Query Metrics",`${b.bold("Total Queries")}: ${b.cyan(i.query.count.toString())}
|
|
663
|
-
${b.bold("Avg Latency")}: ${b.yellow(u)}
|
|
664
|
-
${b.bold("Last Latency")}: ${b.yellow(d)}
|
|
665
|
-
${b.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?b.red(i.query.searchHistoryFailures.toString()):b.green("0")}`,"green")})}finally{await ne(e)}}import lu from"path";G();import La from"path";import cu from"ignore";import Ma from"fs";import ai from"path";var cp=50;function ci(s,e,t,n){let i={name:ai.basename(e)||e,type:"directory",path:e,children:[]};return s.forEach(r=>{let a=ai.relative(e,r.path).split(ai.sep),c=i;for(let l=0;l<a.length;l++){let p=a[l];if(n!==void 0&&l>=n)return;let u=l===a.length-1;if(n===1&&l===0&&u)return;let d=n!==void 0&&l===n-1&&!u,h=ai.join(e,...a.slice(0,l+1)),m=c.children?.find(f=>f.name===p);if(!m){if(c.children&&c.children.length>=cp){c.children.find(y=>y.type==="truncated")||c.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}m={name:p,type:u?"file":"directory",path:h,children:u||d?void 0:[],summary:u?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},m.summary&&(t==="structure"||t==="signatures")&&(delete m.summary.chunks,delete m.summary.imports),c.children?.push(m)}c=m}}),i}import lp from"fast-glob";import bo from"fs";import pp from"ignore";import _o from"path";var li=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],yo=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],Fe={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},ve={FILTERED_QUERY_LIMIT_MULTIPLIER:3,SCORE_BASE:1e3,EXACT_MATCH_BONUS:500,RECENT_FILE_BOOST:80,OLDER_FILE_BOOST:30,RECENT_FILE_THRESHOLD_DAYS:7,OLDER_FILE_THRESHOLD_DAYS:30,FUZZY_MATCH_LIMIT:30,ENABLE_LEXICAL_SCORING:process.env.ENABLE_LEXICAL_SCORING!=="false",LEXICAL_WEIGHT:parseFloat(process.env.LEXICAL_WEIGHT??String(.4)),GRAVITY_STRUCTURAL_WEIGHT:.5},Rs={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},pi={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function Eo(s,e=[]){let t=pp(),n=_o.join(s,".gitignore");return bo.existsSync(n)&&t.add(bo.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await lp(yo,{cwd:s,absolute:!0,ignore:li,stats:!0})).filter(o=>{let a=_o.relative(s,o.path);return!t.ignores(a)}).map(o=>({path:o.path,mtime:o.stats.mtimeMs}))}import Do from"fs";function So(s){let e=s.split(`
|
|
666
|
-
`),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function re(s,e){for(let t=0;t<e.length;t++)if(e[t+1]>s||t===e.length-1)return t+1;return 1}function ui(s,e){return e.slice(0,s).toString("utf8").length}function wo(s){if(s.toString("utf8").length===s.length)return n=>n;let t=new Map;return n=>{let i=t.get(n);return i===void 0&&(i=s.slice(0,n).toString("utf8").length,t.set(n,i)),i}}function xo(s,e,t){let n=s.start-e,i=s.end-e;return n<0||i>t.length?"":t.slice(n,i).toString("utf8")}function vo(s){let e=[],t=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=t.exec(s))!==null;)e.push({start:n.index,end:n.index+n[0].length,text:n[0]});return e}function nt(s,e,t){for(let n of e){if(n.start===s)return n.text;if(n.start>s&&n.start<s+50){let i=t.substring(s,n.start);if(/^\s*$/.test(i))return n.text}if(n.end<=s&&n.end>s-50){let i=t.substring(n.end,s);if(/^\s*$/.test(i))return n.text}}return""}function Ro(s){if(!s)return"";let t=s.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
|
|
667
|
-
`)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function di(s,e,t){let n=s.toLowerCase(),i=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||i.startsWith("use")?"Hook":n.includes("models/")||i.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||i.endsWith("service")||i.endsWith("controller")||i.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||i.endsWith("repository")||i.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function En(s){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(s)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(s)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(s)||/\.query\s*\(|\.execute\s*\(/i.test(s)&&/db|database|client|pool/i.test(s))&&e.push("Database"),(/\bfs\./i.test(s)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(s)||/import\s+.*\bfs\b/.test(s))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(s)||/\bdocument\.cookie\b/.test(s))&&e.push("Browser Storage"),e}function We(s,e){if(!s)return"";let t=s.trimStart();for(;/^\/\*[\s\S]*?\*\//.test(t);)t=t.replace(/^\/\*[\s\S]*?\*\/\s*/,"");for(;/^\/\/[^\n]*\n/.test(t);)t=t.replace(/^\/\/[^\n]*\n\s*/,"");if(t=t.replace(/^(?:import[^\n]*\n)+/,"").replace(/^(?:export\s+\{[^}]*\}\s+from\s+['"][^'"]+['"];?\s*\n?)+/,"").trim(),e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,i=0,r=t.length;for(let a=0;a<t.length;a++){let c=t[a];if(c==="(")n++;else if(c===")")n--;else if(c==="<")i++;else if(c===">")i--;else if(c==="{"){if(n===0&&i===0){r=a;break}}else if(c===";"&&n===0&&i===0){r=a;break}else if(c==="="&&t[a+1]===">"&&n===0&&i===0){r=a+2;break}}let o=t.substring(0,r).trim();return o.length>500?o.slice(0,497)+"...":o}function To(s){let e=[];for(let t of s)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join(", ")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function up(s,e){for(let t of s){if((t.type==="FunctionDeclaration"||t.type==="ClassDeclaration")&&(t.identifier?.value||t.id?.value)===e)return t.span;if(t.type==="VariableDeclaration"){for(let n of t.declarations)if(n.id?.type==="Identifier"&&n.id.value===e)return n.span||t.span}if((t.type==="TsTypeAliasDeclaration"||t.type==="TsInterfaceDeclaration"||t.type==="TsEnumDeclaration")&&(t.id?.value||t.identifier?.value)===e)return t.span;if(t.type==="ExportDeclaration"){let n=t.declaration;if(!n)continue;if((n.type==="FunctionDeclaration"||n.type==="ClassDeclaration")&&(n.identifier?.value||n.id?.value)===e)return n.span||t.span;if(n.type==="VariableDeclaration"){for(let i of n.declarations)if(i.id?.type==="Identifier"&&i.id.value===e)return i.span||n.span||t.span}}}return null}function ko(s,e,t,n,i,r,o,a,c){let l=c??(u=>ui(u,t)),p=[];for(let u of s){if(u.type==="ExportDeclaration"){let d=u.declaration,h=d.type,m="";h==="VariableDeclaration"?m=d.declarations.map(R=>R.id.value).join("",""):m=d.id?.value||d.identifier?.value||"anonymous";let f=l(u.span.start-e),S=l(u.span.end-e),y=nt(f,r,n),_=a(u.span),E=[];if(u.type==="ExportDeclaration"&&(h==="ClassDeclaration"||h==="ClassExpression")){let R=d.body||[];for(let T of R)if(T.type==="ClassMethod"||T.type==="ClassProperty"){let k=T.key.value;if(!k)continue;let F=l(T.span.start-e),B=l(T.span.end-e),M=a(T.span),v=nt(F,r,n);E.push({name:k,kind:T.type,signature:We(M,T.type),line:re(F,i),endLine:re(B,i),doc:v,classification:T.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(h==="FunctionDeclaration"&&d.body?.type==="BlockStatement")E=Ts(d.body.stmts,e,t,n,i,r,a,l);else if(h==="VariableDeclaration"){for(let R of d.declarations)if(R.init&&(R.init.type==="ArrowFunctionExpression"||R.init.type==="FunctionExpression")&&R.init.body?.type==="BlockStatement"){E=Ts(R.init.body.stmts,e,t,n,i,r,a,l);break}}p.push({name:m,kind:h,signature:We(_,h),line:re(f,i),endLine:re(S,i),doc:y,classification:di(o,m,h),capabilities:JSON.stringify(En(_)),members:E})}if(u.type==="ExportNamedDeclaration"){for(let d of u.specifiers)if(d.type==="ExportSpecifier"){let h=d.orig.value,m=d.exported?.value||h,S=up(s,h)||u.span,y=l(S.start-e),_=l(S.end-e),E=nt(y,r,n);p.push({name:m,kind:"ExportSpecifier",signature:`export { ${h} }`,line:re(y,i),endLine:re(_,i),doc:E,classification:"Export mapping",capabilities:"[]"})}}if(u.type==="ExportDefaultDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=nt(d,r,n),f=a(u.span),S=[];if(u.decl.type==="ClassExpression"||u.decl.type==="ClassDeclaration"){let y=u.decl.body||[];for(let _ of y)if(_.type==="ClassMethod"||_.type==="ClassProperty"){let E=_.key.value;if(!E)continue;let R=l(_.span.start-e),T=l(_.span.end-e),k=a(_.span),F=nt(R,r,n);S.push({name:E,kind:_.type,signature:We(k,_.type),line:re(R,i),endLine:re(T,i),doc:F,classification:_.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(u.decl.type==="FunctionExpression"||u.decl.type==="FunctionDeclaration"||u.decl.type==="ArrowFunctionExpression")&&u.decl.body?.type==="BlockStatement"&&(S=Ts(u.decl.body.stmts,e,t,n,i,r,a,l));p.push({name:"default",kind:"DefaultExport",signature:We(f,"DefaultExport"),line:re(d,i),endLine:re(h,i),doc:m,classification:"Default Export",capabilities:JSON.stringify(En(f)),members:S})}if(u.type==="ExportAllDeclaration"){let d=l(u.span.start-e),h=l(u.span.end-e),m=u.source.value,f=nt(d,r,n);p.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${m}"`,line:re(d,i),endLine:re(h,i),doc:f,classification:"Re-export",capabilities:"[]"})}}return p}function Ts(s,e,t,n,i,r,o,a){let c=[];for(let l of s){if(l.type==="VariableDeclaration")for(let p of l.declarations){let u=[],d=m=>{if(m.type==="Identifier")u.push({name:m.value,span:m.span});else if(m.type==="ArrayPattern")for(let f of m.elements)f&&d(f);else if(m.type==="ObjectPattern")for(let f of m.properties)f.type==="AssignmentPatternProperty"?u.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&d(f.value)};d(p.id);let h=p.init&&(p.init.type==="ArrowFunctionExpression"||p.init.type==="FunctionExpression");for(let m of u){let f=h?p.init.span||p.span||m.span:p.span||m.span,S=h?p.init.type:"VariableDeclaration",y=h?"Internal Function":"Internal Variable",_=a(f.start-e),E=a(f.end-e),R=o(f),T=nt(_,r,n);c.push({name:m.name,kind:S,signature:We(R,S),line:re(_,i),endLine:re(E,i),doc:T,classification:y,capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let p=l.identifier?.value||l.ident?.value||"anonymous",u=a(l.span.start-e),d=a(l.span.end-e),h=o(l.span),m=nt(u,r,n);c.push({name:p,kind:"FunctionDeclaration",signature:We(h,"FunctionDeclaration"),line:re(u,i),endLine:re(d,i),doc:m,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let p of l.argument.properties){let u="",d=p.span||p.key?.span||p.ident?.span;if(p.type==="KeyValueProperty"){let h=p.key;u=h?.value||h?.raw||(h?.type==="Identifier"?h.value:"")}else p.type==="MethodProperty"?u=p.key?.value||p.key?.raw||"":p.type==="ShorthandProperty"?u=p.ident?.value||"":p.type==="Identifier"&&(u=p.value||"");if(u&&d){let h=a(d.start-e),m=a(d.end-e),f=o(d),S=nt(h,r,n);c.push({name:u,kind:"ReturnProperty",signature:We(f,"ReturnProperty"),line:re(h,i),endLine:re(m,i),doc:S,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let p=l.expression;if(p.callee.type==="MemberExpression"&&(p.callee.property?.value==="on"||p.callee.property?.value==="once")){let u=p.arguments[0]?.expression?.value,d=p.arguments[1]?.expression;if(u&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let h=a(d.span.start-e),m=a(d.span.end-e),f=o(d.span);c.push({name:`on:${u}`,kind:d.type,signature:We(f,d.type),line:re(h,i),endLine:re(m,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(p.callee.type==="Identifier"&&p.callee.value==="addRoute"&&p.arguments.length>=3){let u=p.arguments[2].expression;if(u.type==="StringLiteral"){let d=u.value,h=a(p.span.start-e),m=a(p.span.end-e),f=o(p.span);c.push({name:d,kind:"HTTP Route",signature:We(f,"HTTP Route"),line:re(h,i),endLine:re(m,i),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:d})})}}}}return c}function Co(s,e,t,n,i,r){let o=r??(l=>ui(l,t)),a=[];function c(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let p=dp(l);if(p){let u=o(l.span.start-e);a.push({...p,line:re(u,n),snippet:i(l.span)})}}for(let p of Object.keys(l)){if(p==="span")continue;let u=l[p];Array.isArray(u)?u.forEach(c):typeof u=="object"&&c(u)}}}return s.forEach(c),a}function dp(s){let{callee:e,arguments:t}=s;if(!t||t.length===0)return null;if(e.type==="Identifier"&&e.value,e.type==="Identifier"&&e.value==="addRoute"&&t.length>=3){let n=t[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value,o=e.object.type==="Identifier"?e.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(o))return{type:"api_route",name:r,direction:"produce"};if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function Sn(s){let{classification:e,capabilities:t,exports:n,fileName:i}=s,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(m=>r[m]).filter(Boolean).join(" and "),c={Component:(m,f)=>{let S=f.find(_=>_.kind==="FunctionDeclaration"||_.kind==="ClassDeclaration")?.name,y=S?`React component: ${S}`:"React UI component";return m?`${y} with ${m}`:y},Hook:(m,f)=>{let S=f.find(_=>_.name.startsWith("use"))?.name,y=S?`Custom React hook: ${S}`:"Custom React hook";return m?`${y} for ${m}`:y},Service:(m,f)=>{let y=`Service layer: ${f[0]?.name||"Service"}`;return m?`${y} handling ${m}`:y},Repository:(m,f)=>`Data repository: ${f[0]?.name||"Repository"} for ${m||"data access"}`,"Type Definition":(m,f)=>`Type definitions: ${f.slice(0,3).map(y=>y.name).join("")}${f.length>3?"...":""}`,Model:(m,f)=>`Data model: ${f[0]?.name||"Model"}`,"HTTP Route":(m,f)=>{let S=f.filter(y=>y.classification==="Service Boundary");return S.length>0?`API endpoints: ${S.slice(0,3).map(y=>y.name).join("")}`:"API route handler"},"Micro IR (PHP)":(m,f)=>{let S=f.some(_=>_.classification==="Service Boundary"),y=f.find(_=>_.kind==="ClassDeclaration")?.name;return S?"PHP controller with API routes":y?`PHP class: ${y}`:"PHP module"},"Micro IR (Python)":(m,f)=>{let S=f.some(_=>_.classification==="Service Boundary"),y=f.find(_=>_.kind==="ClassDeclaration")?.name;return S?"Python API handler with routes":y?`Python class: ${y}`:"Python module"},"Micro IR (Go/TS) ":(m,f)=>{let S=f.some(_=>_.kind==="TypeDeclaration"),y=f.filter(_=>_.kind==="FunctionDeclaration");return S&&y.length>0?`Go package: types and ${y.length} function(s)`:S?"Go package: type definitions":y.length>0?`Go package: ${y[0].name} and ${y.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(m,f)=>{let S=f.find(E=>E.kind==="TraitDeclaration")?.name,y=f.find(E=>E.kind==="StructDeclaration")?.name,_=f.filter(E=>E.kind==="FunctionDeclaration");return S?m.includes("Rust trait")?`Rust module: trait ${S}`:`Rust module: ${S}`:y?`Rust module: struct ${y}`:_.length>0?`Rust module: ${_.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return i?`Module: ${i}`:"Module with no exports";let l=n.filter(m=>m.kind==="FunctionDeclaration"),p=n.filter(m=>m.kind==="ClassDeclaration"),u=n.filter(m=>m.kind==="TsInterfaceDeclaration"||m.kind==="TsTypeAliasDeclaration"),d=[];if(p.length>0&&d.push(`Class: ${p[0].name}`),l.length>0){let m=l.slice(0,2).map(f=>f.name).join("");d.push(`Functions: ${m}`)}u.length>0&&d.push(`Types: ${u.length}`);let h=d.length>0?d.join(" | "):`Module with ${n.length} export(s)`;return o?`${h} \u2014 ${o}`:h}function Io(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&de(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&de(n,e);for(let i in n){if(i==="span"||i==="comments"||i==="interpreter")continue;let r=n[i];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return s.forEach(n=>t(n)),Array.from(e)}function de(s,e){if(s){if(s.type==="TsTypeAnnotation"){de(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&Lo(s.typeName,e),s.typeParams&&de(s.typeParams,e)),s.type==="TsArrayType"&&de(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>de(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>de(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>de(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>de(t.typeAnnotation,e)),s.typeAnnotation&&de(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&de(t.constraint,e),t.default&&de(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>de(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&de(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(de(s.objectType,e),de(s.indexType,e)),s.type==="TsConditionalType"&&(de(s.checkType,e),de(s.extendsType,e),de(s.trueType,e),de(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&de(t.typeAnnotation,e)})}}function Lo(s,e){s.type==="TsQualifiedName"?(s.left&&Lo(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}import Oo from"path";import ks from"path";G();Nt();import Ao from"path";import mp from"fs";import{fileURLToPath as hp}from"url";import*as Ot from"web-tree-sitter";var Vf=Ao.dirname(hp(import.meta.url)),Mo=w.child({module:"parser:tree-sitter"}),mi=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=Ot.Parser||Ot;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=Le("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!mp.existsSync(t))return Mo.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await Ot.Language.load(t);return this.languages.set(e,n),n}catch(n){return Mo.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
|
|
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`
|
|
668
670
|
(function_definition name: (name) @name) @func
|
|
669
671
|
(class_declaration name: (name) @name) @class
|
|
670
672
|
(interface_declaration name: (name) @name) @interface
|
|
@@ -682,284 +684,214 @@ ${b.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?b.red(i.
|
|
|
682
684
|
(type_declaration (type_spec name: (identifier) @name)) @type
|
|
683
685
|
(import_spec path: (interpreted_string_literal) @name) @import
|
|
684
686
|
`;case".rs":return`
|
|
685
|
-
(function_item name: (identifier) @name) @func
|
|
686
|
-
(struct_item name: (_type_identifier) @name) @struct
|
|
687
|
-
(enum_item name: (_type_identifier) @name) @enum
|
|
688
|
-
(trait_item name: (_type_identifier) @name) @trait
|
|
689
|
-
(type_item name: (_type_identifier) @name) @type
|
|
690
|
-
(use_declaration argument: (_) @name) @import
|
|
691
|
-
`;default:return""}}mapKind(e,t){if(e==="import")return"ImportDeclaration";if(t===".php"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration";if(e==="interface")return"InterfaceDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="method")return"MethodDeclaration"}if(t===".py"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration"}if(t===".go"){if(e==="func")return"FunctionDeclaration";if(e==="type")return"TypeDeclaration"}if(t===".rs"){if(e==="func")return"FunctionDeclaration";if(e==="struct")return"StructDeclaration";if(e==="enum")return"EnumDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(e){return e==="import"?"Dependency":e==="func"||e==="method"?"Function":e==="class"||e==="interface"||e==="trait"||e==="struct"||e==="enum"||e==="type"?"Class":"Other"}async parse(e,t){await this.ensureInitialized();let n=
|
|
692
|
-
`),a=this.getQueries(n);if(!a)return[];let l=new
|
|
693
|
-
`),o="",a="",c=0,l=0,
|
|
694
|
-
`).trim(),capabilities:JSON.stringify(
|
|
695
|
-
`).trim(),capabilities:JSON.stringify({attributes:
|
|
696
|
-
`).trim(),capabilities:JSON.stringify({attributes:
|
|
697
|
-
`).trim(),capabilities:JSON.stringify(
|
|
698
|
-
`).trim();if(
|
|
699
|
-
`).trim(),capabilities:JSON.stringify({visibility:
|
|
700
|
-
`),r=[{indent:-1,name:"root",type:"root"}],o=[],a=/^class\s+([a-zA-Z0-9_]+)/,c=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,l=/^(?:from\s+([a-zA-Z0-9_
|
|
701
|
-
`).trim()),
|
|
702
|
-
`);for(let l of o.rules){l.regex.lastIndex=0;let
|
|
703
|
-
`).length,h=fp(a,d-1);i.push({name:u.name||"anonymous",kind:u.kind||"Unknown",classification:u.classification||"Other",signature:u.signature||p[0],line:d,endLine:h,doc:"",capabilities:JSON.stringify(u.meta||{})})}}let c=Sn({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:i.map(l=>({name:l.name,kind:l.kind,classification:l.classification})),fileName:ks.basename(e)});return{exports:i,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:c||"Module",parseStatus:i.length>0?"success":"partial"}}};G();import*as Cs from"@swc/core";function Po(s){if(!s||typeof s!="object")return!1;let e=s;return typeof e.parse=="function"&&typeof e.parseSync=="function"}function yp(){if(Po(Cs))return Cs;let s=Cs;if(Po(s.default))return s.default;throw new Error("SWC runtime unavailable: couldn't resolve parse/parseSync from @swc/core exports")}var No=yp();function Is(s,e,t){return No.parse(s,e,t)}function yi(s,e,t){return No.parseSync(s,e,t)}var Ls=new gi;async function wn(s){let e=Oo.extname(s);if(Ls.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=await Do.promises.readFile(s,"utf-8");return{...await Ls.parse(s,r),content:r}}catch(r){return w.error({filePath:s,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:r.message}}let t;try{t=await Do.promises.readFile(s)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),i=So(n);try{let r=s.endsWith(".tsx"),o=s.endsWith(".d.ts")||s.endsWith(".d.tsx"),a,c={syntax:"typescript",tsx:r,decorators:!0,comments:!0};if(o)try{a=yi(n,c)}catch{a=yi(n,{...c,isModule:!1})}else a=yi(n,c);let l=a.span.start,p=wo(t),u=vo(n),d=T=>xo(T,l,t),h=To(a.body),m=Io(a.body);m.length>0&&w.debug({filePath:s,count:m.length},"Extracted type references"),m.forEach(T=>{h.push({module:"__type_reference__",name:T})});let f=ko(a.body,l,t,n,i,u,s,d,p),S=Co(a.body,l,t,i,d,p),y=di(s,"","Module"),E=u.length>0&&n.slice(0,u[0].start).trim().length===0?u[0].text:f.find(T=>T.doc)?.doc||"",R=Ro(E);if(!R&&f.length>0){let T=En(n);R=Sn({classification:y,capabilities:T,exports:f.map(k=>({name:k.name,kind:k.kind,classification:k.classification})),fileName:Oo.basename(s)})}return{exports:f,imports:h,events:S,classification:y,summary:R,content:n,parseStatus:"success"}}catch(r){w.warn({filePath:s,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=await Ls.parse(s,n);return{...o,content:n,classification:o.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return w.error({filePath:s,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}G();import Ws from"p-limit";ut();import zs from"path";import iu from"fs";import su from"os";import Ye from"path";import en from"fs";import{loadConfig as Ep,createMatchPath as Sp}from"tsconfig-paths";import xt from"path";import xn from"fs";var vt=class extends Error{constructor(t,n,i){super(n);this.code=t;this.cause=i;this.name="FileSystemError"}};function Fo(s){let e;try{e=xn.statSync(s).isDirectory()?s:xt.dirname(s)}catch(t){throw t.code==="ENOENT"?new vt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new vt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new vt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==xt.dirname(e);){let t=xt.join(e,"tsconfig.json");if(xn.existsSync(t))return e;e=xt.dirname(e)}return null}function Wo(s){let e;try{e=xn.statSync(s).isDirectory()?s:xt.dirname(s)}catch(t){throw t.code==="ENOENT"?new vt("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new vt("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new vt("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==xt.dirname(e);){let t=xt.join(e,"package.json");if(xn.existsSync(t))try{if(JSON.parse(xn.readFileSync(t,"utf8")).workspaces)return e}catch{}e=xt.dirname(e)}return null}import Xt from"path";import Ft from"fs";function zo(s,e){let t=new Map,n=e.workspaces||[];for(let i of n){let r=i.replace("/*",""),o=Xt.join(s,r);if(!Ft.existsSync(o))continue;let a=Ft.readdirSync(o);for(let c of a){let l=Xt.join(o,c,"package.json");if(Ft.existsSync(l))try{let p=JSON.parse(Ft.readFileSync(l,"utf8"));p.name&&t.set(p.name,{name:p.name,path:Xt.dirname(l),main:p.main||"dist/index.js"})}catch{}}}return t}function Ho(s){let e=new Map;try{let t=JSON.parse(Ft.readFileSync(s,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[i,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),a=Xt.dirname(s),c=Xt.resolve(a,o),l=Xt.join(c,"package.json");if(Ft.existsSync(l))try{let p=JSON.parse(Ft.readFileSync(l,"utf8"));e.set(i,{name:i,path:c,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import Bo from"path";import Je from"fs";var bp=[".ts",".tsx",".d.ts",".js",".jsx"];function Rt(s){let e=Bo.extname(s);if(e===".js"||e===".jsx"){let t=s.slice(0,-e.length),n=e===".jsx"?[".tsx",".ts"]:[".ts",".tsx"];for(let i of n){let r=t+i;if(Je.existsSync(r)&&Je.statSync(r).isFile())return r}if(Je.existsSync(s)&&Je.statSync(s).isFile())return s}if(Je.existsSync(s)&&Je.statSync(s).isFile())return s;for(let t of bp){let n=s+t;if(Je.existsSync(n)&&Je.statSync(n).isFile())return n}if(Je.existsSync(s)&&Je.statSync(s).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=Bo.join(s,"index"+t);if(Je.existsSync(n))return n}return""}import{builtinModules as _p,createRequire as kg}from"node:module";var Lg=new Set(_p.map(s=>s.replace(/^node:/,"")));var _i=new Map;function bi(s){let e=Fo(s);if(!e)return null;if(_i.has(e))return _i.get(e)||null;let t=Ep(e);if(t.resultType==="failed")return _i.set(e,null),null;let n=t,i=n.absoluteBaseUrl;!i&&n.paths&&Object.keys(n.paths).length>0&&(i=n.configFileAbsolutePath?Ye.dirname(n.configFileAbsolutePath):e);let r=Sp(i,n.paths,n.mainFields,n.addMatchAll),o=Wo(e),a=new Map;if(o){let u=Ye.join(o,"package.json");if(en.existsSync(u))try{let d=JSON.parse(en.readFileSync(u,"utf8"));a=zo(o,d)}catch{}}let c=Ye.join(e,"package.json");en.existsSync(c)&&Ho(c).forEach((d,h)=>a.set(h,d));let l={baseUrl:i||"",paths:n.paths,matchPath:r,workspacePackages:a,imports:new Map},p=Ye.join(e,"package.json");if(en.existsSync(p))try{let u=JSON.parse(en.readFileSync(p,"utf8"));if(u.imports){for(let[d,h]of Object.entries(u.imports))if(typeof h=="string"||typeof h=="object"&&h!==null){let m=h;Array.isArray(h)&&(m=h[0]),typeof m=="object"&&(m=m.default||m.node),typeof m=="string"&&l.imports.set(d,m)}}}catch{}return _i.set(e,l),l}function Wt(s,e,t){if(!s)return"";if(s.includes(".")&&!s.startsWith(".")&&!s.startsWith("/")&&!s.endsWith(".js")&&!s.endsWith(".ts")&&!s.endsWith(".json")){let i=s.split(".")[0];if(i&&i!==s){let r=Wt(i,e,t);if(r)return r}}if(s.startsWith(".")){let i=Ye.dirname(e),r=Ye.resolve(i,s);return Rt(r)}let n=bi(e);if(n){let i=n.matchPath(s);if(i)return Rt(i);if(!s.startsWith("@")||s.startsWith("@/")){let o=Ye.resolve(n.baseUrl,s),a=Rt(o);if(a)return a}for(let[o,a]of n.imports.entries())if(o.includes("*")){let c="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",l=new RegExp(c),p=s.match(l);if(p){let u=p[1],d=a.replace("*",u),h=Ye.resolve(n.baseUrl,d);return Rt(h)}}else if(o===s){let c=Ye.resolve(n.baseUrl,a);return Rt(c)}let r=n.workspacePackages.get(s);if(r){let o=Ye.join(r.path,"src/index.ts");if(en.existsSync(o))return o;let a=Ye.join(r.path,r.main),c=Rt(a);if(c)return c}}return""}import wp from"fs";import xp from"path";import jo from"js-yaml";function Uo(s){let e=xp.basename(s),t=wp.readFileSync(s,"utf8"),n=[];if(e.endsWith(".prisma"))return{...kp(t,s),content:t};if(e.endsWith(".graphql")||e.endsWith(".gql"))return{...Cp(t,s),content:t};let i="Configuration";return e==="lerna.json"?{...Lp(t,s),content:t}:e==="turbo.json"?{...Mp(t,s),content:t}:e==="pnpm-workspace.yaml"?{...Ap(t,s),content:t}:(e.includes("Dockerfile")?(i="Infrastructure (Docker) ",vp(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(i="Infrastructure (YAML) ",Rp(t,n)):e.startsWith(".env")?(i="Configuration (Env) ",Tp(t,n)):e==="package.json"&&(i="Project Manifest",Ip(t,n)),{configs:n,classification:i,content:t})}function vp(s,e){let t=s.split(`
|
|
704
|
-
`);for(let
|
|
705
|
-
`);for(let
|
|
706
|
-
`)
|
|
707
|
-
`).some(r=>r&&Go(r)))return!0}let n=zt("git status --porcelain",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return n?n.split(`
|
|
708
|
-
`)
|
|
709
|
-
`)
|
|
710
|
-
`)
|
|
711
|
-
|
|
712
|
-
`).length:0,t=Ca(s?.exports),n=0,i=0,r=0,o=0;for(let a of t){let c=Ta(a?.line??a?.start_line),l=Ta(a?.endLine??a?.end_line??c);if(!c||!l||l<c||e>0&&l>e){i++;continue}n++,l>c&&o++,e>0&&c===e&&l===e&&r++}return{total:t.length,valid:n,invalid:i,eofCollapsed:r,multiLine:o,lineCount:e}}function au(s){let e=Ia(s);if(e.total===0||e.lineCount===0)return!1;if(e.invalid>0)return!0;let t=e.eofCollapsed/e.total;return e.eofCollapsed>=3&&t>=.5||e.total>=2&&e.eofCollapsed===e.total}function ka(s){let e=Ia(s);return e.valid*2+e.multiLine*2-e.eofCollapsed*3-e.invalid*4}async function ie(s,e=ou,t=!1,n=!0,i){let r=N.getInstance(s),o=r.files.database,a=ct(s),c=a.concurrency??e;if(co(),!t&&pt(s)){let y=fn(s),_=Ke(s);if(y&&!Jo(s,y))return ws(),w.debug({repoPath:s,commit:_},"Index is current, skipping re-index (fast-path)"),o}bi(s);let l=r.files.findAll(),p=new Map(l.map(y=>[y.path,{mtime:y.mtime,hash:y.content_hash}])),u=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let d=await Eo(s,a.ignore),h=new Map(d.map(y=>[y.path,y.mtime])),m=l.filter(y=>!h.has(y.path)).map(y=>y.path),f=l.length===0,S=[];if(t||f)S.push(...d);else{let y=d.filter(T=>{let k=p.get(T.path);return!k||k.mtime!==T.mtime}),_=Ws(c*4),E=y.map(T=>_(async()=>{let k=p.get(T.path);if(!k||!k.hash)return T;try{let F=await iu.promises.readFile(T.path,"utf8");return Cr(F,k.hash)?T:(r.files.updateMtime(T.path,T.mtime),null)}catch{return null}})),R=await Promise.all(E);S.push(...R.filter(T=>T!==null))}if(m.length===0&&S.length===0){ws();let y=Ke(s);return us(s,y||void 0),o}if(f?w.info({totalFiles:d.length},"Starting initial repository indexing..."):w.info({toDelete:m.length,toProcess:S.length},"Syncing repository updates..."),m.length>0&&r.files.deletePaths(m),S.length>0){po(),n?(Gn(!0),Kt().initialize().catch(()=>{})):Gn(!1);let y=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,_=[],E=[];for(let A of S)y.test(zs.basename(A.path))?_.push(A):E.push(A);let R=0,T=S.length,k=!1,F=Qo();try{await F.initialize(),k=!0,w.info({workers:F.workerCount},"Parser worker pool active")}catch(A){w.warn({err:A},"Parser worker pool failed to initialize, falling back to main-thread parsing"),k=!1}let B=async(A,H)=>{let L=H;if(k&&au(H))try{let z=await wn(A.path);ka(z)>ka(H)&&(w.warn({filePath:A.path},"Detected suspicious worker parse ranges; using main-thread parse output"),L=z)}catch(z){w.warn({filePath:A.path,err:z instanceof Error?z.message:String(z)},"Main-thread parse retry failed after suspicious worker parse")}let D=L.imports?.map(z=>({...z,resolved_path:Wt(z.module,A.path,s)})),J=L.content?Jt(L.content):null;return R++,(R%50===0||R===T)&&w.info({completed:R,total:T},"Parsing files..."),i?.({phase:"parse",current:R,total:T,message:`Parsing ${zs.basename(A.path)}`}),{meta:A,...L,imports:D,embedding:null,kind:"code",contentHash:J}},M;if(k)M=_.map(A=>F.parseFile(A.path).then(H=>B(A,H),H=>(R++,w.error({path:A.path,error:H},"Worker parse failed"),{meta:A,exports:[],imports:[],content:"",kind:"error"})));else{let A=f?Math.max(c,Math.min(ru-1,16)):c,H=Ws(A);M=_.map(L=>H(async()=>{try{let D=await wn(L.path);return B(L,D)}catch(D){return R++,w.error({path:L.path,error:D},"Failed to parse file"),{meta:L,exports:[],imports:[],content:"",kind:"error"}}}))}let v=Ws(c),I=E.map(A=>v(async()=>{try{let H=Uo(A.path),L=H.content?Jt(H.content):null;return R++,(R%50===0||R===T)&&w.info({completed:R,total:T},"Parsing configs..."),i?.({phase:"parse",current:R,total:T,message:`Parsing config ${zs.basename(A.path)}`}),{meta:A,...H,embedding:null,kind:"config",contentHash:L}}catch(H){return R++,w.error({path:A.path,error:H},"Failed to parse config"),{meta:A,exports:[],imports:[],content:"",kind:"error"}}}));w.info({total:T,codeFiles:_.length,configFiles:E.length,useParserPool:k},"Phase 1: Parsing all files...");let $=Date.now(),P=(await Promise.all([...M,...I])).filter(Boolean),U=Date.now()-$;if(_n("parse",U),w.info({count:P.length,time:`${(U/1e3).toFixed(1)}s`},"Phase 1 complete"),k&&Zo().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let A=[];P.forEach((x,O)=>{"summary"in x&&x.summary&&A.push({fileIdx:O,text:x.summary})}),w.info("Phase 2+3: Generating file-summary embeddings + persisting in parallel..."),i?.({phase:"embed",current:0,total:P.length,message:"Generating embeddings..."});let H=Date.now(),L=(async()=>{let x=[];return A.length>0&&(w.info({count:A.length}," \u2192 Generating file summary embeddings..."),x=await bs(A.map(O=>O.text),256),w.info({count:A.length}," \u2713 File summaries complete")),x})();i?.({phase:"persist",current:0,total:P.length,message:"Saving to database..."});let D=Date.now();r.files.batchSaveIndexResults(P,s,Jt,Wt);let J=Date.now()-D;_n("persist",J),w.info({time:`${(J/1e3).toFixed(1)}s`},"Structural persist complete");let z=await L,g=Date.now()-H;if(_n("embed",g),w.info({time:`${(g/1e3).toFixed(1)}s`},"File-summary embeddings complete"),z.length>0){let x=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),O=o.transaction(W=>{for(let j of W)x.run(j.embedding?JSON.stringify(j.embedding):null,j.path)}),C=A.map((W,j)=>({path:P[W.fileIdx].meta.path,embedding:z[j]}));O(C),w.info({count:C.length},"File embedding column updated")}}else{i?.({phase:"persist",current:0,total:P.length,message:"Saving to database..."});let A=Date.now();r.files.batchSaveIndexResults(P,s,Jt,Wt),_n("persist",Date.now()-A)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(f||S.length>0){let y=Ke(s);us(s,y||void 0)}if(n&&!va(s)&&Ra(s),(S.length>0||m.length>0)&&new it(s).detectAndRepairShifts(),f||n)try{new Ii(s).analyzeHeritage(50)}catch(y){w.warn({err:y.message},"Heritage sync deferred")}return lo(Date.now()-u),i?.({phase:"complete",current:S.length,total:S.length,message:"Indexing complete"}),o}Y();async function Mi(s,e=pi.DEFAULT_CONCURRENCY,t="detailed",n,i){w.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await ie(s,e);let{files:r,exports:o,imports:a}=N.getInstance(s),c=n?r.findInSubPath(s,n):r.findAll(),l=ct(s),p=cu(),u=La.join(s,".gitignore");if(Ma.existsSync(u)&&p.add(Ma.readFileSync(u,"utf8")),l.ignore&&l.ignore.length>0&&p.add(l.ignore),p.add(li),c=c.filter(_=>{let E=La.relative(s,_.path);return!p.ignores(E)}),w.info({count:c.length},"Fetching data from DB..."),t==="lite"){let _=c.map(E=>({path:E.path,mtime:E.mtime}));return ci(_,s,t,i)}if(t==="summaries"){let _=c.map(E=>({path:E.path,mtime:E.mtime,classification:E.classification||void 0,summary:E.summary||void 0}));return ci(_,s,t,i)}let d=c.map(_=>_.path),h=o.findByFiles(d),m=t==="detailed"?a.findByFiles(d):[],f=new Map;for(let _ of h){let E=f.get(_.file_path)||[];E.push(_),f.set(_.file_path,E)}let S=new Map;for(let _ of m){let E=S.get(_.file_path)||[];E.push(_),S.set(_.file_path,E)}let y=c.map(_=>{let R=(f.get(_.path)||[]).map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.start_line}));t==="structure"?R=R.map(k=>({name:k.name,kind:k.kind,line:k.line})):t==="signatures"&&(R=R.map(k=>({name:k.name,kind:k.kind,signature:k.signature,line:k.line})));let T=[];return t==="detailed"&&(T=(S.get(_.path)||[]).map(F=>({module:F.module_specifier,resolved_path:F.resolved_path}))),{path:_.path,mtime:_.mtime,classification:_.classification||void 0,summary:_.summary||void 0,exports:R,imports:T.length>0?T:void 0,chunks:[]}});return w.info({count:y.length},"Building hierarchical project tree..."),ci(y,s,t,i)}async function Aa(s,e){let t=lu.resolve(s);try{await Q(async()=>{ge("\u{1F311} Liquid Shadow: Topological Mapping");let n=parseInt(e.depth,10),i=await Mi(t,n,"detailed",e.subPath);console.log(` ${b.bold("Root")}: ${b.cyan(t)}`),e.subPath&&console.log(` ${b.bold("Subpath")}: ${b.yellow(e.subPath)}`),console.log("");let r=o=>({name:o.name,info:o.type==="directory"?`${o.children?.length||0} items`:o.size,color:o.type==="directory"?"blue":"white",children:o.children?.map(r)});Es([r(i)]),console.log(""),Ve("Mapping concluded.")})}finally{await ne(t)}}import Pa from"path";import pu from"fs";G();import me from"path";import Hs from"fs";var Ai=w.child({module:"path-resolver"}),Tn=class{repoPath;constructor(e){this.repoPath=me.isAbsolute(e)?me.normalize(e):me.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw Ai.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(me.isAbsolute(e)?t=me.normalize(e):t=me.join(this.repoPath,e),t=me.normalize(t),!this.isWithinRoot(t))throw Ai.warn({inputPath:e,resolved:t},"Path traversal attempt blocked"),new Error(`Access denied: path '${e}' is outside the repository root`);return t}resolveAndValidate(e){try{let t=this.resolve(e);return Hs.existsSync(t)?t:(Ai.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return Ai.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=me.resolve(e),n=me.resolve(this.repoPath),i=me.relative(n,t);if(i.startsWith("..")||me.isAbsolute(i))return!1;if(Hs.existsSync(t)){let o=Hs.realpathSync(t),a=me.relative(n,o);if(a.startsWith("..")||me.isAbsolute(a))return!1}return!0}catch{return!1}}getRelative(e){let t=me.normalize(e);return me.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return me.normalize(e)}static isPathWithinRoot(e,t){let n=me.resolve(e),i=me.resolve(t),r=me.relative(n,i);return r===""||!r.startsWith("..")&&!me.isAbsolute(r)}};function $a(s){return new Tn(s)}async function Na(s,e){let t=Pa.resolve(s);await Q(async()=>{if(ge("\u{1F311} Liquid Shadow: Intelligence Deployment"),console.log(` ${b.bold("Target")}: ${b.cyan(t)}`),console.log(` ${b.bold("Objective")}: ${e.output?b.magenta("Data Extraction"):b.green("Semantic Mapping")}`),console.log(""),!e.output){let i=Oe();i.start("Engaging intelligence engines...");let r="",o=a=>{if(a.phase!==r){r=a.phase;let c={scan:"\u{1F4E1} Scanning topography",parse:"\u{1F9E9} Parsing symbols",embed:"\u{1F9E0} Generating vectors",persist:"\u{1F4BE} Hardening index",complete:"\u{1F3C1} Mapping complete"}[a.phase]||a.phase;i.message(`${c}...`)}if(a.total>0&&a.current>0){let c=Math.round(a.current/a.total*100);i.message(`${r==="parse"?"Parsing":"Processing"}: ${a.current}/${a.total} (${c}%)`)}};try{await ie(t,void 0,e.force,e.deep??!0,o),i.message("\u{1FA79} Running Nano-Repair healing...");let c=new it(t).detectAndRepairShifts();i.stop("Intelligence mapping successfully concluded."),console.log(""),console.log(` ${b.bold("Next Steps:")}`),console.log(` ${b.dim("view your repo stats")} -> ${b.bold(b.cyan("liquid-shadow dashboard"))}`),console.log(` ${b.dim("start a chat search")} -> ${b.bold(b.cyan('liquid-shadow search-concept "your query"'))}`),console.log(""),Ve("Liquid Shadow is online.")}catch(a){throw i.stop(`Operation failed: ${a.message}`),a}finally{await ne(t)}return}let n=Oe();n.start("Engaging intelligence engines...");try{let i=await Mi(t,5,e.level,e.subPath),r=Pa.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!Tn.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");pu.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Data extraction saved: ${b.bold(b.cyan(r))}`),Ve("Extraction complete.")}catch(i){throw n.stop(`Extraction failed: ${i.message}`),i}finally{await ne(t)}})}import{performance as Da}from"perf_hooks";import uu from"path";Y();async function Oa(s){let e=uu.resolve(s);await Q(async()=>{console.log(`
|
|
713
|
-
|
|
714
|
-
`)
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
${
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
Benchmark failed during execution:`,n),n}finally{await ne(e)}})}import Di from"path";import Me from"path";import Us from"fs";var du=/[\x00-\x1f\x7f]/g,mu=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Bs(s){if(typeof s!="string")throw new Error("Invalid path: expected string");if(s.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(s.replace(du,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function $i(s,e=4096){if(typeof s!="string")return"";let t=s.replace(mu,"").trim();return t.length>e?t.slice(0,e):t}ut();function hu(s){let e=Me.isAbsolute(s)?Me.normalize(s):Me.resolve(process.cwd(),s),t=Me.parse(e).root;for(;e!==t;){if(Us.existsSync(Me.join(e,".liquid-shadow.db"))||Us.existsSync(Me.join(e,".git"))||Us.existsSync(Me.join(e,"package.json")))return e;let n=Me.dirname(e);if(n===e)break;e=n}return null}function st(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=Bs(e)),t&&(t=Bs(t));let n;if(e)Me.isAbsolute(e)||(e=Me.resolve(process.cwd(),e)),n=e;else if(t){let o=Me.resolve(process.cwd(),t);n=hu(Me.dirname(o))||process.cwd()}else n=process.cwd();n=Me.normalize(n);let i=$a(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}Y();G();import Gt from"fs";import Se from"path";import{Visitor as fu}from"@swc/core/Visitor.js";var Pi=class extends fu{calls=new Set;apiCalls=[];imports=new Map;axiosInstances=new Map([["axios",""],["http",""],["appApi",""],["restApi",""],["adminApi",""]]);visitImportDeclaration(e){let t=e.source.value;for(let n of e.specifiers)(n.type==="ImportDefaultSpecifier"||n.type==="ImportSpecifier")&&this.imports.set(n.local.value,t);return super.visitImportDeclaration(e)}visitCallExpression(e){if(e.callee.type==="Identifier"){let t=e.callee.value;this.calls.add(t),(t==="axios"||t==="http")&&e.arguments.length>0&&this.extractApiCallFromConfig(e.arguments[0].expression)}else if(e.callee.type==="MemberExpression"){let t=e.callee.property.value,n=r=>{if(!r)return"?";if(r.type==="Identifier")return r.value;if(r.type==="ThisExpression")return"this";if(r.type==="MemberExpression"){let o=n(r.object),a=r.property.value||"?";return`${o}.${a}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},i=n(e.callee.object);if(i!=="?"&&t){if(this.calls.add(`${i}.${t}`),i==="axios"||i==="http"||this.axiosInstances.has(i)){let r=this.axiosInstances.get(i)||"";this.extractApiCall(t,e.arguments,r)}if((i.toLowerCase().includes("pubsub")||i==="pubSubClient"||i.endsWith(".pubSubClient"))&&t!=="subscribe"){let r=t;if((t==="publish"||t==="publishMessage"||t==="publishTaskByNameAndPayload")&&e.arguments.length>0)for(let o of e.arguments){let a=o.expression;if(a.type==="ObjectExpression"){let c=a.properties.find(l=>l.key?.type==="Identifier"&&(l.key.value==="action"||l.key.value==="type")||l.key?.type==="StringLiteral"&&(l.key.value==="action"||l.key.value==="type"));if(c&&c.value?.type==="StringLiteral"){r=c.value.value;break}}if(a.type==="CallExpression"&&a.callee.type==="MemberExpression"&&a.callee.object.value==="JSON"&&a.callee.property.value==="stringify"&&a.arguments.length>0){let c=a.arguments[0].expression;if(c.type==="ObjectExpression"){let l=c.properties.find(p=>p.key?.type==="Identifier"&&(p.key.value==="action"||p.key.value==="type")||p.key?.type==="StringLiteral"&&(p.key.value==="action"||p.key.value==="type"));if(l&&l.value?.type==="StringLiteral"){r=l.value.value;break}}}}this.apiCalls.push({method:"PUBSUB",url:r})}}}return e.callee.type==="Identifier"&&e.callee.value==="fetch"&&this.extractApiCall("GET",e.arguments),super.visitCallExpression(e)}visitNewExpression(e){return e.callee.type==="Identifier"&&this.calls.add(e.callee.value),super.visitNewExpression(e)}visitVariableDeclarator(e){if(e.init&&e.init.type==="CallExpression"){let t=e.init.callee;if(t.type==="MemberExpression"&&t.property.value==="create"&&t.object.value==="axios"){let i=e.init.arguments[0]?.expression;if(i&&i.type==="ObjectExpression"){let r=i.properties.find(o=>o.key.value==="baseURL");if(r){let o="?";r.value.type==="StringLiteral"?o=r.value.value:r.value.type==="Identifier"&&(o=`\${${r.value.value}}`),e.id.type==="Identifier"&&this.axiosInstances.set(e.id.value,o)}}}}return super.visitVariableDeclarator(e)}extractApiCallFromConfig(e){if(e&&e.type==="ObjectExpression"){let t=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="url"||i.key.type==="StringLiteral"&&i.key.value==="url"),n=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="method"||i.key.type==="StringLiteral"&&i.key.value==="method");if(t&&t.value){let i=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:i.toUpperCase(),url:r})}}}resolveUrlValue(e){return e.type==="StringLiteral"?e.value:e.type==="TemplateLiteral"?e.quasis.map(t=>t.cooked).join("*"):"?"}visitTsType(e){return e}extractApiCall(e,t,n=""){if(t.length>0){let i=t[0].expression,r=this.resolveUrlValue(i);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},nn=class{calls=new Set;apiCalls=[];imports=new Map;visit(e,t){if(t===".php"){let n=/(?:([a-zA-Z0-9_$->:\(\)]*)?(?:->|::))?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&!["$this","self","parent"].includes(r)&&this.calls.add(`${r}${r.includes("::")?"::":"->"}${o}`),["save","delete","update","create","first","all","where","get","find"].includes(o)&&r&&!["Log","Route","Cache","Config","Http"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}->${o}()`}),o==="publish"&&r&&(r.includes("topic")||r.includes("pubSub"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="Http"||r==="client"||r.endsWith("request")||r.includes("Client")||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if(t===".py"){let n=/(?:([a-zA-Z0-9_\.]+)\.)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],a=i[3];if(this.calls.add(o),r&&r!=="self"&&r!=="cls"&&this.calls.add(`${r}.${o}`),["save","delete","update","create","first","all","filter","get"].includes(o)&&r&&!["logger","os","sys"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}.${o}()`}),o==="publish"&&r&&(r.includes("publisher")||r.includes("client"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="requests"||r==="httpx"||r==="client"||r==="http"||!r)){let p=a.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),u=p?p[1]:a.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:u})}}}else if([".ts",".tsx",".js",".jsx"].includes(t)){let n=/import\s+[\s\S]*?from\s+['"](.*?)['"];?/g,i;for(;(i=n.exec(e))!==null;)this.imports.set("*",i[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=o[2];a?(this.calls.add(`${a}.${c}`),(a.toLowerCase().includes("pubsub")||a==="pubSubClient")&&c!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:c})):this.calls.add(c)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,i;for(;(i=n.exec(e))!==null;)this.calls.add(i[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,i;for(;(i=n.exec(e))!==null;){let r=i[1],o=r.split("\\"),a=i[2]||o[o.length-1];this.imports.set(a,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,i;for(;(i=n.exec(e))!==null;){let a=i[1];i[2].split(",").map(l=>l.trim()).forEach(l=>{this.imports.set(l,a)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let a=o[1],c=a.split("."),l=c[c.length-1];this.imports.set(l,a)}}}};var gu=new Set(["api","v1","v2","v3","http","https","localhost","admin","internal","public","private","app","src","get","post","put","delete","patch","user","users","id","search","list","create","update","data"]),yu=new Set(["GET","POST","PUT","DELETE","PATCH"]),bu=[/\bRoute::(?:get|post|put|delete|patch)\b/i,/\brouter\.(?:get|post|put|delete|patch)\s*\(/i,/\bapp\.(?:get|post|put|delete|patch)\s*\(/i,/\bfastify\.(?:get|post|put|delete|patch)\s*\(/i,/\baddRoute\s*\(/i,/\bHTTPMethods\.(?:GET|POST|PUT|DELETE|PATCH)\b/i,/\bpath\s*\(/i,/\bre_path\s*\(/i,/@(?:GET|POST|PUT|DELETE|PATCH|Route)\b/i,/@(?:Get|Post|Put|Delete|Patch|RequestMapping)\b/];function _u(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kn(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function js(s){let e=kn(s).replace(/:[^/]+/g,"__SEG__").replace(/\{[^}]+\}/g,"__SEG__").replace(/\$[^/]+/g,"__SEG__").replace(/\*/g,"__SEG__"),t=_u(e).replace(/__SEG__/g,"[^/]+");return new RegExp(`^${t}$`)}function Fa(s){let e=[/(HTTPMethods\.)?(GET|POST|PUT|DELETE|PATCH)\b/i,/Route::(get|post|put|delete|patch)\b/i,/@(GET|POST|PUT|DELETE|PATCH)\b/i],t;for(let n of e){let i=s.match(n);if(i?.[2]){t=i[2].toUpperCase();break}if(i?.[1]){t=i[1].toUpperCase();break}}return t&&yu.has(t)?t:null}function Eu(s){return s.replace(/<[^>]+>/g," ")}function Su(s){return bu.some(e=>e.test(s))}function wu(s){let e=[],t=/['"`]([^'"`]*\/[^'"`]*)['"`]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();i&&e.push(i)}return e}function xu(s){let e=s.replace(/^\^/,"").replace(/\$$/,"");if(e.includes("://"))try{e=new URL(e).pathname}catch{}if(!e.startsWith("/")){let t=e.indexOf("/");if(t===-1)return null;e=e.slice(t)}return kn(e)}function vu(s,e){let t=wu(s);for(let n of t){let i=xu(n);if(!i)continue;let r=js(i),o=e.replace(/\*/g,"test-val");if(r.test(o)||!/[:{*$]/.test(i)&&o.startsWith(`${i}/`))return!0}return!1}function Ru(s,e){if(e)try{let i=JSON.parse(e);if(typeof i.path=="string"&&i.path.startsWith("/"))return kn(i.path)}catch{}let t=/['"]([^'"]+)['"]/g,n=null;for(;(n=t.exec(s))!==null;){let i=n[1].trim();if(i){if(i=i.replace(/^\^/,"").replace(/\$$/,""),!i.startsWith("/")){if(!i.includes("/")&&!i.includes(":"))continue;i=`/${i}`}return kn(i)}}return null}function Tu(s,e){let t=s.toLowerCase();return e.reduce((n,i)=>n+(t.includes(i.toLowerCase())?20:0),0)}function Wa(s,e,t){let n=e,i=e.match(/\$\{([^}]+)\}/g);if(i)for(let h of i){let m=h.substring(2,h.length-1),f=s.configs.findEnvValue(m);f&&(n=n.replace(h,f))}let r=n.split("?")[0].split("#")[0];try{r.includes("://")&&(r=new URL(r).pathname)}catch{}r=kn(r);let o=t?.toUpperCase(),a=[],c=!1,l=r.replace(/\*/g,"%").replace(/:[^/]+/g,"%").replace(/\{[^}]+\}/g,"%"),p=s.files.findSynapses({type:"api_route",name:l.includes("%")?l:r,direction:"consume",limit:10});for(let h of p)js(h.name).test(r.replace(/\*/g,"test-val"))&&(a.push({file_path:h.file_path,start_line:h.line_number||0,signature:`[Synapse] ${h.name}`,score:1e3}),c=!0);let u=r.split(/[^a-zA-Z0-9-_]/).filter(h=>h.length>=3&&!gu.has(h.toLowerCase())&&!/^\d+$/.test(h));if(u.length>0){let f=[...u].sort((y,_)=>_.length-y.length).slice(0,2).flatMap(y=>s.exports.findRoutesByToken(y,20)),S=new Set;for(let y of f){let _=`${y.file_path}:${y.start_line}:${y.name}`;if(S.has(_))continue;S.add(_);let E=y.signature||y.name||"",R=Fa(E);if(o&&R&&o!==R)continue;let T=Ru(E,y.capabilities);if(o&&!R&&!T)continue;let k=40;if(T){if(!js(T).test(r.replace(/\*/g,"test-val")))continue;k+=280,c=!0}o&&R&&o===R&&(k+=120,c=!0),k+=Tu(`${E} ${T||""}`,u),a.push({file_path:y.file_path,start_line:y.start_line,signature:`[Boundary] ${E}`,capabilities:y.capabilities||void 0,score:k})}}if(a.length<3&&!c){let h=u.map(m=>m.replace(/[^a-zA-Z0-9_]/g,"")).filter(m=>m.length>0).join(" AND ");if(h.length>0){let m=s.content.search(h);for(let f of m){let S=Eu(f.snippet);if(!Su(S)||!vu(S,r))continue;let y=Fa(S);if(o&&y&&y!==o)continue;let _=0,E=f.file_path.toLowerCase(),R=S.toLowerCase();(E.includes("route")||E.includes("controller"))&&(_+=10),(E.includes("src/api")||E.includes("services/api"))&&(_+=5),(R.includes("addroute")||R.includes("@get"))&&(_+=15),(R.includes("axios.")||R.includes("fetch("))&&(_-=10),(E.includes(".spec.")||E.includes(".test."))&&(_-=20),o&&R.includes(o.toLowerCase())&&(_+=20),_>0&&a.push({file_path:f.file_path,start_line:0,signature:`[FTS Match] ${S.replace(/\n/g," ")}`,score:_})}}}let d=new Map;return a.sort((h,m)=>m.score-h.score).forEach(h=>{d.has(h.file_path)||d.set(h.file_path,h)}),Array.from(d.values()).slice(0,c?2:3)}var Gs=7,jt=80,ku=2,Cu=4,Iu=6,Lu=3,Mu=24,Au=new Set(["publish","publishmessage","publishtaskbynameandpayload"]),$u=new Set(["Error","TypeError","RangeError","ReferenceError","SyntaxError","Promise","Map","Set","WeakMap","WeakSet","Date","Array","Object","String","Number","Boolean","RegExp","URL","URLSearchParams"]),Pu=new Set(["error","errors","request","response","result","results","value","values","item","data","payload","message","messages","text","description","name","id","type","status","code"]),Ha=new Set(["req","res","request","response","error","err","event","item","row","data","value","obj","window","document","console","json","math"]),Nu=new Set(["length","size","value","values","name","id","type","status"]),Ba=new Set(["push","pop","shift","unshift","slice","splice","map","filter","reduce","reduceRight","forEach","find","findIndex","includes","indexOf","lastIndexOf","every","some","flat","flatMap","fill","copyWithin","entries","keys","values","join","concat","sort","reverse","at","with","toSorted","toReversed","toSpliced","toString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","charAt","charCodeAt","codePointAt","split","substring","substr","trim","trimStart","trimEnd","padStart","padEnd","repeat","replace","replaceAll","match","matchAll","search","toLowerCase","toUpperCase","localeCompare","normalize","startsWith","endsWith","then","catch","finally","get","set","has","delete","clear","size","length","call","apply","bind"]);function Du(s,e){return Se.resolve(s)===Se.resolve(e)}function Ou(s){if($u.has(s))return!0;let e=s.trim().toLowerCase();if(!e||e.length<2||/\[|\]|\s/.test(s)||Pu.has(e))return!0;let t=s.split(/(?:\.|->|::)+/).filter(Boolean),n=(t.length>0?t[t.length-1]:e).replace(/^\$+/,"");if(Nu.has(n.toLowerCase())||Ba.has(n))return!0;if(t.length>1){let i=t[0].replace(/^\$+/,"").toLowerCase();if(Ha.has(i))return!0}return!1}function Vs(s,e){if(e.has(s))return e.get(s)??null;try{let t=Gt.readFileSync(s,"utf8");return e.set(s,t),t}catch{return null}}function Fu(s){return s<20?Gs:s<45?Gs-1:Math.max(4,Gs-2)}function Wu(s,e){let t=s<=2?1:s<=4?.7:.4,n=e<25?1:e<55?.8:.55,i=Math.floor(Mu*t*n);return Math.max(Lu,i)}function zu(s,e){let t=s.split(`
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
`);if(e.
|
|
726
|
-
`).trim())
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
${
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
`),
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
`);else if(a&&a>0){let D=Math.max(80,Math.floor(a*.12)),J=this.estimateTokenCount(I),z=[],g=[];for(let x of H){let O=this.estimateTokenCount(x.text),C=J+O<=a-D;if(z.length<2||C)z.push(x.text),J+=O;else{let W=x.gravity?" \u269B\uFE0F":"";g.push(`${x.index}. \`${x.relativePath}\`${W} (${x.matchPct}% Evidence Match)`)}}L=I+z.join(`
|
|
796
|
-
`),g.length>0&&(L+=`
|
|
797
|
-
|
|
798
|
-
### Folded Lower-Relevance Matches (${g.length})
|
|
799
|
-
_Expanded blocks omitted to stay within token budget._
|
|
800
|
-
`+g.join(`
|
|
801
|
-
`))}else L=I+H.map(D=>D.text).join(`
|
|
802
|
-
`);if(E.length>0){let D=`
|
|
803
|
-
|
|
804
|
-
---
|
|
805
|
-
## Intent Vectors (${E.length} matching decision(s))
|
|
806
|
-
|
|
807
|
-
`+E.map((z,g)=>{let x=Math.round((z.score||0)*100),O=z.symbolName?` \`${z.symbolName}\``:"",C=z.missionId?` [Mission #${z.missionId}]`:"",W=z.content.length>200?z.content.slice(0,200)+"...":z.content;return o?`${g+1}. **[${z.type}]**${O}${C} (${x}%) - ${W}`:`### ${g+1}. [${z.type}]${O}${C} (${x}% Evidence Match)
|
|
808
|
-
> ${W}
|
|
809
|
-
`}).join(`
|
|
810
|
-
`),J=`
|
|
811
|
-
|
|
812
|
-
---
|
|
813
|
-
## Intent Vectors (${E.length} matching decision(s))
|
|
814
|
-
|
|
815
|
-
`+E.slice(0,2).map((z,g)=>{let x=Math.round((z.score||0)*100),O=z.symbolName?` \`${z.symbolName}\``:"",C=z.missionId?` [Mission #${z.missionId}]`:"";return`${g+1}. **[${z.type}]**${O}${C} (${x}%)`}).join(`
|
|
816
|
-
`)+(E.length>2?`
|
|
817
|
-
> Additional intent matches folded by token budget.`:"");a&&a>0&&this.estimateTokenCount(L+D)>a?L+=J:L+=D}return{content:[{type:"text",text:L}]}}if(n===0){let R=this.filesRepo.getStats(),T=e.toLowerCase().split(/\s+/),k=this.filesRepo.findByPathKeywords(T,t);if(r&&(k=k.filter(F=>s.matchesFilters(F.path,i,F.mtime,F.classification))),k.length>0)return{content:[{type:"text",text:`# Concept Search: "${e}"
|
|
818
|
-
|
|
819
|
-
\u26A0\uFE0F No high-confidence semantic matches cleared the ${Math.round(d*100)}% evidence floor (${R.withSummary}/${R.total} summaries indexed).
|
|
820
|
-
|
|
821
|
-
Found ${k.length} file(s) with matching paths:
|
|
822
|
-
|
|
823
|
-
`+k.map((B,M)=>`${M+1}. \`${l(B.path)}\` (${B.classification||"Unknown"})`).join(`
|
|
824
|
-
`)}]};if(_.length>0){let F=_.slice(0,Math.min(3,t)).map((B,M)=>{let v=Math.round((B.score||0)*100);return`${M+1}. \`${l(B.path)}\` (${v}% evidence) - ${B.summary||"No summary"}`}).join(`
|
|
825
|
-
`);return{content:[{type:"text",text:`# Semantic Concept Search: "${e}"
|
|
826
|
-
|
|
827
|
-
No high-confidence semantic matches cleared the evidence floor (${Math.round(d*100)}% required for ${u.profile} queries).
|
|
828
|
-
|
|
829
|
-
Low-confidence candidates were suppressed instead of being presented as relevant matches:
|
|
830
|
-
${F?`
|
|
831
|
-
${F}
|
|
832
|
-
|
|
833
|
-
`:`
|
|
834
|
-
`}Try adding distinctive identifiers, narrowing the concept, or using shadow_search_symbol({ query: "${e}", repoPath }).`}]}}}return{content:[{type:"text",text:`No high-confidence files found matching concept: "${e}"
|
|
835
|
-
|
|
836
|
-
Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}async searchBySymbol(e,t,n,i,r,o="any"){let a=e.toLowerCase(),c=v=>v.replace(this.repoPath,"").replace(/^\//,""),l=this.buildFtsQuery(e,o),p;try{p=this.exportsRepo.findFts(l,t+50)}catch{p=this.exportsRepo.findByPartialName(e,t+50)}if(p.length===0){let v=this.exportsRepo.getAllNames(5e3),I=e.trim().split(/\s+/).filter(P=>P.length>0);if(I.length>1){let P=new Map;for(let A of I){let H=Ln(A,v,40,20);for(let L of H){let D=P.get(L.match);D?(D.terms.push(A),D.bestScore=Math.max(D.bestScore,L.score)):P.set(L.match,{terms:[A],bestScore:L.score})}}let U=Array.from(P.entries()).sort((A,H)=>H[1].terms.length!==A[1].terms.length?H[1].terms.length-A[1].terms.length:H[1].bestScore-A[1].bestScore).slice(0,10);if(U.length>0){let A=U.map(([H,L])=>{let D=L.terms.join(", ");return` \u2022 \`${H}\` (matches: ${D}, ${Math.round(L.bestScore)}%)`}).join(`
|
|
837
|
-
`);return{content:[{type:"text",text:`No symbols found matching all terms: "${e}"
|
|
838
|
-
|
|
839
|
-
**Partial matches:**
|
|
840
|
-
${A}
|
|
841
|
-
|
|
842
|
-
\u{1F4A1} Try searching for individual terms, or use shadow_search_concept for semantic search.`}]}}}else{let P=Ln(e,v,50,5);if(P.length>0){let U=P.map(A=>` \u2022 \`${A.match}\` (${Math.round(A.score)}% ${A.matchType} match)`).join(`
|
|
843
|
-
`);return{content:[{type:"text",text:`No symbols found matching: "${e}"
|
|
844
|
-
|
|
845
|
-
**Did you mean?**
|
|
846
|
-
${U}
|
|
847
|
-
|
|
848
|
-
\u{1F4A1} Try shadow_search_symbol with fuzzy, or shadow_search_concept for semantic search.`}]}}}return{content:[{type:"text",text:`No symbols found matching: "${e}"
|
|
849
|
-
|
|
850
|
-
\u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(p=p.filter(v=>{let I=this.filesRepo.findByPath(v.file_path);return s.matchesFilters(v.file_path,i,I?.mtime,I?.classification)}));let u=new In(this.repoPath),d=new Ae(this.repoPath),h=u.getAncestorMissionIds(),m=be(this.repoPath)||void 0,f=this.exportsRepo.getGravityMap(h,m),S=d.getSection("gravity"),y=new Map;if(S?.hotspots)for(let v of S.hotspots)y.set(`${v.filePath}::${v.symbol}`,v.gravity);let _="\u{1F525}",E="\u26A1",R="\u269B\uFE0F",T=p.map((v,I)=>{let $=f[v.id],P=y.get(`${v.file_path}::${v.name}`),U=this.filesRepo.findByPath(v.file_path),A=Xe.getMultiplier(v.file_path,U?.classification),H=(ve.SCORE_BASE-I)*A;$&&(H+=$.score*ve.SCORE_BASE),P&&(H+=P*ve.SCORE_BASE*ve.GRAVITY_STRUCTURAL_WEIGHT),v.name.toLowerCase()===a&&(H+=ve.EXACT_MATCH_BONUS*A);let L=U?.mtime;if(L!=null){let J=L>1e10?L/1e3:L,z=(Date.now()/1e3-J)/Rs.SECONDS_PER_DAY;z<ve.RECENT_FILE_THRESHOLD_DAYS?H+=ve.RECENT_FILE_BOOST:z<ve.OLDER_FILE_THRESHOLD_DAYS&&(H+=ve.OLDER_FILE_BOOST)}let D=[];return $&&D.push(...$.reasons),P&&D.push(`Structural Hotspot (Gravity: ${P.toFixed(1)})`),{...v,activeGravity:$,structuralGravity:P,sortScore:H,reasons:D}}).sort((v,I)=>I.sortScore-v.sortScore).slice(n,n+t),k=p.length,F=n+t<k,B=T.map((v,I)=>{let $=c(v.file_path),P=this.filesRepo.getContent(v.file_path),U="";if(P){let L=P.split(`
|
|
851
|
-
`);U=L.slice(Math.max(0,v.start_line-2),Math.min(L.length,v.start_line+3)).join(`
|
|
852
|
-
`).trim()}let A=[];v.activeGravity&&(v.activeGravity.reasons.some(L=>L.includes("Working Set"))?A.push(_):v.activeGravity.reasons.some(L=>L.includes("Recent Intent"))&&A.push(E)),v.structuralGravity&&A.push(R);let H=A.length>0?` ${A.join("")}`:"";return{relPath:$,name:v.name,kind:v.kind,signature:v.signature,line:v.start_line,snippet:U,badgeStr:H,gravityReasons:v.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
|
|
853
|
-
|
|
854
|
-
Showing ${B.length} matching symbol(s)${F?` (use offset=${n+t} for more)`:""}:
|
|
855
|
-
|
|
856
|
-
`+B.map((v,I)=>{let $=`## ${n+I+1}. \`${v.name}\` (${v.kind})${v.badgeStr}
|
|
857
|
-
**File**: \`${v.relPath}:${v.line}\`
|
|
858
|
-
`;return v.gravityReasons&&($+=`> *${v.gravityReasons.join(", ")}*
|
|
859
|
-
`),v.signature&&($+=`**Signature**: \`${v.signature}\`
|
|
860
|
-
`),v.snippet&&($+=`
|
|
861
|
-
\`\`\`typescript
|
|
862
|
-
${v.snippet}
|
|
863
|
-
\`\`\`
|
|
864
|
-
`),$}).join(`
|
|
865
|
-
`)}]}}async findConceptMatches(e,t,n,i,r,o=0){let a=be(this.repoPath)||void 0,l=new Wi(this.repoPath).getScorer(),u=new In(this.repoPath).getAncestorMissionIds(),d=this.filesRepo.getGravityMap(u,a),h=Ct.extractKeywords(e),m=h.length>=3,f=this.extractOrderedConceptTerms(e),S=this.buildNgrams(f,2,3),y=this.classifyConceptQuery(e,h),_=m?this.collectConceptSymbolHintPaths(h,Math.max(r*10,100)):new Set,E=Math.min(Math.max((r+o)*y.channelMultiplier,ve.FILTERED_QUERY_LIMIT_MULTIPLIER*20),Fe.MAX_LIMIT),R=Math.min(Math.max(E*4,200),4e3),[T,k,F]=await Promise.all([Promise.resolve(t?this.filesRepo.findWithEmbeddings():[]),Promise.resolve(this.filesRepo.findContentFts(e,E)),Promise.resolve(t?this.exportsRepo.findWithEmbeddings(R):[])]),B=[];if(t){for(let g of T)try{let x=JSON.parse(g.embedding),O=qn(t,x);B.push({row:g,similarity:O,vectorRank:0})}catch{}B.sort((g,x)=>x.similarity-g.similarity);for(let g=0;g<B.length;g++)B[g].vectorRank=g+1}let M=[];if(t){for(let g of F)if(g.embedding)try{let x=JSON.parse(g.embedding),O=qn(t,x);if(O<=0)continue;M.push({row:g,similarity:O,symbolVectorRank:0})}catch{}M.sort((g,x)=>x.similarity-g.similarity);for(let g=0;g<M.length;g++)M[g].symbolVectorRank=g+1}let v=new Map;for(let g of T)v.set(g.path,g);for(let g of k)v.has(g.path)||v.set(g.path,g);let I=new Map,$=[],P=new Set;for(let g of M.slice(0,R)){let x=g.row.file_path,O=I.get(x);if((!O||g.similarity>O.similarity)&&I.set(x,{similarity:g.similarity,symbolRank:g.symbolVectorRank,symbolName:g.row.name}),P.has(x))continue;let C=v.get(x);C||(C=this.filesRepo.findByPath(x),C&&v.set(x,C)),C&&($.push({path:x,rank:g.symbolVectorRank,score:g.similarity,row:C,symbolName:g.row.name}),P.add(x))}let U=this.rrfMerge(B.slice(0,E).map(g=>({path:g.row.path,rank:g.vectorRank,score:g.similarity,row:g.row})),k.slice(0,E).map((g,x)=>({path:g.path,rank:x+1,bm25Rank:g.bm25_rank,row:g})),y.rrfK,{vectorWeight:y.vectorWeight,ftsWeight:y.ftsWeight,symbolWeight:y.symbolWeight,symbolResults:$.slice(0,E)});if(U.length===0)return[];let A=new Map;for(let g of B)A.set(g.row.path,g.similarity);let H=Math.min(U.length,Math.max(r*y.lexicalWindowMultiplier,40)),L=new Set(U.slice(0,H).map(g=>g.path)),D=[],J=new Map;for(let g of U){let x=g.row,O=A.get(x.path)||0,C=I.get(x.path),W=C?.similarity||0,j=Math.max(O,W),Z=g.ftsRank!==null,he=g.symbolVectorRank!==null||!!C,Ce=g.vectorRank!==null||he,Ie=_.has(x.path),gt=L.has(x.path)||Z||Ie||he;if(!gt&&g.fusedScore<y.earlyRejectThreshold&&j<.18&&!i)continue;let fe=gt?this.filesRepo.getContent(x.path):null,$e=ve.ENABLE_LEXICAL_SCORING&&fe?Ct.calculateLexicalScore(fe,e):0,Pe=fe?Ct.calculateKeywordCoverageFromKeywords(fe,h):0,Ee=h.length>0?Math.round(Pe*h.length):0,K=this.calculatePhraseCoverage(`${x.path}
|
|
866
|
-
${x.summary||""}
|
|
867
|
-
${fe||""}`,S),ae=1;if(fe){let ce=/\b(class|function|const|let|var|enum)\s+\w+/.test(fe);if(/export\s+/.test(fe)&&!ce){let at=fe.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");/\b(class|function|const|let|var|enum)\s+\w+/.test(at)||(ae=.1)}}let ot=Ie?.08:he?.1:$e>0||K>0||Z?.14:m?.22:.18;if(Ce&&j<=ot&&!Z)continue;if(h.length>0&&$e===0&&!Z){if(m){if(!Ie&&(Ee===0&&K===0&&j<.4||Ee<=1&&K===0&&j<.34||Ee===1&&j<.3))continue}else if(Ee===0&&j<.24)continue}if(m&&!Ie&&K===0&&Ee<=1&&j<.3&&!Z||i&&!s.matchesFilters(x.path,n,x.mtime,x.classification))continue;let yt=x.mtime>2e9?Math.floor(x.mtime/1e3):x.mtime,Be=Math.floor(Date.now()/1e3)-Rs.SECONDS_PER_YEAR,Ue=Xe.getMultiplier(x.path,x.classification),$t=Ce?l.calculateScore(j,yt||Be):0,we=(g.fusedScore*60+$t*.2)*Ue,V=d[x.path],q=x.classification?Xe.mapClassificationToTier(x.classification):Xe.classify(x.path,{content:fe??void 0}),X=`vector_rank: ${this.formatRank(g.vectorRank)} | symbol_vector_rank: ${this.formatRank(g.symbolVectorRank)} | fts_rank: ${this.formatRank(g.ftsRank)} | fused_score: ${g.fusedScore.toFixed(6)} | query_profile: ${y.profile} | Similarity: ${(j*100).toFixed(0)}%, Tier: ${q}${Ue!==1?` (${Ue}x)`:""}`;if(Ie&&(X+=" | SymbolHint"),C&&(X+=` | SymbolVec: ${C.symbolName}`),$e>0&&(we+=$e*ve.LEXICAL_WEIGHT,X+=` | Lexical: +${$e.toFixed(1)}`),h.length>0)if(Pe>0){let ce=m?Pe*.45:Pe*.35;we+=ce,X+=` | Keywords: ${(Pe*100).toFixed(0)}%`}else X+=" | Keywords: 0%",m&&!Z&&(we*=.55,X+=" (penalty)");if(S.length>0)if(K>0){let ce=m?K*.8:K*.35;we+=ce,X+=` | Phrases: ${(K*100).toFixed(0)}%`}else m&&!Z&&(we*=.72,X+=" | Phrases: 0% (penalty)");V&&(we+=V.score,X+=` | \u{1F525} Gravity: +${V.score.toFixed(1)} (${V.reasons.join(", ")})`),m&&this.isGenericConceptPath(x.path)&&Ee<=1&&K===0&&!Z&&(we*=.75,X+=" | Generic path penalty"),ae<1&&(we*=ae,X+=` | \u{1F4C9} Barrel: x${ae}`);let xe=fe?Ct.extractSnippet(fe,e):void 0;D.push({path:x.path,summary:x.summary||"",score:j,fusedScore:g.fusedScore,vectorRank:g.vectorRank,ftsRank:g.ftsRank,decayedScore:we,rationale:X,snippet:xe}),J.set(x.path,{lexicalScore:$e,keywordCoverage:Pe,matchedKeywordCount:Ee,phraseCoverage:K,similarity:j,hasFtsSignal:Z,hasSymbolHint:Ie,hasSymbolVectorSignal:he,lexicalConfirm:0,identifierOverlap:0,isGenericPath:this.isGenericConceptPath(x.path)})}if(D.length>0&&h.length>0){let g=this.exportsRepo.findByFiles(D.map(O=>O.path)),x=new Map;for(let O of g){let C=x.get(O.file_path)??[];C.push(O.name),x.set(O.file_path,C)}for(let O of D){let C=this.calculateIdentifierOverlap(h,x.get(O.path)??[]),W=J.get(O.path);if(W&&(W.identifierOverlap=C),C>0){let j=m?C*.8:C*.25;O.decayedScore=(O.decayedScore||0)+j,O.rationale+=` | Symbols: ${(C*100).toFixed(0)}%`}else m&&this.isGenericConceptPath(O.path)&&(O.decayedScore=(O.decayedScore||0)*.82,O.rationale+=" | Symbols: 0% (generic penalty)")}}let z=new Map;for(let g of D){let x=g.path.split("/").pop()?.split(".")[0].replace(/(Controller|Service|Repository|Component|View|Page|Handler|Wrapper|Client|DTO|Interface)$/i,"").toLowerCase();x&&x.length>3&&(z.has(x)||z.set(x,[]),z.get(x).push(g))}for(let[g,x]of z.entries())if(new Set(x.map(C=>C.path.split(".").pop())).size>1)for(let C of x)C.decayedScore=(C.decayedScore||0)+.15,C.rationale+=` | \u{1F310} Polyglot Flow: +0.15 (Linked via '${g}')`;if(m&&D.length>1){let g=Math.min(Math.max(r*4,ve.FILTERED_QUERY_LIMIT_MULTIPLIER*20),D.length),x=[...D].sort((C,W)=>(W.decayedScore||0)-(C.decayedScore||0)).slice(0,g),O=this.computeBm25LikeConfirmation(x.map(C=>C.path),h);for(let C of x){let W=O.get(C.path)||0,j=J.get(C.path);if(j&&(j.lexicalConfirm=W),W>0){let Z=Math.min(.95,W*.18);C.decayedScore=(C.decayedScore||0)+Z,C.rationale+=` | LexConfirm: +${Z.toFixed(2)}`}else j&&j.matchedKeywordCount<=1&&j.phraseCoverage===0&&j.lexicalScore===0&&(C.decayedScore=(C.decayedScore||0)*.85,C.rationale+=" | LexConfirm: 0 (penalty)")}}for(let g of D){let x=J.get(g.path);x&&(g.score=this.calculateConceptEvidenceScore({profile:y.profile,queryKeywordCount:h.length,...x}),g.rationale+=` | Evidence: ${(g.score*100).toFixed(0)}%`)}return D.sort((g,x)=>(x.decayedScore||0)-(g.decayedScore||0)),D.slice(o,o+Math.min(r,Fe.MAX_LIMIT))}async findIntentLogMatches(e,t){return(await this.intentLogsRepo.findSemanticMatches(e,t)).map(i=>({id:i.id,missionId:i.mission_id,type:i.type,content:i.content,symbolName:i.symbol_name,filePath:i.file_path,score:i.similarity,decayedScore:i.similarity,rationale:`Similarity: ${(i.similarity*100).toFixed(0)}%`,createdAt:i.created_at}))}buildFtsQuery(e,t){let n=e.trim();if(!n.includes(" "))return`"${n}" OR ${n}*`;let i=n.split(/\s+/).filter(r=>r.length>0);switch(t){case"exact":return`"${n}"`;case"all":return i.map(r=>`${r}*`).join(" ");default:return i.map(r=>`${r}*`).join(" OR ")}}extractPathKeywords(e){let t=e.trim();if(!t)return[];let n=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_\/.-]+/).map(r=>r.trim()).filter(r=>r.length>=2),i=new Set;i.add(t.toLowerCase());for(let r of n)i.add(r);return Array.from(i)}isLikelySymbolQuery(e){let t=e.trim();return!t||/[\/\\]/.test(t)?!1:/^[a-z]+(?:[A-Z][a-z0-9]+)+$/.test(t)||!t.includes(" ")&&/[A-Z]/.test(t)}countPathKeywordHits(e,t){let n=e.toLowerCase(),i=t.filter(o=>o.length>=3),r=0;for(let o of i)n.includes(o.toLowerCase())&&(r+=1);return r}scorePathResult(e,t,n,i){let o=this.countPathKeywordHits(e,t)*10;n==="symbol"&&(o+=25);let a=e.toLowerCase(),c=a.includes("/.env")||a.endsWith(".env")||a.endsWith(".yml")||a.endsWith(".yaml")||a.endsWith(".json")||a.endsWith(".md");return i&&c&&(o-=20),i&&a.includes("/tests/")&&(o-=15),o}findSymbolBackedPaths(e,t,n){let i=e.trim().toLowerCase();if(!i)return[];if(/[\/\\]/.test(i))return[];let r=Array.from(new Set([i,...t])).filter(c=>c.length>=3).slice(0,6);if(r.length===0)return[];let o=r.flatMap(c=>{let l=c===i?Math.min(n,60):Math.min(n,30);return this.exportsRepo.findByPartialName(c,l)}),a=new Map;for(let c of o){let l=c.name.toLowerCase(),p=0;l===i&&(p+=6),l.startsWith(i)&&(p+=4),l.includes(i)&&(p+=3);for(let d of t)d.length>=3&&l.includes(d)&&(p+=1);if(p===0)continue;let u=a.get(c.file_path)||0;p>u&&a.set(c.file_path,p)}return Array.from(a.entries()).sort((c,l)=>l[1]-c[1]).slice(0,Math.min(n,Fe.MAX_LIMIT)).map(([c])=>c)}rrfMerge(e,t,n,i){let r=new Map,o=i?.vectorWeight??1.2,a=i?.ftsWeight??.8,c=i?.symbolWeight??1.1,l=i?.symbolResults??[];for(let p of e){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.vectorRank=p.rank,u.fusedScore+=o/(n+p.rank),r.set(p.path,u)}for(let p of t){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.ftsRank=p.rank,u.fusedScore+=a/(n+p.rank),r.set(p.path,u)}for(let p of l){let u=r.get(p.path)||{path:p.path,row:p.row,vectorRank:null,symbolVectorRank:null,symbolName:null,ftsRank:null,fusedScore:0};u.symbolVectorRank=p.rank,u.symbolName=p.symbolName,u.fusedScore+=c/(n+p.rank),r.set(p.path,u)}return Array.from(r.values()).sort((p,u)=>u.fusedScore-p.fusedScore)}formatRank(e){return e==null?"none":String(e)}getConceptConfidenceFloor(e){switch(e){case"identifier-heavy":return .33;case"lexical-heavy":return .38;case"semantic-exploratory":return .3;default:return .35}}getIntentConfidenceFloor(e){return Math.max(.28,this.getConceptConfidenceFloor(e)-.05)}calculateConceptEvidenceScore(e){let t=Math.min(1,e.lexicalConfirm/Math.max(1,e.queryKeywordCount*1.5)),n=e.profile==="semantic-exploratory"?.72:.58,i=e.profile==="lexical-heavy"?.16:.12,r=e.profile==="identifier-heavy"?.12:.08,o=e.similarity*n+Math.min(1,e.lexicalScore)*.08+e.keywordCoverage*.1+e.phraseCoverage*i+e.identifierOverlap*r+t*.08;return e.hasFtsSignal&&(o+=.04),e.hasSymbolHint?o+=.03:e.hasSymbolVectorSignal&&(o+=.02),e.matchedKeywordCount===0&&e.phraseCoverage===0&&e.lexicalScore===0?o*=e.hasFtsSignal||e.hasSymbolVectorSignal?.72:.6:e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.88),e.isGenericPath&&e.matchedKeywordCount<=1&&e.phraseCoverage===0&&e.identifierOverlap===0&&(o*=.85),e.queryKeywordCount===0&&(o*=.75),Math.max(0,Math.min(.97,o))}estimateTokenCount(e){return e?Math.ceil(e.length/4):0}classifyConceptQuery(e,t){let n=e.trim(),i=t.length,r=/\b[a-z]+[A-Z][A-Za-z0-9]*\b/.test(n),o=/\b[a-z0-9]+_[a-z0-9_]+\b/i.test(n),a=/[/.:#()]/.test(n),c=i<=1&&!n.includes(" "),l=n.includes('"')||i>=5&&n.split(/\s+/).length>=6;return r||o||a&&i>=2?{profile:"identifier-heavy",rrfK:45,vectorWeight:1,ftsWeight:.75,symbolWeight:1.45,channelMultiplier:5,lexicalWindowMultiplier:5,earlyRejectThreshold:.012}:l?{profile:"lexical-heavy",rrfK:55,vectorWeight:.95,ftsWeight:1.3,symbolWeight:1,channelMultiplier:7,lexicalWindowMultiplier:8,earlyRejectThreshold:.008}:c||i<=2?{profile:"semantic-exploratory",rrfK:70,vectorWeight:1.35,ftsWeight:.6,symbolWeight:.9,channelMultiplier:4,lexicalWindowMultiplier:4,earlyRejectThreshold:.018}:{profile:"balanced",rrfK:60,vectorWeight:1.15,ftsWeight:.9,symbolWeight:1.2,channelMultiplier:6,lexicalWindowMultiplier:6,earlyRejectThreshold:.01}}extractOrderedConceptTerms(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>=3):[]}buildNgrams(e,t,n){if(e.length<t)return[];let i=[];for(let r=t;r<=n&&!(e.length<r);r++)for(let o=0;o<=e.length-r;o++)i.push(e.slice(o,o+r).join(" "));return Array.from(new Set(i))}calculatePhraseCoverage(e,t){if(!e||t.length===0)return 0;let n=e.toLowerCase(),i=0;for(let r of t)n.includes(r)&&(i+=1);return i/t.length}calculateIdentifierOverlap(e,t){if(e.length===0||t.length===0)return 0;let n=new Set(e.map(o=>o.toLowerCase())),i=new Set;for(let o of t){let a=o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(c=>c.trim()).filter(c=>c.length>=3);for(let c of a)i.add(c)}let r=0;for(let o of n)i.has(o)&&(r+=1);return r/n.size}isGenericConceptPath(e){let t=e.toLowerCase();return/(?:^|\/)(index|utils?|helpers?|common|shared|types?|constants?|models?)(?:\/|\.|$)/.test(t)}computeBm25LikeConfirmation(e,t){let n=Array.from(new Set(t.map(u=>u.toLowerCase()).filter(u=>u.length>=3)));if(e.length===0||n.length===0)return new Map;let i=new Set(n),r=[],o=new Map;for(let u of e){let h=(this.filesRepo.getContent(u)??"").toLowerCase().split(/[^a-z0-9_]+/).map(f=>f.trim()).filter(Boolean),m=new Map;for(let f of h)i.has(f)&&m.set(f,(m.get(f)||0)+1);for(let f of n)(m.get(f)||0)>0&&o.set(f,(o.get(f)||0)+1);r.push({path:u,frequencies:m,length:Math.max(h.length,1)})}let a=r.reduce((u,d)=>u+d.length,0)/Math.max(r.length,1),c=1.2,l=.75,p=new Map;for(let u of r){let d=0;for(let h of n){let m=u.frequencies.get(h)||0;if(m===0)continue;let f=o.get(h)||0,S=Math.log(1+(r.length-f+.5)/(f+.5)),y=m*(c+1)/(m+c*(1-l+l*(u.length/Math.max(a,1))));d+=S*y}p.set(u.path,d)}return p}collectConceptSymbolHintPaths(e,t){let n=Array.from(new Set(e.filter(r=>r.length>=4&&!this.isLowSignalConceptKeyword(r)))).slice(0,6);if(n.length===0)return new Set;let i=new Map;for(let r of n){let o=this.exportsRepo.findByPartialName(r,Math.min(t,80));for(let a of o){let c=a.name.toLowerCase(),l=0;c===r&&(l+=3),c.startsWith(r)&&(l+=2),c.includes(r)&&(l+=1),l!==0&&i.set(a.file_path,(i.get(a.file_path)||0)+l)}}return new Set(Array.from(i.entries()).sort((r,o)=>o[1]-r[1]).slice(0,Math.min(t,Fe.MAX_LIMIT)).map(([r])=>r))}isLowSignalConceptKeyword(e){return new Set(["type","types","data","update","create","list","item","value","model","helper"]).has(e.toLowerCase())}};G();Y();function zi(s){let{fileType:e,layer:t}=s,n={fileType:Lt.normalizeFileType(e),layer:t},i=!!(n.fileType?.length||n.layer!=null);return{filters:n,hasFilters:i}}async function nc(s){let e=$i(s.query??""),t={...s,query:e},n=ri();try{let{repoPath:i}=st(t),{query:r,limit:o=Fe.DEFAULT_LIMIT,offset:a=0,compact:c=!1,tokenBudget:l}=t;await ie(i);let{filters:p,hasFilters:u}=zi(t),h=await new Lt(i).searchByConcept(r,o,a,p,u,c,l);try{let m=Li(i);if(m.status==="running"){let[f,S]=m.progress.split("/").map(Number),y=S>0?Math.round(f/S*100):0,_=`\u26A0\uFE0F Symbol embeddings still warming (${m.progress}, ${y}%) \u2014 symbol-level results may be incomplete. File-level results are fully available.
|
|
868
|
-
|
|
869
|
-
`;h.content?.[0]?.type==="text"&&(h.content[0].text=_+h.content[0].text)}}catch{}return Zu(i,r,"concept"),n(),h}catch(i){return w.error({error:i,args:s},"Concept Search failed"),n(),await Qt(),{content:[{type:"text",text:`Concept Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Zu(s,e,t){try{let n=N.getInstance(s),i=be(s);n.searchHistory.record(e,t,i)}catch(n){let i=be(s);w.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),Qt()}}G();Y();async function Zs(s){let e=$i(s.query??""),t={...s,query:e},n=ri();try{let{repoPath:i}=st(t),{query:r,limit:o=Fe.DEFAULT_LIMIT,offset:a=0,matchMode:c="any"}=t;await ie(i);let{filters:l,hasFilters:p}=zi(t),d=await new Lt(i).searchBySymbol(r,o,a,l,p,c);return Xu(i,r,"symbol"),n(),d}catch(i){return w.error({error:i,args:s},"Symbol Search failed"),n(),await Qt(),{content:[{type:"text",text:`Symbol Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Xu(s,e,t){try{let n=N.getInstance(s),i=be(s);n.searchHistory.record(e,t,i)}catch(n){let i=be(s);w.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),Qt()}}Y();G();import ln from"path";function ic(s,e){let t=s.findContentByToken(e,100);return{count:t.length,files:t}}async function sc(s){let{repoPath:e,query:t,key:n="",kind:i,limit:r=50,showUsage:o=!1}=s,a=n||t;if(!a&&!i)return{content:[{type:"text",text:'Error: Either "key" or "kind" parameter is required.'}]};await ie(e);let c=N.getInstance(e),{configs:l,files:p}=c;if(a){w.info({repoPath:e,key:a},"Searching for config key in DB...");let m=l.findByKey(a,r);if(m.length===0)return{content:[{type:"text",text:`No configuration found for key: ${a}`}]};if(o){let y=m.map(T=>{let k=ic(p,T.key),F=k.count===0?"\u26A0\uFE0F ORPHANED":`\u2713 ${k.count} usage(s)`;return{file:ln.relative(e,T.file_path),key:T.key,value:T.value,kind:T.kind,usageCount:k.count,usageFiles:k.files.slice(0,5).map(B=>ln.relative(e,B)),status:F}});y.sort((T,k)=>T.usageCount===0&&k.usageCount>0?-1:k.usageCount===0&&T.usageCount>0?1:T.usageCount-k.usageCount);let _=y.filter(T=>T.usageCount===0).length;return{content:[{type:"text",text:(_>0?`# Configuration Search: "${a}" (with Usage Analysis)
|
|
870
|
-
|
|
871
|
-
\u26A0\uFE0F **${_} orphaned var(s)** (defined but never used in code)
|
|
872
|
-
|
|
873
|
-
Found ${m.length} match(es):
|
|
874
|
-
|
|
875
|
-
`:`# Configuration Search: "${a}" (with Usage Analysis)
|
|
876
|
-
|
|
877
|
-
Found ${m.length} match(es), all in use:
|
|
878
|
-
|
|
879
|
-
`)+y.map(T=>{let k=`## ${T.file} (${T.kind}) ${T.status}
|
|
880
|
-
**${T.key}**: \`${T.value}\``;return T.usageCount>0&&T.usageFiles.length>0&&(k+=`
|
|
881
|
-
> Used in: ${T.usageFiles.map(F=>`\`${F}\``).join(", ")}${T.usageCount>5?` (+${T.usageCount-5} more)`:""}`),k}).join(`
|
|
882
|
-
|
|
883
|
-
`)}]}}let f=m.map(y=>({file:ln.relative(e,y.file_path),key:y.key,value:y.value,kind:y.kind}));return{content:[{type:"text",text:`# Configuration Search: "${a}"
|
|
884
|
-
|
|
885
|
-
Found ${m.length} match(es):
|
|
886
|
-
|
|
887
|
-
`+f.map(y=>`## ${y.file} (${y.kind})
|
|
888
|
-
**${y.key}**: \`${y.value}\``).join(`
|
|
889
|
-
|
|
890
|
-
`)+"\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars."}]}}let u=l.findByKind(i||null,r);if(o){let m=u.map(_=>{let E=ic(p,_.key);return{file:ln.relative(e,_.file_path),key:_.key,value:_.value,kind:_.kind,usageCount:E.count,usageFiles:E.files.slice(0,3).map(R=>ln.relative(e,R)),status:E.count===0?"ORPHANED":"in-use"}});m.sort((_,E)=>_.usageCount===0&&E.usageCount>0?-1:E.usageCount===0&&_.usageCount>0?1:_.usageCount-E.usageCount);let f=m.filter(_=>_.usageCount===0).length,S=m.length,y=`# Config Discovery (${i||"all"}) with Usage Analysis
|
|
891
|
-
|
|
892
|
-
`;return y+=`**Summary**: ${S} config(s) found, ${f} orphaned
|
|
893
|
-
|
|
894
|
-
`,f>0&&(y+=`## \u26A0\uFE0F Orphaned (${f})
|
|
895
|
-
`,y+=m.filter(_=>_.usageCount===0).map(_=>`- \`${_.key}\` in ${_.file}`).join(`
|
|
896
|
-
`),y+=`
|
|
897
|
-
|
|
898
|
-
`),y+=`## \u2713 In Use (${S-f})
|
|
899
|
-
`,y+=m.filter(_=>_.usageCount>0).map(_=>{let E=_.usageFiles.length>0?`, used in ${_.usageFiles.map(R=>`\`${R}\``).join(", ")}${_.usageCount>3?` (+${_.usageCount-3} more)`:""}`:"";return`- \`${_.key}\`=\`${_.value}\` in \`${_.file}\` (${_.usageCount} usages${E})`}).join(`
|
|
900
|
-
`),u.length===r&&(y+=`
|
|
901
|
-
|
|
902
|
-
> Results limited to ${r} entries. Use the 'limit' parameter to see more.`),{content:[{type:"text",text:y}]}}let d=u.map(m=>({...m,file:ln.relative(e,m.file_path)})),h=JSON.stringify(d,null,2);return u.length===r&&(h=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
|
|
903
|
-
|
|
904
|
-
`+h),h+="\n\n> \u{1F4A1} **Tip**: Use `showUsage: true` to see usage counts and identify orphaned vars.",{content:[{type:"text",text:h}]}}Y();Ut();import ed from"fs";import rc from"path";var td=new Set(["ClassDeclaration","FunctionDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","VariableDeclaration"]);function oc(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xs(s,e,t){let n=t.trim();return!!(!n||n.length>8e3||/^\w{1,4}\s+['"].*['"];?$/.test(n)&&!n.startsWith("export ")||n.includes(`
|
|
905
|
-
import `)&&!n.startsWith("import ")||e&&td.has(e)&&s&&!new RegExp(`\\b${oc(s)}\\b`).test(n))}function nd(s,e){let t=Math.max(0,(s.start_line||1)-1),n=Math.min(e.length,Math.max(t+1,(s.end_line||s.start_line||1)+1,t+120)),i=e.slice(t,n).join(`
|
|
906
|
-
`),r=We(i,s.kind);return r?r.length>800?`${r.slice(0,797)}...`:r:s.signature||""}function id(s,e,t){if(!s)return null;let n=oc(s),i=[];e==="TsTypeAliasDeclaration"&&i.push(new RegExp(`^\\s*export\\s+type\\s+${n}\\b`)),e==="TsInterfaceDeclaration"&&i.push(new RegExp(`^\\s*export\\s+interface\\s+${n}\\b`)),e==="FunctionDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:async\\s+)?function\\s+${n}\\b`)),e==="ClassDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:abstract\\s+)?class\\s+${n}\\b`)),e==="VariableDeclaration"&&i.push(new RegExp(`^\\s*(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`)),i.push(new RegExp(`\\b${n}\\b`));for(let r of i)for(let o=0;o<t.length;o++)if(r.test(t[o]))return o+1;return null}function sd(s,e,t){let n=Math.max(0,s-1);if(e==="TsTypeAliasDeclaration"||e==="VariableDeclaration"||e==="TsEnumDeclaration"){for(let i=n;i<t.length;i++){if(t[i].includes(";"))return i+1;if(/^\s*export\s+(type|interface|class|function|const|let|var)\b/.test(t[i])&&i>n)return i}return Math.min(t.length,s+20)}if(e==="TsInterfaceDeclaration"||e==="ClassDeclaration"||e==="FunctionDeclaration"){let i=0,r=!1;for(let o=n;o<t.length;o++){let a=t[o];for(let c of a)c==="{"?(i+=1,r=!0):c==="}"&&(i-=1);if(r&&i<=0)return o+1}return Math.min(t.length,s+120)}return Math.min(t.length,s+40)}function rd(s){return Array.isArray(s)?s.filter(e=>e.module!=="__type_reference__"):s}function od(s,e){return s?e==="TsTypeAliasDeclaration"?`type ${s}`:e==="TsInterfaceDeclaration"?`interface ${s}`:e==="FunctionDeclaration"?`function ${s}()`:e==="ClassDeclaration"?`class ${s}`:e==="VariableDeclaration"?`const ${s}`:`${e||"symbol"} ${s}`:e||"symbol"}function ad(s,e){if(!s||e!=="TsTypeAliasDeclaration"&&e!=="TsInterfaceDeclaration")return s;let t=s.indexOf(`
|
|
907
|
-
export `);return t<=0?s:s.slice(0,t).trim()}async function Hi(s){let{repoPath:e,filePath:t}=st(s);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=s.detailLevel||"signatures";await ie(e);let{files:i,exports:r}=N.getInstance(e),o=i.findByPath(t),a=rc.basename(t),c=/\.(ts|tsx|php|py|go)$/.test(a),l;c?l=await wn(t):l={exports:r.findByFile(t),imports:[]};let p=null;if(c)try{p=ed.readFileSync(t,"utf8").split(`
|
|
908
|
-
`)}catch{p=null}Array.isArray(l.exports)&&p&&(l.exports=l.exports.map(m=>{let f=typeof m.signature=="string"?m.signature:"",S=m.start_line??m.line??1,y=m.end_line??m.endLine??S;if(Xs(m.name||"",m.kind,f)){let E=id(m.name||"",m.kind,p),R=E??S,T=E?sd(R,m.kind,p):y,k=nd({name:m.name||"",kind:m.kind,signature:f,start_line:R,end_line:T},p),F=ad(k,m.kind),B=Xs(m.name||"",m.kind,F)?od(m.name||"",m.kind):F;return{...m,signature:B,start_line:R,end_line:T,line:R,endLine:T,members:Array.isArray(m.members)?m.members.filter(M=>{let v=typeof M.signature=="string"?M.signature:"";return!Xs(M.name||"",M.kind,v)}):m.members}}return m})),l.imports=rd(l.imports),n==="structure"?(l.exports=l.exports.map(m=>{let f={name:m.name,kind:m.kind,line:m.start_line,classification:m.classification};return m.members&&m.members.length>0?{...f,members:m.members.map(S=>({name:`${m.name}.${S.name}`,kind:S.kind,line:S.start_line}))}:f}),delete l.imports):n==="signatures"&&(l.exports=l.exports.map(m=>{let f={name:m.name,kind:m.kind,signature:m.signature,line:m.start_line,classification:m.classification,capabilities:JSON.parse(m.capabilities||"[]")};return m.members&&m.members.length>0?{...f,members:m.members.map(S=>({name:`${m.name}.${S.name}`,kind:S.kind,signature:S.signature,line:S.start_line}))}:f}),delete l.imports);let u=rc.relative(e,t),d=l.exports?.length||0,h="";return n==="structure"&&d>0?h=`
|
|
909
|
-
|
|
910
|
-
\u{1F4A1} Showing ${d} symbol names. For full signatures: shadow_inspect_file({ filePath: "${u}", detailLevel: "signatures" })`:n==="signatures"&&d>0&&(h=`
|
|
911
|
-
|
|
912
|
-
\u{1F4A1} Showing ${d} complete signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...l,fileDescription:o?.summary||"",classification:o?.classification&&o.classification!=="Unknown"?o.classification:Bt(t,N.getInstance(e)).layer},null,2)+h}]}}Y();import ac from"path";import cd from"fs";function ld(s,e,t){let n=s.split(`
|
|
913
|
-
`),i=[],r=0;for(let u=0;u<Math.min(n.length,50);u++){let d=n[u].trim();if(d.startsWith("import ")||d.startsWith("from ")||d.startsWith("export ")&&d.includes(" from "))r=u+1;else if(d&&!d.startsWith("//")&&!d.startsWith("/*")&&!d.startsWith("*")&&d!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((u,d)=>u.startLine-d.startLine),a=0,c=0;for(let u of o)if(u.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${u.name} \u2501\u2501\u2501`);let d=n.slice(u.startLine-1,u.endLine);i.push(...d),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),c++}else{let d=u.signature||pd(n,u.startLine-1,u.kind);d&&(i.push(`${d}`),i.push(` /* implementation: ${u.lineCount} lines */`),i.push(""),a++)}let l=o[o.length-1];if(l)for(let u=l.endLine;u<n.length;u++){let d=n[u].trim();if(d==="}"||d==="};"){i.push(n[u]);break}else if(d&&!d.startsWith("//"))break}return{foldedSource:i.join(`
|
|
914
|
-
`),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:c,siblingsFolded:a}}function pd(s,e,t){let n=s[e];if(t.includes("Function")||t.includes("Method")||t.includes("Arrow")){let i="";for(let r=e;r<Math.min(e+5,s.length);r++)if(i+=s[r],i.includes("{")||i.includes("=>")){let o=i.indexOf("{");o>0&&(i=i.substring(0,o).trim());break}return i.trim()}return n}function ud(s,e=","){let t=[],n="",i=0,r=0,o=0,a=0,c=null,l=!1;for(let u of s){if(c){if(n+=u,l){l=!1;continue}if(u==="\\"){l=!0;continue}u===c&&(c=null);continue}if(u==='"'||u==="'"||u==="`"){c=u,n+=u;continue}if(u==="("?i++:u===")"?i=Math.max(0,i-1):u==="{"?r++:u==="}"?r=Math.max(0,r-1):u==="["?o++:u==="]"?o=Math.max(0,o-1):u==="<"?a++:u===">"&&(a=Math.max(0,a-1)),u===e&&i===0&&r===0&&o===0&&a===0){let d=n.trim();d&&t.push(d),n="";continue}n+=u}let p=n.trim();return p&&t.push(p),t}function dd(s){let e=s.indexOf("(");if(e<0)return null;let t=0;for(let n=e;n<s.length;n++){let i=s[n];if(i==="("&&t++,i===")"&&(t--,t===0))return{start:e,end:n}}return null}function Bi(s,e){let t=0,n=0,i=0,r=0,o=null,a=!1;for(let c=0;c<s.length;c++){let l=s[c];if(o){a?a=!1:l==="\\"?a=!0:l===o&&(o=null);continue}if(l==='"'||l==="'"||l==="`"){o=l;continue}if(l==="("?t++:l===")"?t=Math.max(0,t-1):l==="{"?n++:l==="}"?n=Math.max(0,n-1):l==="["?i++:l==="]"?i=Math.max(0,i-1):l==="<"?r++:l===">"&&(r=Math.max(0,r-1)),l===e&&t===0&&n===0&&i===0&&r===0)return c}return-1}function md(s){let t=s.trim(),n=!1;t.startsWith("...")&&(n=!0,t=t.slice(3).trim());let i=Bi(t,"="),r=i>=0,o=r?t.slice(0,i).trim():t,a=r?t.slice(i+1).trim():void 0,c=Bi(o,":"),l=(c>=0?o.slice(0,c):o).replace(/^(?:readonly\s+)?(?:public|private|protected)\s+/,"").trim(),p=l.includes("?"),u=l.replace(/\?/g,"").trim(),d=c>=0&&o.slice(c+1).trim()||null;return{name:u||"(anonymous)",type:d,optional:p,rest:n,hasDefault:r,...a?{defaultValue:a}:{}}}function hd(s,e){let t=s.slice(e+1).trim();if(!t)return null;let n=t.indexOf("=>");if(n>=0){let r=t.slice(0,n).trim(),o=Bi(r,":");if(o>=0){let c=r.slice(o+1).trim();if(c)return c}return t.slice(n+2).replace(/\{.*$/,"").trim()||null}let i=Bi(t,":");return i>=0&&t.slice(i+1).replace(/\{.*$/,"").trim()||null}function fd(s){let e=s.trim();if(!e)return[];if(e==="*")return["*"];if(e.startsWith("[")&&e.endsWith("]"))try{let n=JSON.parse(e);if(Array.isArray(n))return n.map(i=>String(i).trim()).filter(Boolean).map(i=>i.replace(/^['"`]|['"`]$/g,""))}catch{}return e.replace(/^\{|\}$/g,"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>n.replace(/^type\s+/,"")).map(n=>n.split(/\s+as\s+/i)[0]?.trim()||n).map(n=>n.replace(/^['"`]|['"`]$/g,""))}function gd(s,e,t){let n=s?.replace(/\s+/g," ").trim()||null,r=n?.match(/\b(public|private|protected)\b/)?.[1]||null,a=(n?.match(/\bfunction\s*\*?\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)/)||n?.match(/^(?:export\s+)?(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\(/))?.[1]||e,c=n?dd(n):null,l=n&&c?n.slice(c.start+1,c.end):"",p=l?ud(l).map(md):[],u=n&&c?hd(n,c.end):null,d=n?.match(/(?:function\s+[A-Za-z_$][A-Za-z0-9_$]*|[A-Za-z_$][A-Za-z0-9_$]*)\s*(<[^>]+>)\s*\(/);return{raw:s,normalized:n,symbol:a,kind:t,visibility:r,isStatic:/\bstatic\b/.test(n||""),isAsync:/\basync\b/.test(n||""),isGenerator:/function\s*\*/.test(n||"")||/\*\s*[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(n||""),isArrowFunction:/=>/.test(n||""),typeParameters:d?.[1]||null,parameters:p,parameterCount:p.length,returnType:u}}function yd(s,e,t=5){let n=new Map;for(let o of s){let a=n.get(o.file_path)||{classification:o.classification||null,importedSymbols:new Set,wildcard:!1},c=fd(o.imported_symbols);(c.length===0||c.includes("*"))&&(a.wildcard=!0);for(let l of c)a.importedSymbols.add(l);!a.classification&&o.classification&&(a.classification=o.classification),n.set(o.file_path,a)}let i=Array.from(n.entries()).map(([o,a])=>({file:ac.relative(e,o),classification:a.classification,importedSymbols:a.importedSymbols.size>0?Array.from(a.importedSymbols).sort():["*"],wildcard:a.wildcard})),r=i.slice(0,Math.max(1,t));return{totalVerifiedCallers:i.length,showing:r.length,wildcardCallers:i.filter(o=>o.wildcard).length,topCallers:r.map(({wildcard:o,...a})=>a)}}async function pn(s){let{repoPath:e,filePath:t,resolver:n}=st(s),i=String(s.symbolName),r=s.context||"definition";if(t&&!n.isWithinRoot(t))return{content:[{type:"text",text:`Error: Access denied. Path ${t} is outside the repository root.`}],isError:!0};await ie(e);let o=N.getInstance(e),a=[];if(i.includes(".")){let[v,I]=i.split(".");a=o.exports.findMemberCandidates(v,I,t)}else a=o.exports.findDefinitionCandidates(i,t);if(a.length===0){let v=o.exports.findPotentialParents(i);if(v.length>0){let U=v.map(A=>`\`${A.name}\` (in ${n.getRelative(A.file_path)})`).join(", ");return{content:[{type:"text",text:`Symbol "${i}" not found as a top-level export.
|
|
915
|
-
However, it likely exists inside: ${U}.
|
|
916
|
-
Try: shadow_inspect_symbol({ symbolName: "${v[0].name}", context: "full" }) to see the class body.`}]}}let $=o.exports.findFuzzyCandidates(i).map(U=>U.name),P=Ln(i,$,50,3);if(P.length>0){let U=P.map(A=>` \u2022 \`${A.match}\` (${A.score}% match)`).join(`
|
|
917
|
-
`);return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
|
|
918
|
-
|
|
919
|
-
Suggestions:
|
|
920
|
-
${U}
|
|
921
|
-
|
|
922
|
-
Next steps:
|
|
923
|
-
\u2022 Search semantically: shadow_search_concept({ query: "${i}" })
|
|
924
|
-
\u2022 Verify repository is indexed: shadow_sync_index({ repoPath: "${e}" })`}]}}return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
|
|
925
|
-
|
|
926
|
-
Next steps:
|
|
927
|
-
\u2022 Search for it: shadow_search_concept({ query: "${i}" })
|
|
928
|
-
\u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${i}", filePath: "..." })
|
|
929
|
-
`}]}}let c=a[0];if(c.kind==="ExportSpecifier"||c.kind==="ExportAllDeclaration"){let v=o.imports.findImportSource(c.file_path,i);if(v&&v.resolved_path)return pn({...s,filePath:v.resolved_path})}let l=cd.readFileSync(c.file_path,"utf8"),p=l.split(`
|
|
930
|
-
`),u=c.end_line-c.start_line+1,d=150,h,m=!1,f=null;if(r==="definition"&&u>d){let I=o.exports.findSiblings(c.file_path).map($=>({name:$.name,kind:$.kind,signature:$.signature||"",startLine:$.start_line,endLine:$.end_line,lineCount:$.end_line-$.start_line+1,isTarget:$.name===c.name&&$.start_line===c.start_line,parentName:$.parent_name}));if(I.length>1){f=ld(l,{name:c.name,startLine:c.start_line,endLine:c.end_line},I);let $=n.getRelative(c.file_path);h=f.foldedSource+`
|
|
931
|
-
|
|
932
|
-
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
933
|
-
\u{1F4CA} Semantic Fold Applied (context: "definition")
|
|
934
|
-
|
|
935
|
-
Original file: ${f.totalOriginalLines} lines
|
|
936
|
-
Folded view: ${f.foldedToLines} lines
|
|
937
|
-
Target Symbol: ${c.name}
|
|
938
|
-
\u{1F4A1} Need more context?
|
|
939
|
-
\u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${c.name}", context: "full" })
|
|
940
|
-
\u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${$}", detailLevel: "signatures" })
|
|
941
|
-
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,m=!0}else h=p.slice(c.start_line-1,c.start_line-1+d).join(`
|
|
942
|
-
`)+`
|
|
943
|
-
|
|
944
|
-
... (truncated ${u-d} lines)`,m=!0}else h=p.slice(c.start_line-1,c.end_line).join(`
|
|
945
|
-
`);let S=c.parent_name?`${c.parent_name}.${c.name}`:c.name,y=o.exports.findHydratedById(c.id),_=c.parent_name||c.name,E=o.imports.findProxies(c.file_path).map(v=>v.file_path),R=Array.from(new Set([c.file_path,...E])),T=o.imports.findVerifiedDependents(R,_),k=yd(T,e),F=gd(c.signature,S,c.kind),B={name:S,kind:c.kind,signature:F,file:n.getRelative(c.file_path),startLine:c.start_line,endLine:c.end_line,totalLines:u,...m&&{truncated:!0,previewLines:d},classification:c.classification,callerSummary:k,source:h};if(y&&y.recent_intents&&y.recent_intents.length>0){let v={},I=Date.now();for(let $ of y.recent_intents){if($.is_crystallized&&$.type!=="crystal")continue;let P=$.created_at;P<1e10&&(P*=1e3);let U=new Date(P).getTime(),A=I-U,H="just now";if(A>0){let L=Math.floor(A/1e3),D=Math.floor(L/60),J=Math.floor(D/60),z=Math.floor(J/24);z>0?H=`${z}d ago`:J>0?H=`${J}h ago`:D>0?H=`${D}m ago`:H=`${L}s ago`}v[$.type]||(v[$.type]=[]),v[$.type].push(`[${H}] ${$.content}`)}B.intelligence={working_set_of:y.active_missions.map($=>`Mission #${$.id}: ${$.name}`),total_intents:y.intent_log_count,recent_activity:v}}else y&&(B.intelligence={working_set_of:y.active_missions.map(v=>`Mission #${v.id}: ${v.name}`),total_intents:y.intent_log_count,recent_activity:null});try{let{generateEmbedding:v}=await Promise.resolve().then(()=>(qe(),Et)),I=`Symbol: ${B.name}
|
|
946
|
-
Signature: ${c.signature||""}
|
|
947
|
-
File: ${B.file}`,$=await v(I);if($){let P=o.intentLogs.findSemanticMatches($,3,c.id),U=new Promise(H=>setTimeout(()=>H([]),100)),A=await Promise.race([P,U]);A&&A.length>0&&(B.intelligence||(B.intelligence={}),B.intelligence.related_knowledge=A.map(H=>({type:H.type,content:H.content,from_symbol:H.symbol_name,similarity:`${(H.similarity*100).toFixed(0)}%`})))}}catch{}if(r==="definition")return{content:[{type:"text",text:JSON.stringify(B,null,2)}]};let M={definition:B,dependencies:o.imports.getImportsForFile(c.file_path).map(v=>({module:v.module_specifier,symbols:v.imported_symbols,relativePath:v.resolved_path?ac.relative(e,v.resolved_path):null})),callerSummary:k};return M.verifiedUsages=k.topCallers,{content:[{type:"text",text:JSON.stringify(M,null,2)}]}}async function cc(s,e){let t=Mn.resolve(e.dir);await Q(async()=>{ge("Semantic Concept Search");let n=Oe();n.start(`Analyzing intent: "${b.bold(s)}"...`);try{let i=await nc({repoPath:t,query:s});n.stop("Analysis complete.");let r=i.content[0].text;if(r.includes("Found")){let a=r.split("## ").slice(1).map(c=>{let[l,...p]=c.split(`
|
|
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)&>.statSync(r).isFile())return r}if(gt.existsSync(s)&>.statSync(s).isFile())return s}if(gt.existsSync(s)&>.statSync(s).isFile())return s;for(let t of Ef){let n=s+t;if(gt.existsSync(n)&>.statSync(n).isFile())return n}if(gt.existsSync(s)&>.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
|
+
);
|
|
948
797
|
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
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(`
|
|
963
895
|
CREATE TABLE IF NOT EXISTS fused_repos (
|
|
964
896
|
alias TEXT PRIMARY KEY,
|
|
965
897
|
repo_path TEXT NOT NULL UNIQUE,
|
|
@@ -993,64 +925,102 @@ File: ${B.file}`,$=await v(I);if($){let P=o.intentLogs.findSemanticMatches($,3,c
|
|
|
993
925
|
|
|
994
926
|
CREATE INDEX IF NOT EXISTS idx_virtual_edges_source ON virtual_edges(source_repo, source_file_path);
|
|
995
927
|
CREATE INDEX IF NOT EXISTS idx_virtual_edges_target ON virtual_edges(target_repo, target_file_path);
|
|
996
|
-
`),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(
|
|
997
|
-
VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
WHERE type = 'api_route' AND direction = 'produce'
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
`);
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
`)}
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
`).run(e.sourceRepo,e.sourceFilePath,e.sourceSymbolId||null,e.targetRepo,e.targetFilePath,e.targetSymbolId||null,e.relationship,e.metadata?JSON.stringify(e.metadata):null,e.confidence??1).lastInsertRowid}scanEdges(){return Cd.info({name:this.connection.nameValue},"Starting edge scan"),_c(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var Ec=w.child({module:"fused-index"}),sr=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Gi(e),this.service=new qi(this.connection)}attachRepo(e){this.connection.attachRepo(e)}detachRepo(e){this.connection.detachRepo(e)}refreshRepo(e){this.connection.refreshRepo(e)}getAttachedRepos(){return this.connection.getAttachedRepos()}checkHealth(){return this.connection.checkHealth()}close(){this.connection.close(),Ec.info({name:this.configName},"Fused index closed")}getStatus(){let e=this.service.executeRawQuery("SELECT COUNT(*) as count FROM virtual_edges");return{name:this.connection.nameValue,path:this.connection.dbPath,attachedRepos:this.connection.getAttachedRepos().length,repos:this.connection.getAttachedRepos(),virtualEdgesCount:e[0]?.count||0}}searchExports(e,t=50){return this.service.searchExports(e,t)}searchFiles(e,t=50){return this.service.searchFiles(e,t)}getVirtualEdges(e,t){return this.service.getVirtualEdges(e,t)}addVirtualEdge(e){return this.service.addVirtualEdge(e)}scanEdges(){return this.service.scanEdges()}buildUnionQuery(e,t,n){return this.service.buildUnionQuery(e,t,n)}executeFederatedQuery(e,...t){return this.service.executeFederatedQuery(e,...t)}executeRawQuery(e,...t){return this.service.executeRawQuery(e,...t)}buildAdvancedQuery(e){return this.service.buildAdvancedQuery(e)}buildFtsQuery(e,t,n,i,r){return this.service.buildFtsQuery(e,t,n,i,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return Ec.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},ir=new Map;function Sc(s){let e=ir.get(s.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),i=new Set(s.repoPaths.map(o=>Id.resolve(o)));if(n.size===i.size&&[...n].every(o=>i.has(o)))return e;e.close(),ir.delete(s.name)}let t=new sr(s);return ir.set(s.name,t),t}G();var Ld=w.child({module:"mcp:tools:workspace:fuse"});async function wc(s){let{repoPaths:e,name:t}=s;Ld.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=Sc({repoPaths:e,name:t||`workspace-${Date.now()}`});return{content:[{type:"text",text:JSON.stringify({message:"Fused index created",status:n.getStatus()},null,2)}]}}catch(n){throw new Error(`Failed to fuse: ${n.message}`)}}import Vi from"path";async function xc(s){let[e,...t]=s;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${b.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${b.bold("Commands: ")}`),console.log(` ${b.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${b.cyan("link")} <args...> Link missions across repositories`),console.log(` ${b.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${b.bold("Examples: ")}`),console.log(" liquid-shadow workspace missions /frontend /backend"),console.log(" liquid-shadow workspace link /frontend 5 /backend 12"),console.log(" liquid-shadow workspace fuse /frontend /backend --name my-app"),console.log("");return}await Q(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${b.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>Vi.resolve(r)),i=await hc({repoPaths:n});if(console.log(""),console.log(` ${b.bold("Workspace Missions")}`),console.log(""),i.content&&i.content[0]){let r=JSON.parse(i.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${b.cyan("\u2022")} ${b.bold(o.name)} (ID: ${o.id})`),console.log(` ${b.dim("Repo: ")} ${o.repo_path}`),console.log(` ${b.dim("Status: ")} ${o.status}`),console.log(` ${b.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${b.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${b.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${b.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,i,r,o,a]=t;await fc({parentRepoPath:Vi.resolve(n),parentMissionId:parseInt(i,10),childRepoPath:Vi.resolve(r),childMissionId:parseInt(o,10),relationship:a}),console.log(""),console.log(` ${b.green("\u2714")} ${b.bold("Missions linked successfully")}`),console.log(` ${b.dim("Parent: ")} ${n} (Mission ${i})`),console.log(` ${b.dim("Child: ")} ${r} (Mission ${o})`),a&&console.log(` ${b.dim("Relationship: ")} ${a}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${b.red("\u2716")} Please provide at least one repository path`);return}let n,i=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):i.push(Vi.resolve(t[o]));let r=await wc({repoPaths:i,name:n});if(console.log(""),console.log(` ${b.green("\u2714")} ${b.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${b.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${b.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${b.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${b.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}G();G();var Ji=w.child({module:"strategy-normalizer"}),ze=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(i){return Ji.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:this.normalizeSteps(t)}}static normalizeSteps(e){return Array.isArray(e)?e.map((t,n)=>{if(typeof t=="string")return{id:`step-${n}`,description:t,status:"pending"};if(typeof t=="object"&&t!==null){let{verification:i,...r}=t,o=this.sanitizeVerification(i);return{...r,id:t.id||`step-${n}`,description:t.description||t.content||t.name||`Step ${n+1}`,status:t.status||"pending",dependencies:t.dependencies||t.deps,...o!==void 0?{verification:o}:{}}}return{id:`step-${n}`,description:String(t),status:"pending"}}):e.steps&&Array.isArray(e.steps)?this.normalizeSteps(e.steps):typeof e=="object"?Object.entries(e).map(([t,n],i)=>{if(typeof n=="string")return{id:t,description:n,status:"pending"};if(typeof n=="object"&&n!==null){let{verification:r,...o}=n,a=this.sanitizeVerification(r);return{...o,id:t,description:n.description||n.content||n.name||t,status:n.status||"pending",dependencies:n.dependencies||n.deps,...a!==void 0?{verification:a}:{}}}return{id:t||`step-${i}`,description:String(n),status:"pending"}}):[]}static looksLikeNaturalLanguage(e){return e.trim().split(/\s+/).length>=5}static VALID_VERIFICATION_TYPES=new Set(["usage","import","pattern"]);static sanitizeVerificationRule(e){if(!e)return null;if(typeof e=="string")return this.looksLikeNaturalLanguage(e)?(Ji.warn({verification:e},"Stripping natural-language verification rule (not a valid pattern)"),null):{type:"pattern",target:e};if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.target!="string"||!t.target)return Ji.warn({verification:e},"Stripping verification rule without target"),null;if(this.looksLikeNaturalLanguage(t.target))return Ji.warn({verification:e},"Stripping natural-language verification target (not a valid pattern)"),null;let i={type:typeof t.type=="string"&&this.VALID_VERIFICATION_TYPES.has(t.type)?t.type:"pattern",target:t.target};return typeof t.context=="string"&&(i.context=t.context),typeof t.filePath=="string"&&(i.filePath=t.filePath),i}static sanitizeVerification(e){if(e!=null){if(Array.isArray(e)){let t=e.map(n=>this.sanitizeVerificationRule(n)).filter(Boolean);return t.length>0?t.length===1?t[0]:t:void 0}return this.sanitizeVerificationRule(e)??void 0}}static stringify(e){return JSON.stringify(e,null,2)}static validate(e){let t=[];if(!e)return{valid:!0,errors:[]};try{let n=this.normalize(e),i=new Set;for(let r of n.steps)if(i.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),i.add(r.id),r.dependencies)for(let o of r.dependencies)i.has(o)||t.push(`Step "${r.id}" depends on non-existent step "${o}"`);return{valid:t.length===0,errors:t}}catch(n){return t.push(`Strategy validation failed: ${n instanceof Error?n.message:String(n)}`),{valid:!1,errors:t}}}};G();import rr from"fs";import vc from"path";import Md from"os";var Ad=[{id:"step-0",description:"Analyze impact: identify dependents and call sites",status:"pending"},{id:"step-1",description:"Implement refactor and update call sites",status:"pending"},{id:"step-2",description:"Run tests and verify behavior; update docs if needed",status:"pending"}],$d=[{id:"step-0",description:"Capture requirements and acceptance criteria",status:"pending"},{id:"step-1",description:"Implement feature with tests",status:"pending"},{id:"step-2",description:"Integrate and verify end-to-end",status:"pending"}],Pd=[{id:"step-0",description:"Reproduce the bug and document steps",status:"pending"},{id:"step-1",description:"Diagnose root cause and plan fix",status:"pending"},{id:"step-2",description:"Apply fix and add/update regression test",status:"pending"},{id:"step-3",description:"Verify fix and run full test suite",status:"pending"}],Rc=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:Ad},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:$d},{id:"bug-fix",name:"Bug fix",description:"Reproduction \u2192 diagnosis \u2192 fix \u2192 regression test",defaultGoal:"Fix {{target}}: reproduce, diagnose, fix, and add regression test.",steps:Pd}],or=new Map(Rc.map(s=>[s.id,s])),Yi=!1;function Nd(){if(Yi)return;let s=vc.join(Md.homedir(),".shadow","templates");if(!rr.existsSync(s)){w.debug({templatesDir:s},"Custom templates directory does not exist"),Yi=!0;return}try{let e=rr.readdirSync(s).filter(t=>t.endsWith(".json"));for(let t of e)try{let n=vc.join(s,t),i=rr.readFileSync(n,"utf8"),r=JSON.parse(i);if(!r.id||!r.name||!r.defaultGoal||!r.steps){w.warn({file:t,template:r},"Invalid custom template structure - skipping");continue}if(!Array.isArray(r.steps)||r.steps.length===0){w.warn({file:t},"Template has no steps - skipping");continue}if(Rc.some(o=>o.id===r.id)){w.warn({file:t,templateId:r.id},"Custom template ID conflicts with built-in - skipping");continue}or.set(r.id,r),w.info({file:t,templateId:r.id},"Loaded custom template")}catch(n){w.warn({file:t,error:n},"Failed to load custom template")}Yi=!0}catch(e){w.warn({error:e,templatesDir:s},"Failed to read custom templates directory"),Yi=!0}}function Dd(s){return Nd(),or.get(s)}function Od(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function Tc(s,e,t={}){let n=Dd(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(or.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=Od(n.defaultGoal,{...t,target:i}),a=ze.normalize({steps:n.steps}),c=ze.stringify(a);return{name:r,goal:o,strategy:c}}Y();Cn();import kc from"node:path";var An=w.child({module:"mcp:tools:ops:plan"}),Fd=["name","goal","strategy","parentId","outcomeContract"],Wd="Mission update requires at least one updatable field: name, goal, strategy, parentId, outcomeContract.",zd="Mission requires name and goal (or templateId with optional templateVars).";async function Cc(s){let{repoPath:e,name:t,goal:n,strategy:i,workingSet:r,missionId:o,parentId:a,outcomeContract:c,templateId:l,templateVars:p}=s,{missions:u}=N.getInstance(e),d=be(e),h=Ke(e);An.info({repoPath:e,name:t,missionId:o,templateId:l},"Planning mission");try{let m=t,f=n,S=i;if(!o&&l){let E=Tc(l,t,p||{});m=m??E.name,f=f??E.goal,S=S??E.strategy}let y,_;if(o){let E=u.findById(o);if(!E)throw new Error(`Mission ${o} not found.`);let R;if(i!==void 0)if(i){let k=ze.normalize(i);R=ze.stringify(k);let F=ze.validate(R);F.valid||An.warn({errors:F.errors,strategy:i},"Strategy validation warnings detected")}else R=null;let T={commit_sha:h};if(t!==void 0&&(T.name=t),n!==void 0&&(T.goal=n),R!==void 0&&(T.strategy_graph=R),a!==void 0&&(T.parent_id=a),c!==void 0&&(T.outcome_contract=c),Object.keys(T).length===1)throw new Error(Wd);u.update(o,{...T}),y=o,_=`Mission "${t??E.name}" updated.`}else{if(!m||!f)throw new Error(zd);let E=null;if(S){let R=ze.normalize(S);E=ze.stringify(R);let T=ze.validate(E);T.valid||An.warn({errors:T.errors,strategy:S},"Strategy validation warnings detected")}if(y=u.create({name:m,goal:f,strategy_graph:E,status:"planned",git_branch:d,commit_sha:h,parent_id:a||null,verification_context:null,outcome_contract:c||null}),r&&r.length>0){u.clearWorkingSet(Number(y));for(let R of r){let T=kc.isAbsolute(R)?R:kc.join(e,R);u.addToWorkingSet(Number(y),T,"planned")}}_=`Mission "${m}" planned.`}try{await new Ze(e).syncMissionToGitNotes(Number(y))}catch(E){An.info({missionId:y,...Re(E)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:y,status:"planned",message:_,strategy_saved:!!S,working_set_populated:r?.length||0,working_set_seeded:r?.length||0,contract_saved:!!c,updateable_fields:Fd,from_template:l??void 0,commit:h},null,2)}]}}catch(m){let f=qt(m);throw An.error({repoPath:e,...Re(m)},"Failed to plan mission"),new Error(`Failed to plan mission: ${f}`)}}G();Y();var Ki=class s{constructor(e){this.intentLogs=e}static RECENCY_HALF_LIFE_HOURS=48;static WEIGHTS={recency:.4,activity:.3,statusBoost:.2,blockerBoost:.1};score(e){if(e.length===0)return[];let t=Math.floor(Date.now()/1e3),n=e.map(c=>c.id),i=this.intentLogs.countByMissions(n),r=this.intentLogs.findMissionsWithBlockers(n),o=Math.max(1,...Object.values(i));return e.map(c=>{let l=this.computeRecency(c.updated_at,t),p=(i[c.id]||0)/o,u=this.computeStatusBoost(c.status),d=r.has(c.id)?1:0,h=s.WEIGHTS,m=l*h.recency+p*h.activity+u*h.statusBoost+d*h.blockerBoost;return{mission:c,score:Math.round(m*1e3)/1e3,breakdown:{recency:Math.round(l*1e3)/1e3,activity:Math.round(p*1e3)/1e3,blockerBoost:d,statusBoost:u}}}).sort((c,l)=>l.score-c.score)}computeRecency(e,t){let n=Math.max(0,(t-e)/3600);return Math.pow(.5,n/s.RECENCY_HALF_LIFE_HOURS)}computeStatusBoost(e){switch(e){case"in-progress":return 1;case"verifying":return .8;case"planned":return .4;default:return 0}}};Y();G();var Hd=w.child({module:"collision-service"}),Qi=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=be(this.repoPath);if(!e)return[];let{missions:t}=N.getInstance(this.repoPath),n=t.findActive(e)??[],i=new Set(n.map(l=>l.id)),r=(t.findActive()??[]).filter(l=>!i.has(l.id)),o=[],a=new Set;for(let l of r){let p=l.git_branch||"unknown",u=[e,p].sort().join("::");Hd.info({branch:p,currentBranch:e,missionId:l.id},"Checking predictive collisions"),p!==e&&!a.has(u)&&(a.add(u),Vo(this.repoPath,e,p)&&o.push({branch:p,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${p}'.`}))}let c=this.analyzeMissionOverlaps([...i]);for(let l of c)o.push({branch:e,mission_id:l.missionB.id,mission_name:l.missionB.name,type:"intent",description:`Logical conflict: Mission '${l.missionA.name}' overlaps with '${l.missionB.name}'.`,conflictingFiles:l.sharedFiles});return o}analyzeMissionOverlaps(e){let t=be(this.repoPath);if(!t)return[];let{missions:n}=N.getInstance(this.repoPath),i=n.findActive(t)??[],r=e&&e.length>0?i.filter(a=>e.includes(a.id)):i,o=[];for(let a=0;a<r.length;a+=1){let c=r[a],l=new Set(n.getWorkingSet(c.id).map(p=>p.file_path));for(let p=a+1;p<r.length;p+=1){let u=r[p],d=n.getWorkingSet(u.id).map(m=>m.file_path),h=Array.from(new Set(d.filter(m=>l.has(m)))).sort();h.length!==0&&o.push({missionA:{id:c.id,name:c.name},missionB:{id:u.id,name:u.name},sharedFiles:h})}}return o}};Y();var ar=new Set(["planned","in-progress","verifying","suspended"]),$n=class{constructor(e){this.repoPath=e}buildPlanForParent(e){let{missions:t,claims:n}=N.getInstance(this.repoPath);if(!t.findById(e))throw new Error(`Mission ${e} not found`);let o=t.findByParentId(e).filter(d=>ar.has(d.status)).map(d=>{let h=t.getWorkingSet(d.id).map(m=>m.file_path);return{id:d.id,name:d.name,status:d.status,files:h}}),a=this.computeOverlapMatrix(o),c=this.colorIntoWaves(o,a),l=new Set(o.map(d=>d.id)),p=Array.from(new Set(o.flatMap(d=>d.files))),u=n.getClaimsByFiles(p).filter(d=>!l.has(d.mission_id)).map(d=>({file_path:d.file_path,mission_id:d.mission_id,mission_name:d.mission_name,mission_status:d.mission_status,mission_branch:d.mission_branch}));return this.composePlan(o,a,u,e)}buildPlanForMissions(e,t={}){let{includeClaimCheck:n=!0}=t,{missions:i,claims:r}=N.getInstance(this.repoPath),a=i.findByIds(e).filter(p=>ar.has(p.status)).map(p=>({id:p.id,name:p.name,status:p.status,files:i.getWorkingSet(p.id).map(u=>u.file_path)})),c=this.computeOverlapMatrix(a),l=n?this.computeExternalClaims(a,r.getClaimsByFiles(Array.from(new Set(a.flatMap(p=>p.files))))):[];return this.composePlan(a,c,l)}toHandlerPayload(e){let t=new Map(e.child_missions.map(p=>[p.id,p])),n=e.waves.map(p=>({waveIndex:p.wave,missions:p.missions.map(u=>{let d=t.get(u);return{id:u,name:d?.name??`Mission ${u}`,workingSetSize:d?.file_count??0}})})),i=e.overlap_matrix.map(p=>({missionA:p.mission_a,missionB:p.mission_b,sharedFiles:p.shared_files})),r=e.external_claims.map(p=>({filePath:p.file_path,claimedByMissionId:p.mission_id,claimedByMissionName:p.mission_name,claimedByMissionStatus:p.mission_status,claimedByMissionBranch:p.mission_branch})),o=e.child_missions.length,a=n.length,c=n[0]?.missions.length??0,l=`${o} missions in ${a} waves, ${c} parallelizable in wave 1`;return{waves:n,overlapMatrix:i,externalClaims:r,summary:l}}groupMissionsForParallelism(e){let{missions:t}=N.getInstance(this.repoPath),i=t.findByIds(e).filter(o=>ar.has(o.status)).map(o=>({id:o.id,name:o.name,status:o.status,files:t.getWorkingSet(o.id).map(a=>a.file_path)})),r=this.computeOverlapMatrix(i);return this.colorIntoWaves(i,r)}composePlan(e,t,n,i){let r=this.colorIntoWaves(e,t);return{...i!==void 0?{parent_mission_id:i}:{},mission_ids:e.map(o=>o.id),child_missions:e.map(o=>({id:o.id,name:o.name,status:o.status,file_count:o.files.length})),waves:r,overlap_matrix:t,external_claims:n}}computeExternalClaims(e,t){let n=new Set(e.map(i=>i.id));return t.filter(i=>!n.has(i.mission_id)).map(i=>({file_path:i.file_path,mission_id:i.mission_id,mission_name:i.mission_name,mission_status:i.mission_status,mission_branch:i.mission_branch}))}computeOverlapMatrix(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n],r=new Set(i.files);for(let o=n+1;o<e.length;o+=1){let a=e[o],c=a.files.filter(l=>r.has(l));c.length!==0&&t.push({mission_a:i.id,mission_b:a.id,shared_files:Array.from(new Set(c)).sort()})}}return t}colorIntoWaves(e,t){if(e.length===0)return[];let n=new Map;for(let a of e)n.set(a.id,new Set);for(let a of t)n.get(a.mission_a)?.add(a.mission_b),n.get(a.mission_b)?.add(a.mission_a);let i=[...e].sort((a,c)=>{let l=(n.get(c.id)?.size??0)-(n.get(a.id)?.size??0);return l!==0?l:a.id-c.id}),r=new Map;for(let a of i){let c=new Set;for(let p of n.get(a.id)??[]){let u=r.get(p);u!==void 0&&c.add(u)}let l=1;for(;c.has(l);)l+=1;r.set(a.id,l)}let o=new Map;for(let[a,c]of r.entries()){let l=o.get(c)??[];l.push(a),o.set(c,l)}return[...o.entries()].sort((a,c)=>a[0]-c[0]).map(([a,c])=>({wave:a,missions:c.sort((l,p)=>l-p)}))}};var Zi=class{constructor(e){this.repoPath=e}async getBriefing(e={}){let{missionId:t,scope:n="mission",altitude:i,activeMissionsLimit:r,recentActivityLimit:o,compact:a}=e,c=a??(i==="orbit"||i==="atmosphere"),l=o??(i==="orbit"?0:i==="ground"?20:10),{missions:p,intentLogs:u}=N.getInstance(this.repoPath),d=Ke(this.repoPath),h=be(this.repoPath);return n==="project"?this.getProjectBriefing({altitude:i,activeMissionsLimit:r,recentActivityLimit:l,compact:c,currentBranch:h,currentCommit:d}):this.getMissionBriefing({missionId:t,altitude:i,recentActivityLimit:l,currentBranch:h,currentCommit:d})}async getProjectBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i,claims:r}=N.getInstance(t),{altitude:o,activeMissionsLimit:a,recentActivityLimit:c,compact:l,currentBranch:p,currentCommit:u}=e,d=n.findActive(p||void 0),h=d.length;a&&d.length>a&&(d=d.slice(0,a));let m=n.findParentOnlyIds(d),f=new Set(m),S=d.filter(g=>!f.has(g.id)),_=new Ki(i).score(S),E=.15,R=3,T=l&&_.length>R?_.filter((g,x)=>x<R||g.score>=E):_,k=T.map(g=>g.mission),F=new Map(T.map(g=>[g.mission.id,g.score])),B=new Set(d.map(g=>g.id)),M=r.listClaims().filter(g=>B.has(g.mission_id)).map(g=>({file_path:g.file_path,mission_id:g.mission_id,mission_name:g.mission_name,mission_status:g.mission_status,mission_branch:g.mission_branch,claimed_at:g.claimed_at,updated_at:g.updated_at})),v=new $n(t).groupMissionsForParallelism(d.map(g=>g.id)),I=v.length,$=new Map;for(let g of M)$.set(g.mission_id,($.get(g.mission_id)??0)+1);let P=g=>({id:g.id,name:g.name,goal:g.goal,status:g.status,relevance:F.get(g.id),claimedFileCount:$.get(g.id)??0}),U=g=>({...g,claimedFileCount:$.get(g.id)??0});if(o==="orbit")return{scope:"project",altitude:"orbit",counts:n.getStats(),next_work_candidates:k.map(P),parallel_wave_count:I,claims_count:M.length,meta:{current_branch:p,activeMissionsTotal:h,ember:this.getEmberLabel(t)}};let A={},H=[];for(let g of d)g.parent_id!=null?(A[g.parent_id]||(A[g.parent_id]=[]),A[g.parent_id].push(g)):H.push(g);let L=n.findRecentCompleted(5).map(P),D=c>0?i.findRecentDecisionActivity(c):void 0,J=m.map(g=>{let x=d.find(C=>C.id===g);return{parent:l?{...U(x),strategy_graph:void 0,verification_context:void 0}:U(x),children:(A[g]??[]).map(U)}}),z=H.filter(g=>!f.has(g.id)).map(U);return{scope:"project",altitude:o||"atmosphere",counts:n.getStats(),analytics:n.getAnalytics(),hierarchy:J.length>0?J:void 0,standalone_active:z.length>0?z:void 0,active_missions:J.length===0?l?d.map(g=>({...U(g),strategy_graph:void 0})):d.map(U):void 0,claims:M,parallel_groups:v,next_work_candidates:k.map(P),recent_completed:L,recent_activity:D,meta:{current_branch:p,current_commit:u,activeMissionsTotal:h,active_limit_applied:!!a,relevance_filtered:T.length<_.length?{shown:T.length,total:_.length}:void 0,ember:this.getEmberLabel(t)}}}getEmberLabel(e){try{let{status:t,progress:n}=Li(e);if(t==="idle")return;if(t==="done")return"symbols: fully embedded";let[i,r]=n.split("/").map(Number),o=r>0?Math.round(i/r*100):0;return t==="running"?`symbols: warming ${n} (${o}%)`:`symbols: ${t} ${n}`}catch{return}}async getMissionBriefing(e){let{repoPath:t}=this,{missions:n,intentLogs:i,claims:r}=N.getInstance(t),{missionId:o,altitude:a,recentActivityLimit:c,currentBranch:l,currentCommit:p}=e,u;if(o?u=n.findById(o):u=n.findActive(l||void 0)[0],!u)return null;let d=null;try{u.strategy_graph&&(d=JSON.parse(u.strategy_graph))}catch{}if(a==="orbit")return{altitude:"orbit",mission:{id:u.id,name:u.name,goal:u.goal,status:u.status,last_updated:new Date(u.updated_at*1e3).toISOString()},strategy_snapshot:d};let h="No external shadow changes detected.";try{new on(t).analyzeGhostChanges(u.commit_sha||void 0),h="Shadow Trace completed: Checked for external modifications."}catch{}let m={repaired:0,failed:0};try{m=new it(t).detectAndRepairShifts()}catch{}let f=n.getHandoffs(u.id).map(y=>{let _=null;try{_=JSON.parse(y.metadata??"")}catch{}return{artifactId:y.id,kind:y.identifier,confidence:_?.confidence??null,findingsCount:_?.findings?.length??0,risksCount:_?.risks?.length??0,missionsCreated:_?.missionsCreated??[],createdAt:y.created_at}}),S={altitude:a||"atmosphere",mission:{id:u.id,name:u.name,goal:u.goal,status:u.status,last_updated:new Date(u.updated_at*1e3).toISOString(),git_branch:u.git_branch,commit_sha:u.commit_sha,outcome_contract:u.outcome_contract},artifacts:n.getArtifacts(u.id),handoffs:f,shadow_trace:{ghost_analysis:h,symbols_repaired:m.repaired,symbols_missing:m.failed},context:{current_commit:p,working_set:n.getWorkingSet(u.id).map(y=>y.file_path)},claims:r.getClaimsForMission(u.id),parallel_groups:new $n(t).groupMissionsForParallelism(n.findActive(l||void 0).map(y=>y.id)),strategy_snapshot:d,recent_activity:a==="ground"?i.findByMission(u.id,c||20):i.findByMissionPreferCrystal(u.id,15),ancestor_activity_summary:[],predictive_collisions:[]};try{let y=new Qi(t);S.predictive_collisions=await y.analyzePotentialCollisions()}catch{}if(u.parent_id){let y=a==="ground"?i.findByMission(u.parent_id,5):i.findByMissionPreferCrystal(u.parent_id,3);S.ancestor_activity_summary=y.map(_=>({type:_.type,content:_.content,date:new Date(_.created_at*1e3).toISOString()}))}return S}};var Ic=w.child({module:"mcp:tools:ops:briefing"});async function Lc(s){let{repoPath:e,scope:t="mission"}=s;Ic.info({repoPath:e,missionId:s.missionId,scope:t},"Generating briefing");try{let i=await new Zi(e).getBriefing(s);if(!i&&t==="mission")return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let r;if(t==="project"){let o=i.counts;r=i.next_work_candidates.length===0&&o.active===0?{tool:"shadow_ops_plan",reason:"No open work; create a mission"}:{tool:"shadow_ops_track",reason:"Select a mission from hierarchy or next_work_candidates to execute"}}return{content:[{type:"text",text:JSON.stringify(i,null,2)}],suggestedNext:r}}catch(n){throw Ic.error({error:n,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${n instanceof Error?n.message:String(n)}`)}}G();Y();Y();G();G();var Bd=w.child({module:"reasoning-engine"}),Xi=class{analyze(e){Bd.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[],sourceMissions:[]};for(let i of e){let r=i.content.toLowerCase(),o=this.matchesContext(r,i.type),a=this.matchesDecision(r,i.type),c=this.matchesConsequence(r,i.type),l=this.matchesRecommendation(r,i.type);o?t.context.push(i.content):a?t.decisions.push(i.content):l?t.recommendations.push(i.content):c?t.consequences.push(i.content):i.type==="decision"?t.decisions.push(i.content):i.type==="discovery"||i.type==="fix"?t.consequences.push(i.content):t.unclassified.push(i.content)}let n=new Set;for(let i of e)i.mission_id!=null&&n.add(i.mission_id);return t.sourceMissions=[...n],t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(i=>e.includes(i))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(i=>e.includes(i))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(i=>e.includes(i))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(i=>e.includes(i))}};var es=w.child({module:"briefing-engine"}),mt=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=N.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Xi,this.persistencePivot=new Ze(e)}async distillMission(e,t=!0){es.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.gatherConsolidatedLogs(e);if(n.length===0)return{missionId:e,adr:"No intent logs found for this mission.",metrics:{totalLogs:0,symbolCount:0}};let i=this.reasoningEngine.analyze(n),r=new Set(n.map(a=>a.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
|
|
1031
|
-
|
|
1032
|
-
`;
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
`,
|
|
1037
|
-
`
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
`)
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
`),i.
|
|
1045
|
-
`,i.recommendations.forEach(a=>{o+=`- ${a}
|
|
1046
|
-
`}),
|
|
1047
|
-
`),i.
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
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&<(y,{code:"db_missing_registry",scope:"registry",severity:"warning",message:"Fused DB exists but registry entry is missing."}),f&&!h&<(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
|
+
`)&<(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&<(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&<(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&<(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&<(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&<(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}
|
|
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+=`
|
|
1051
1009
|
---
|
|
1052
|
-
*Generated by Liquid Shadow Reasoning Engine v1*`,t){this.intentLogs.create({mission_id:e,type:"adr",content:o,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:null});try{await this.persistencePivot.syncMissionToGitNotes(e),es.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(a){es.error({missionId:e,error:a},"Failed to sync ADR to Git Notes")}}else es.info({missionId:e},"Tactical Briefing synthesized (dry-run).");return{missionId:e,adr:o,metrics:{totalLogs:n.length,symbolCount:r.size}}}gatherConsolidatedLogs(e,t=0){let n=this.intentLogs.findByMissionPreferCrystal(e,500);if(t>2)return n;let i=this.missions.findByParentId(e);for(let r of i)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};G();import{Visitor as Ud}from"@swc/core/Visitor.js";import*as Mc from"@swc/core";var jd=w.child({module:"verification-engine"}),cr=class extends Ud{foundUsage=!1;foundImport=!1;rule;currentFunctionName=null;constructor(e){super(),this.rule=e}visitImportDeclaration(e){return this.rule.type==="import"&&e.source.value===this.rule.target&&(this.foundImport=!0),super.visitImportDeclaration(e)}visitFunctionDeclaration(e){let t=this.currentFunctionName;this.currentFunctionName=e.identifier.value;let n=super.visitFunctionDeclaration(e);return this.currentFunctionName=t,n}visitCallExpression(e){return this.rule.type==="usage"&&e.callee.type==="Identifier"&&e.callee.value===this.rule.target&&(!this.rule.context||this.currentFunctionName===this.rule.context)&&(this.foundUsage=!0),super.visitCallExpression(e)}},ts=class{async verify(e,t){try{let n=await Mc.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new cr(t);i.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=i.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=i.foundUsage,!r){let a=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${a} not found.`)}}else t.type==="pattern"&&(r=new RegExp(t.target).test(e),r||o.push(`Required pattern "${t.target}" not found.`));return{passed:r,errors:o}}catch(n){return jd.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};Cn();import Ac from"path";import ns from"fs";var Te=w.child({module:"mcp:tools:ops:track"});function lr(s,e){return Ac.isAbsolute(e)?e:Ac.join(s,e)}async function $c(s,e,t){let{missions:n,intentLogs:i}=N.getInstance(s),r=n.findById(e);if(!r?.parent_id)return;let o=n.findByParentId(r.parent_id);if(!o.every(p=>p.status==="completed"))return;let c=n.findById(r.parent_id);if(!c||c.status==="completed")return;Te.info({parentId:c.id,childCount:o.length},"All children completed \u2014 cascading parent completion"),n.updateStatus(c.id,"completed",t||void 0),n.clearWorkingSet(c.id);let{claims:l}=N.getInstance(s);l.releaseAllForMission(c.id),i.create({mission_id:c.id,type:"system",content:`Parent auto-completed: all ${o.length} child missions finished`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:t});try{await new mt(s).distillMission(c.id),Te.info({parentId:c.id},"Parent Auto-Synthesis completed")}catch(p){Te.info({parentId:c.id,...Re(p)},"Parent Auto-Synthesis deferred")}try{await new Ze(s).syncMissionToGitNotes(c.id)}catch(p){Te.info({parentId:c.id,...Re(p)},"Parent Git Notes sync deferred")}await $c(s,c.id,t)}async function Pc(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:a}=s,{missions:c,intentLogs:l}=N.getInstance(e),p=Ke(e);Te.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:a?.length},"Updating mission status");try{if(a&&Array.isArray(a))for(let h of a)c.addArtifact(t,h.type,h.identifier,h.metadata);let u=[];if(o&&Array.isArray(o)&&u.push(...o),n&&i&&u.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(c.updateStatus(t,i,p||void 0),i==="completed"){c.clearWorkingSet(t);let{claims:h}=N.getInstance(e),m=h.releaseAllForMission(t);m>0&&Te.info({missionId:t,released:m},"Auto-released file claims on completion")}if(l.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),i==="completed"){try{await new mt(e).distillMission(t),Te.info({missionId:t},"Auto-Synthesis completed successfully")}catch(h){Te.info({missionId:t,...Re(h)},"Auto-Synthesis deferred or failed")}await $c(e,t,p)}if(!u.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:i,message:"Mission status updated successfully.",artifacts_added:a?.length||0,commit:p},null,2)}]}}if(u.length===0&&(!a||a.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let d=[];for(let h of u){let{stepId:m,status:f,contextPivot:S}=h,y=c.findById(t);if(!y)throw new Error(`Mission ID ${t} not found`);let _=JSON.parse(y.strategy_graph||"{}"),E=null;if(Array.isArray(_)?E=_.find(R=>R.id===m):_.nodes&&Array.isArray(_.nodes)?E=_.nodes.find(R=>R.id===m):_.steps?Array.isArray(_.steps)?E=_.steps.find(R=>R.id===m):E=_.steps[m]:_[m]&&(E=_[m]),!E)throw new Error(`Step ID "${m}" not found`);if(f==="completed"&&E.verification){let R=new ts,T=Array.isArray(E.verification)?E.verification:[E.verification];for(let k of T){let F=k;if(typeof k=="string"){if(k.trim().split(/\s+/).length>=5){Te.warn({rule:k},"Skipping natural-language verification rule");continue}F={type:"pattern",target:k}}if(!F||!F.target){Te.warn({rule:k},"Skipping invalid verification rule (missing target)");continue}if(typeof F.target=="string"&&F.target.trim().split(/\s+/).length>=5){Te.warn({rule:F},"Skipping natural-language verification target");continue}let B=F.filePath;if(B&&(B=lr(e,B)),B){if(!ns.existsSync(B))throw new Error(`Verification failed: File not found at ${B}`);let M=await R.verify(ns.readFileSync(B,"utf8"),F);if(!M.passed)throw new Error(`Verification failed: ${M.errors.join("")}`)}else{let M=c.getWorkingSet(t),v=!1;M.length===0&&Te.warn("No working set files to verify against for rule");for(let I of M){let $=lr(e,I.file_path);if(!ns.existsSync($))continue;if((await R.verify(ns.readFileSync($,"utf8"),F)).passed){v=!0;break}}if(!v)throw new Error(`Verification failed: Rule "${F.target}" not satisfied in any working set file.`)}}}if(E.status=f,c.update(t,{strategy_graph:JSON.stringify(_),commit_sha:p}),l.create({mission_id:t,type:"system",content:`Step "${m}" updated to "${f}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),S){let R=S.trim();if(R.startsWith("{")||R.startsWith("["))try{let T=JSON.parse(R);if(T.files&&Array.isArray(T.files)){c.clearWorkingSet(t);for(let k of T.files)c.addToWorkingSet(t,lr(e,k))}}catch(T){Te.warn({error:T},"Failed to apply context pivot")}}d.push({stepId:m,status:f})}try{await new Ze(e).syncMissionToGitNotes(t)}catch(h){Te.info({missionId:t,...Re(h)},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,updates:d,artifacts_added:a?.length||0,message:"Status updated",commit:p},null,2)}]}}catch(u){let d=qt(u);throw Te.error({repoPath:e,...Re(u)},"Failed to update status"),new Error(`Failed to update status: ${d}`)}}G();var Fc=w.child({module:"mcp:tools:ops:graph"});async function Wc(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;Fc.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(Oc(),Dc));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw Fc.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}Y();G();import zc from"node:path";var dn=w.child({module:"mcp:tools:ops:log"}),Gd=["in-progress","verifying"];function qd(s){for(let e of Gd){let t=s.find(n=>n.status===e);if(t)return t.id}return s[0]?.id??null}function Vd(s,e){return e?zc.isAbsolute(e)?e:zc.join(s,e):null}async function Hc(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o,standalone:a}=s;dn.info({repoPath:e,type:n,symbolName:o,standalone:a},"Logging intent");let{missions:c,exports:l,intentLogs:p}=N.getInstance(e),u=Vd(e,r);try{let d=t??null,h=be(e)||void 0;if(a)d=null,dn.debug("Standalone intent requested; mission auto-resolution skipped");else if(d){if(!c.findById(d))throw new Error(`Mission ${d} not found. Use shadow_ops_briefing to see available missions.`)}else{let E=c.findActive(h);E.length>0?(d=qd(E),dn.debug({missionId:d,currentBranch:h},"Auto-resolved to active mission on current branch")):(d=null,dn.debug({currentBranch:h},"No active mission found on current branch; logging as system/unlinked intent"))}let m=null,f=null,S=o||null,y=u;if(o){let R=(u?l.findByNameAndFile(o,u):l.findByName(o))[0];R?(m=R.id,f=R.signature,S=R.name,y=R.file_path||y):dn.warn({symbolName:o,filePath:u??r},"Symbol not found for intent linking")}let _=p.create({mission_id:d,symbol_id:m,file_path:y,type:n,content:i,confidence:1,symbol_name:S,signature:f,commit_sha:null});return d&&y&&c.addToWorkingSet(d,y,m?"symbol":"intent"),{content:[{type:"text",text:JSON.stringify({logId:_,missionId:d,symbolId:m,status:"logged",message:m?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(d){throw dn.error({error:d,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${d instanceof Error?d.message:String(d)}`)}}Y();G();var Bc=w.child({module:"mcp:tools:ops:synthesize"});async function Uc(s){let{repoPath:e,missionId:t}=s;Bc.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=N.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new mt(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics},null,2)}]}}catch(i){throw Bc.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}import Jd from"path";var oe={...b,box:ue,table:ni,list:oo};async function jc(s){let[e,...t]=s;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${oe.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${oe.bold("Actions: ")}`),console.log(` ${oe.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${oe.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${oe.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${oe.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${oe.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${oe.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await Q(async()=>{let n=t[0]?Jd.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${oe.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let a=await Cc({repoPath:n,name:r,goal:o}),c=JSON.parse(a.content[0].text);console.log(` ${oe.green("\u2714")} Mission planned (ID: ${c.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${oe.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await Pc({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${oe.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...a]=t;if(!r||!o||a.length===0){console.error(` ${oe.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await Hc({repoPath:n,missionId:parseInt(r),type:o,content:a.join(" ")}),console.log(` ${oe.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${oe.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await Uc({repoPath:n,missionId:parseInt(r)});console.log(""),oe.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await Wc({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i=await Lc({repoPath:n});if(i.content&&i.content[0]){let r=i.content[0].text;try{let o=JSON.parse(r);if(o.mission){console.log(""),console.log(oe.bold(oe.cyan(` Mission Dashboard: ${o.mission.name} `))),oe.box("Tactical Goal",o.mission.goal,"cyan");let a=o.mission.status==="completed"?"green":o.mission.status==="failed"?"red":"yellow",c=[["Status",oe.bold(oe[a](o.mission.status.toUpperCase()))],["ID",`#${o.mission.id}`],["Branch",o.mission.git_branch||"main"]];oe.table(["Field","Value"],c),o.recent_activity&&o.recent_activity.length>0&&(console.log(` ${oe.bold("Recent Activity:")}`),oe.list(o.recent_activity.slice(0,5).map(l=>`${oe.dim(`[${l.type.toUpperCase()}]`)} ${l.content}`)))}else console.log(r)}catch{console.log(r)}}break}}})}import ur from"path";async function Gc(s){let[e,...t]=s;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${b.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${b.bold("Actions: ")}`),console.log(` ${b.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${b.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await Q(async()=>{let n=t[0]?ur.resolve(t[0]):process.cwd();if(e==="symbol"){let i=t[1];if(!i){console.error(` ${b.red("\u2716")} Please provide a symbol name`);return}let r=await pn({repoPath:n,symbolName:i});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let i=t[1];if(!i){console.error(` ${b.red("\u2716")} Please provide a file path`);return}let r=ur.isAbsolute(i)?i:ur.join(n,i),o=await Hi({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var qc=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],Yd=["--help","-h","--version","-v","--dir","-d"],Kd={index:["--output","-o","--level","-l","--subPath","--force","--deep"],tree:["--subPath","--depth","-d"],trace:["--dir","-d"],"search-config":["--dir","-d","--kind"],"search-concept":["--dir","-d","--interactive","-i"],"search-symbol":["--dir","-d","--interactive","-i"],"search-fuzzy":["--dir","-d","--interactive","-i"]};function Qd(){let s=Object.entries(Kd).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
|
|
1053
|
-
`),e
|
|
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)
|
|
1054
1024
|
_liquid_shadow() {
|
|
1055
1025
|
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
1056
1026
|
local words=("\${COMP_WORDS[@]}")
|
|
@@ -1060,7 +1030,7 @@ _liquid_shadow() {
|
|
|
1060
1030
|
if [[ "\${words[$i]}" != -* ]]; then cmd="\${words[$i]}"; break; fi
|
|
1061
1031
|
((i++))
|
|
1062
1032
|
done
|
|
1063
|
-
local opts="${
|
|
1033
|
+
local opts="${Hg.join(" ")}"
|
|
1064
1034
|
if [ -n "$cmd" ]; then
|
|
1065
1035
|
case "$cmd" in
|
|
1066
1036
|
${s}
|
|
@@ -1072,11 +1042,11 @@ ${s}
|
|
|
1072
1042
|
COMPREPLY=($(compgen -W "$opts" -- "$cur"))
|
|
1073
1043
|
}
|
|
1074
1044
|
complete -F _liquid_shadow liquid-shadow
|
|
1075
|
-
`}function
|
|
1045
|
+
`}function Gg(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
|
|
1076
1046
|
# Run after compinit (e.g. in .zshrc after compinit)
|
|
1077
1047
|
|
|
1078
1048
|
_liquid_shadow() {
|
|
1079
|
-
local -a cmds; cmds=(${
|
|
1049
|
+
local -a cmds; cmds=(${Dp.map(e=>`'${e}'`).join(" ")})
|
|
1080
1050
|
if [ $CURRENT -eq 2 ]; then
|
|
1081
1051
|
_describe 'command' cmds
|
|
1082
1052
|
return
|
|
@@ -1093,339 +1063,374 @@ _liquid_shadow() {
|
|
|
1093
1063
|
_describe 'flag' fl
|
|
1094
1064
|
}
|
|
1095
1065
|
compdef _liquid_shadow liquid-shadow
|
|
1096
|
-
`}async function
|
|
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
|
|
1097
1069
|
|
|
1098
|
-
|
|
1070
|
+
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
1099
1071
|
|
|
1100
|
-
|
|
1101
|
-
|
|
1072
|
+
# Run liquid-shadow sync in background to avoid blocking git operations
|
|
1073
|
+
nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
1102
1074
|
|
|
1103
|
-
|
|
1104
|
-
`,
|
|
1075
|
+
exit 0
|
|
1076
|
+
`,"post-checkout":`#!/bin/sh
|
|
1077
|
+
# Liquid Shadow: Auto-refresh index after branch checkout
|
|
1078
|
+
# Generated by liquid-shadow
|
|
1105
1079
|
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
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"
|
|
1111
1090
|
|
|
1112
|
-
|
|
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 &
|
|
1113
1095
|
|
|
1114
|
-
|
|
1096
|
+
exit 0
|
|
1097
|
+
`,"post-commit":`#!/bin/sh
|
|
1098
|
+
# Liquid Shadow: Trigger symbol shift detection after commit
|
|
1099
|
+
# Generated by liquid-shadow
|
|
1115
1100
|
|
|
1116
|
-
|
|
1101
|
+
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
1117
1102
|
|
|
1118
|
-
|
|
1119
|
-
2
|
|
1120
|
-
- \`shadow_ops_chronicle\` (since: <unix>, limit: 20, repoPath)
|
|
1121
|
-
- \`shadow_ops_chronicle\` (until: <unix>, limit: 20, repoPath)
|
|
1122
|
-
3. **Structured Data**: \`shadow_ops_chronicle\` (format: "json", limit: 50, repoPath) \u2014 For processing.
|
|
1123
|
-
4. **Paginated**: \`shadow_ops_chronicle\` (limit: 10, offset: 10, repoPath) \u2014 Second page.
|
|
1103
|
+
# Run liquid-shadow sync in background
|
|
1104
|
+
nohup "${s}" "${e}" sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
1124
1105
|
|
|
1125
|
-
|
|
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:`---
|
|
1129
|
+
name: chronicle
|
|
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.
|
|
1131
|
+
---
|
|
1126
1132
|
|
|
1127
|
-
|
|
1128
|
-
| :-------------------- | :---------------------------------------------------------------- |
|
|
1129
|
-
| **Recent (Markdown)** | \`shadow_ops_chronicle\` (limit: 10, format: "markdown") |
|
|
1130
|
-
| **Time Range** | \`shadow_ops_chronicle\` (since: <unix>, until: <unix>) |
|
|
1131
|
-
| **JSON Data** | \`shadow_ops_chronicle\` (format: "json", limit: 50) |
|
|
1132
|
-
| **Pagination** | \`shadow_ops_chronicle\` (limit: 10, offset: 10) |
|
|
1133
|
+
# Chronicle
|
|
1133
1134
|
|
|
1134
|
-
|
|
1135
|
+
Use this skill when the answer lives in mission history rather than the current code graph.
|
|
1135
1136
|
|
|
1136
|
-
|
|
1137
|
-
- **\`format: "json"\`**: Structured data for programmatic analysis (includes missionId, steps, timestamps, ADRs)
|
|
1137
|
+
## Core calls
|
|
1138
1138
|
|
|
1139
|
-
|
|
1139
|
+
- Recent narrative: \`shadow_ops_chronicle({ repoPath, limit: 10, format: "markdown" })\`
|
|
1140
|
+
- Structured output: \`shadow_ops_chronicle({ repoPath, format: "json", limit: 50 })\`
|
|
1141
|
+
- Time window: \`shadow_ops_chronicle({ repoPath, since, until })\`
|
|
1142
|
+
- Branch-scoped history: \`shadow_ops_chronicle({ repoPath, branch, limit })\`
|
|
1143
|
+
- Pagination: \`shadow_ops_chronicle({ repoPath, limit, offset })\`
|
|
1140
1144
|
|
|
1141
|
-
|
|
1142
|
-
- **Release Notes**: Get completed missions since last release
|
|
1143
|
-
- **ADR Review**: Extract all architectural decisions
|
|
1144
|
-
- **Progress Reports**: Show what's been done this week
|
|
1145
|
+
## Good pairings
|
|
1145
1146
|
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
name: crystallize
|
|
1149
|
-
description: Compress a mission's intent logs into a dense crystal summary for token-efficient briefings. Use when a mission has accumulated many raw logs, when briefings are too verbose, or when the user asks about log compression, crystallization, or context reduction.
|
|
1150
|
-
---
|
|
1147
|
+
- \`shadow_ops_context({ repoPath, compact: true })\` if you also need the current mission landscape.
|
|
1148
|
+
- \`shadow_ops_graph({ repoPath, missionId, format: "mermaid" })\` when a historical mission hierarchy matters.
|
|
1151
1149
|
|
|
1152
|
-
|
|
1150
|
+
## Notes
|
|
1153
1151
|
|
|
1154
|
-
|
|
1152
|
+
- \`format: "markdown"\` is best for humans.
|
|
1153
|
+
- \`format: "json"\` is best when another tool or agent will process the result.
|
|
1154
|
+
- Chronicle is backed by Git Notes, so it survives across branches and clones.
|
|
1155
|
+
`,shadow_continue:`---
|
|
1156
|
+
name: continue
|
|
1157
|
+
description: Get briefing, pick one mission from next_work_candidates, then work that mission to completion with all remaining steps in one run. Use when continuing work on missions, executing mission steps, or when the user asks to continue work, finish a mission, or proceed with development tasks.
|
|
1158
|
+
---
|
|
1155
1159
|
|
|
1156
|
-
|
|
1160
|
+
# Continue
|
|
1161
|
+
|
|
1162
|
+
Pick one mission from \`next_work_candidates\` and finish it end to end.
|
|
1163
|
+
|
|
1164
|
+
## Start
|
|
1165
|
+
|
|
1166
|
+
1. \`shadow_ops_context({ repoPath, compact: true })\` or \`shadow_ops_briefing({ repoPath, scope: "project", altitude: "orbit" })\`
|
|
1167
|
+
2. Pick one leaf mission from \`next_work_candidates\`. Prefer in-progress over planned.
|
|
1168
|
+
3. If there is no candidate, stop and plan new work instead of inventing a mission.
|
|
1169
|
+
|
|
1170
|
+
## Work loop
|
|
1171
|
+
|
|
1172
|
+
- Mark the active step: \`shadow_ops_track({ repoPath, missionId, stepId, status: "in-progress" })\`
|
|
1173
|
+
- If multiple agents may edit the same area, check and claim first:
|
|
1174
|
+
- \`shadow_working_set_check({ repoPath, filePaths })\`
|
|
1175
|
+
- \`shadow_ops_claim({ repoPath, missionId, filePaths, agentTag? })\`
|
|
1176
|
+
- Do focused discovery with the relevant search, recon, analyze, and inspect tools.
|
|
1177
|
+
- Record at least one meaningful log per step:
|
|
1178
|
+
- \`shadow_ops_log({ repoPath, missionId, type: "decision" | "discovery" | "fix", content, filePath?, symbolName? })\`
|
|
1179
|
+
- Mark each finished step:
|
|
1180
|
+
- \`shadow_ops_track({ repoPath, missionId, stepId, status: "completed", contextPivot? })\`
|
|
1181
|
+
|
|
1182
|
+
## Finish
|
|
1183
|
+
|
|
1184
|
+
- Optional handoff for downstream agents:
|
|
1185
|
+
- \`shadow_ops_handoff({ repoPath, missionId, kind, findings, risks?, gaps?, confidence?, agentTag? })\`
|
|
1186
|
+
- \`shadow_ops_handoff_read({ repoPath, missionId?, kind?, query?, limit? })\`
|
|
1187
|
+
- Optional review gate, but only after the user explicitly asks for Tribunal or clearly approves it:
|
|
1188
|
+
- \`shadow_ops_tribunal_submit({ repoPath, missionId })\`
|
|
1189
|
+
- \`shadow_ops_tribunal_status({ repoPath, missionId })\`
|
|
1190
|
+
- Release any claims you took:
|
|
1191
|
+
- \`shadow_ops_release({ repoPath, missionId, filePaths? })\`
|
|
1192
|
+
- Complete the mission:
|
|
1193
|
+
- \`shadow_ops_track({ repoPath, missionId, status: "completed" })\`
|
|
1194
|
+
|
|
1195
|
+
## Rules
|
|
1196
|
+
|
|
1197
|
+
- Don't do one step and stop \u2014 /continue is "finish a mission," not "do one step."
|
|
1198
|
+
- Don't call \`shadow_ops_synthesize\` after completion unless you are intentionally regenerating the record.
|
|
1199
|
+
- Never run Tribunal without explicit user consent.
|
|
1200
|
+
- \`shadow_ops_handoff\` does not take \`role\` or \`summary\`; use \`kind\` plus structured \`findings\`.
|
|
1201
|
+
- \`shadow_ops_crystallize_theme\` takes \`theme\`, not \`query\`.
|
|
1202
|
+
`,shadow_coordinate:`---
|
|
1203
|
+
name: coordinate
|
|
1204
|
+
description: Coordinate multi-agent or parallel work with working-set checks, file claims, dispatch waves, handoffs, and user-approved Tribunal review. Use when several agents may edit at once or when work must be transferred cleanly.
|
|
1205
|
+
---
|
|
1157
1206
|
|
|
1158
|
-
|
|
1159
|
-
- Mid-mission, before requesting a detailed briefing \u2014 keeps \`atmosphere\` altitude lean.
|
|
1160
|
-
- Before synthesis (optional) \u2014 produces cleaner ADRs from compressed input.
|
|
1161
|
-
- The briefing at \`atmosphere\` altitude already prefers crystals over raw logs (\`findByMissionPreferCrystal\`), so crystallizing makes those briefings significantly leaner.
|
|
1207
|
+
# Coordinate
|
|
1162
1208
|
|
|
1163
|
-
|
|
1209
|
+
Use this skill when execution risk comes from overlap, not code complexity.
|
|
1164
1210
|
|
|
1165
|
-
|
|
1166
|
-
2. **Verify**: \`shadow_ops_briefing\` (scope: "mission", missionId, altitude: "atmosphere", repoPath) \u2014 Crystal should appear in \`recent_activity\` instead of raw logs.
|
|
1211
|
+
## Conflict control
|
|
1167
1212
|
|
|
1168
|
-
|
|
1213
|
+
- \`shadow_working_set_check({ repoPath, filePaths })\`
|
|
1214
|
+
- \`shadow_ops_claim({ repoPath, missionId, filePaths, agentTag? })\`
|
|
1215
|
+
- \`shadow_ops_release({ repoPath, missionId, filePaths? })\`
|
|
1169
1216
|
|
|
1170
|
-
|
|
1171
|
-
| :--------------- | :--------------------------------------------- | :-------------------------------------- |
|
|
1172
|
-
| **Crystallize** | \`shadow_ops_crystallize\` | missionId, repoPath \u2014 compress raw logs |
|
|
1173
|
-
| **Check Status** | \`shadow_ops_briefing\` (altitude: "atmosphere") | Verify crystal appears in activity |
|
|
1174
|
-
| **Full Logs** | \`shadow_ops_briefing\` (altitude: "ground") | Still shows raw logs if needed |
|
|
1217
|
+
## Parallel planning
|
|
1175
1218
|
|
|
1176
|
-
|
|
1219
|
+
- \`shadow_ops_dispatch_plan({ repoPath, parentMissionId?, missionIds?, includeClaimCheck: true })\`
|
|
1220
|
+
- \`shadow_ops_graph({ repoPath, missionId, depth?, format: "mermaid" | "json" })\`
|
|
1177
1221
|
|
|
1178
|
-
|
|
1179
|
-
- Count of compressed logs and symbols
|
|
1180
|
-
- Log types present (decision, fix, discovery, blocker)
|
|
1181
|
-
- Structured breakdown: decisions, context, consequences, recommendations
|
|
1222
|
+
## Handoffs
|
|
1182
1223
|
|
|
1183
|
-
|
|
1224
|
+
- Write: \`shadow_ops_handoff({ repoPath, missionId?, kind, findings, risks?, gaps?, missionsCreated?, confidence?, agentTag? })\`
|
|
1225
|
+
- Read: \`shadow_ops_handoff_read({ repoPath, missionId?, kind?, query?, limit? })\`
|
|
1184
1226
|
|
|
1185
|
-
|
|
1186
|
-
- New logs added after crystallization remain as raw until the next crystallize call.
|
|
1187
|
-
- Raw logs are **not deleted** \u2014 they're marked as absorbed. \`ground\` altitude still shows them.
|
|
1188
|
-
`,shadow_mission:`---
|
|
1189
|
-
name: mission
|
|
1190
|
-
description: Define the objective, strategy, and success criteria for a new development mission. Use when planning strategic initiatives, creating missions, setting up development goals, or when the user asks about mission planning, strategic alignment, or outcome contracts.
|
|
1191
|
-
---
|
|
1227
|
+
Available \`kind\` values:
|
|
1192
1228
|
|
|
1193
|
-
|
|
1229
|
+
- \`recon_report\`
|
|
1230
|
+
- \`risk_assessment\`
|
|
1231
|
+
- \`impact_map\`
|
|
1232
|
+
- \`debt_scan\`
|
|
1233
|
+
- \`custom\`
|
|
1194
1234
|
|
|
1195
|
-
|
|
1235
|
+
## Tribunal
|
|
1196
1236
|
|
|
1197
|
-
|
|
1237
|
+
Never run Tribunal unless the user explicitly asks for it or clearly approves it.
|
|
1198
1238
|
|
|
1199
|
-
|
|
1239
|
+
- \`shadow_ops_tribunal_submit({ repoPath, missionId })\`
|
|
1240
|
+
- \`shadow_ops_tribunal_status({ repoPath, missionId? or sessionId? })\`
|
|
1200
1241
|
|
|
1201
|
-
|
|
1202
|
-
2. **Optional Expanded Context** (only if needed):
|
|
1203
|
-
- \`shadow_recon_topography\` (repoPath) \u2014 Detailed layer breakdown to align goal with architecture.
|
|
1204
|
-
- \`shadow_ops_chronicle\` (limit: 10, repoPath) \u2014 More historical ADRs if 5 isn't enough.
|
|
1205
|
-
- \`shadow_ops_briefing\` (scope: "project", altitude: "ground", repoPath) \u2014 Full detail with analytics, collisions, and working sets.
|
|
1206
|
-
3. **Strategic Plan**: \`shadow_ops_plan\` (name, goal, outcomeContract, ...).
|
|
1207
|
-
- **Strategy DAG**: Define logical steps and verification rules.
|
|
1208
|
-
- **Initiative vs Mission**: Decide if this is a parent (Initiative) or a leaf (Mission). Parent missions auto-complete via cascade when all children finish.
|
|
1209
|
-
4. **Alignment**: Present the plan to the user. Do not begin execution until the user approves the strategy.
|
|
1242
|
+
## Rules
|
|
1210
1243
|
|
|
1211
|
-
|
|
1244
|
+
- Claim only the files you expect to edit.
|
|
1245
|
+
- Release claims promptly when the work is done.
|
|
1246
|
+
- Tribunal is opt-in only. Treat it as a user-consent gate, not an automatic review step.
|
|
1247
|
+
- Handoffs must be structured. There is no \`role\` or \`summary\` field.
|
|
1248
|
+
`,shadow_crystallize:`---
|
|
1249
|
+
name: crystallize
|
|
1250
|
+
description: Compress a mission's intent logs into a dense crystal summary for token-efficient briefings. Use when a mission has accumulated many raw logs, when briefings are too verbose, or when the user asks about log compression, crystallization, or context reduction.
|
|
1251
|
+
---
|
|
1212
1252
|
|
|
1213
|
-
|
|
1214
|
-
| :-------------------- | :----------------------------------------- | :-------------------------------------------------------------------------------------------------- |
|
|
1215
|
-
| **Session Start** | \`shadow_ops_context\` | **START HERE** \u2014 hologram + chronicle + briefing in one call |
|
|
1216
|
-
| **Establish Plan** | \`shadow_ops_plan\` | Create the mission and strategy. |
|
|
1217
|
-
| **Architectural Map** | \`shadow_recon_topography\` | Contextualize the target layers (if context wasn't enough). |
|
|
1218
|
-
| **Detailed Briefing** | \`shadow_ops_briefing\` (altitude: "ground") | Full analytics, collisions, working sets. |
|
|
1219
|
-
| **Lean Briefing** | \`shadow_ops_briefing\` (altitude: "orbit") | Counts + candidates only (~200 tokens). |
|
|
1220
|
-
| **Graph View** | \`shadow_ops_graph\` | Visualize the initiative's hierarchy. |
|
|
1221
|
-
| **Theme Patterns** | \`shadow_ops_crystallize_theme\` | Before planning: surface recurring themes across past missions to avoid repeating solved problems. |
|
|
1222
|
-
| **Prior Handoffs** | \`shadow_ops_handoff_read\` | In multi-agent contexts: retrieve typed findings from a prior RECON agent before defining strategy. |
|
|
1223
|
-
| **Event Mesh** | \`shadow_analyze_mesh\` | When planning event-driven or API work: map all HTTP routes, socket events, pubsub topics. |
|
|
1253
|
+
# Crystallize
|
|
1224
1254
|
|
|
1225
|
-
|
|
1255
|
+
Compress raw intent logs into a crystal so briefings stay useful instead of noisy.
|
|
1226
1256
|
|
|
1227
|
-
##
|
|
1257
|
+
## Core calls
|
|
1228
1258
|
|
|
1229
|
-
-
|
|
1230
|
-
-
|
|
1231
|
-
-
|
|
1259
|
+
- Mission-level compression: \`shadow_ops_crystallize({ repoPath, missionId })\`
|
|
1260
|
+
- Verify the result: \`shadow_ops_briefing({ repoPath, scope: "mission", missionId, altitude: "atmosphere" })\`
|
|
1261
|
+
- Cross-mission theme compression: \`shadow_ops_crystallize_theme({ repoPath, theme, missionIds?, limit? })\`
|
|
1232
1262
|
|
|
1233
|
-
##
|
|
1263
|
+
## When to use it
|
|
1234
1264
|
|
|
1235
|
-
|
|
1265
|
+
- A mission has many raw logs and \`atmosphere\` briefings are getting bloated.
|
|
1266
|
+
- You want cleaner synthesis input before closing a mission.
|
|
1267
|
+
- You want to surface repeating patterns across missions with \`theme\`.
|
|
1236
1268
|
|
|
1237
|
-
|
|
1238
|
-
- **Discovery Logs**: Record insights found during initial reconnaissance.
|
|
1269
|
+
## Notes
|
|
1239
1270
|
|
|
1240
|
-
|
|
1241
|
-
|
|
1271
|
+
- Crystallization is **idempotent**: if no new raw logs exist, it reports \`already_crystallized\`.
|
|
1272
|
+
- Raw logs are not deleted; they are marked as absorbed.
|
|
1273
|
+
- New logs stay raw until the next crystallize call.
|
|
1274
|
+
- \`shadow_ops_crystallize_theme\` takes \`theme\`, not \`query\`.
|
|
1275
|
+
`,shadow_mission:'---\nname: mission\ndescription: Define the objective, strategy, and success criteria for a mission. Use when planning new work, shaping initiatives, writing outcome contracts, or aligning a task before execution starts.\n---\n\n# Mission\n\nThis skill is for planning. It stops at "ready to execute."\n\n## Start\n\n1. `shadow_ops_context({ repoPath, compact: true })`\n2. If needed, expand with:\n - `shadow_recon_topography({ repoPath })`\n - `shadow_ops_briefing({ repoPath, scope: "project", altitude: "ground" })`\n - `shadow_ops_chronicle({ repoPath, limit: 10 })`\n3. Reuse prior intelligence when available:\n - `shadow_ops_handoff_read({ repoPath, missionId?, kind?, query? })`\n - `shadow_ops_crystallize_theme({ repoPath, theme, missionIds? })`\n\n## Create the mission\n\nUse `shadow_ops_plan` with the fields that matter:\n\n- `name`: short, concrete title\n- `goal`: what changes and why\n- `outcomeContract`: binary success test\n- `strategy`: JSON step graph when the work has multiple stages\n- `workingSet`: expected files or directories\n- `templateId`: `refactoring`, `feature`, or `bug-fix`\n- `parentId`: when this mission belongs under an initiative\n\n## Planning rules\n\n- Prefer a leaf mission when one deliverable can be completed in one run.\n- Use a parent initiative only when the work is intentionally split into child missions.\n- Keep `outcomeContract` verifiable. "Looks good" is not a contract.\n- If API or event boundaries matter, use `shadow_analyze_mesh({ repoPath, topic, type? })` with a concrete route or topic fragment.\n- Present the plan for approval before execution. Use `/continue` for the actual implementation pass.\n',shadow_onboard:'---\nname: onboard\ndescription: Initialize and analyze a repository for Shadow workflows. Use when onboarding a repo, bootstrapping indexes and hooks, checking intelligence health, or preparing the first mission.\n---\n\n# Onboard\n\nUse this skill when a repository needs its first Shadow pass or when a fresh clone needs to be made operational.\n\n## Core workflow\n\n1. `shadow_recon_onboard({ repoPath })`\n2. `shadow_recon_hologram({ repoPath, compact: true })`\n3. `shadow_sync_trace({ repoPath })`\n4. `shadow_ops_health({ repoPath })`\n5. `shadow_ops_context({ repoPath, compact: true })`\n\n## Useful follow-ups\n\n- `shadow_recon_topography({ repoPath })` for layer breakdown.\n- `shadow_ops_chronicle({ repoPath, limit: 5 })` for recent decisions.\n- `shadow_env_diagnose({ repoPath })` for hooks, index, and daemon health.\n- `shadow_env_hooks({ repoPath, action: "install", enableAutoRefresh: true, enableSymbolHealing: true })`\n- `shadow_ops_plan({ repoPath, name, goal, outcomeContract? })` for the first mission.\n\n## Rules\n\n- Always use an absolute `repoPath`.\n- `shadow_recon_onboard` is the baseline bootstrap; `shadow_sync_trace` is the normal follow-up maintenance pass.\n- Do not call `shadow_analyze_mesh` without a concrete `topic`.\n',shadow_research:`---
|
|
1242
1276
|
name: research
|
|
1243
|
-
description:
|
|
1277
|
+
description: Research external dependencies without losing local context. Use when checking library usage, verifying versions, finding integration examples, or comparing official documentation against what the repo already does.
|
|
1244
1278
|
---
|
|
1245
1279
|
|
|
1246
|
-
#
|
|
1247
|
-
|
|
1248
|
-
High-signal research for external dependencies.
|
|
1280
|
+
# Research
|
|
1249
1281
|
|
|
1250
|
-
|
|
1282
|
+
Start local, then verify externally.
|
|
1251
1283
|
|
|
1252
|
-
|
|
1253
|
-
2. **Web Search**: Use the \`WebSearch\` tool for official docs and latest versions.
|
|
1254
|
-
3. **Deep Intel (Context7)**: resolve-library-id, query-docs (server: user-context7).
|
|
1255
|
-
4. **Integration Check**: \`shadow_inspect_file\` (filePath, detailLevel: "signatures", repoPath).
|
|
1256
|
-
5. **Log Findings**: \`shadow_ops_log\` (type: "discovery", content, repoPath).
|
|
1284
|
+
## Local first
|
|
1257
1285
|
|
|
1258
|
-
|
|
1286
|
+
- \`shadow_search_concept({ repoPath, query, compact: true })\` for existing patterns.
|
|
1287
|
+
- \`shadow_search_path({ repoPath, query, ranked: true })\` for likely integration files.
|
|
1288
|
+
- \`shadow_search_config({ repoPath, key?, query?, showUsage: true })\` for env and config hooks.
|
|
1289
|
+
- \`shadow_analyze_deps({ repoPath, filePath, direction: "imports" | "imported_by" })\` to see how the dependency sits in the graph.
|
|
1290
|
+
- \`shadow_inspect_file({ repoPath, filePath, detailLevel: "signatures" })\` for a quick local API read.
|
|
1259
1291
|
|
|
1260
|
-
|
|
1261
|
-
| :----------------- | :-------------------------------------------------------------------------- |
|
|
1262
|
-
| **Local Usage** | \`shadow_search_concept\` (query, **compact: true** for broad search) |
|
|
1263
|
-
| **File Discovery** | \`shadow_search_path\` (query, **ranked: true**) \u2014 gravity-sorted with layers |
|
|
1264
|
-
| **Config Check** | \`shadow_search_config\` (key, **showUsage: true**) \u2014 with usage counts |
|
|
1265
|
-
| **External Docs** | context7 tools (user-context7) |
|
|
1266
|
-
| **Relational** | \`shadow_analyze_deps\` (filePath, direction) |
|
|
1292
|
+
## External verification
|
|
1267
1293
|
|
|
1268
|
-
|
|
1294
|
+
- Use the host model's documentation or web tools to read official vendor docs and primary sources.
|
|
1295
|
+
- Check the exact installed version in \`package.json\`, lockfiles, or existing imports before trusting examples.
|
|
1296
|
+
- Prefer official docs over blogs, and repo-local patterns over generic snippets.
|
|
1269
1297
|
|
|
1270
|
-
|
|
1271
|
-
- **\`shadow_search_path\` with \`ranked: true\`**: Results sorted by gravity (high-import files first) with layer classification. Reveals architecturally important files.
|
|
1272
|
-
- **\`shadow_search_config\` with \`showUsage: true\`**: Shows usage counts per config var and identifies orphaned vars (defined but never used in code).
|
|
1298
|
+
## Closeout
|
|
1273
1299
|
|
|
1274
|
-
|
|
1300
|
+
- \`shadow_ops_log({ repoPath, missionId?, type: "discovery", content, filePath? })\` when the research affects an ongoing mission.
|
|
1275
1301
|
`,shadow_sync:`---
|
|
1276
1302
|
name: sync
|
|
1277
1303
|
description: 'Sync index and mission state after external changes. Day-to-day: index + NanoRepair run automatically when MCP tools (search, inspect, etc.) trigger reindex. Use trace after git pull/checkout/merge (or rely on hooks); use index deep:true for full rebuild.'
|
|
1278
1304
|
---
|
|
1279
1305
|
|
|
1280
|
-
#
|
|
1306
|
+
# Sync
|
|
1281
1307
|
|
|
1282
|
-
|
|
1308
|
+
Day-to-day, Shadow often reindexes on demand. Use manual sync when the repository changed outside the normal flow.
|
|
1283
1309
|
|
|
1284
|
-
##
|
|
1310
|
+
## Prefer these calls
|
|
1285
1311
|
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1312
|
+
- After \`pull\`, \`checkout\`, \`merge\`, or large rebases:
|
|
1313
|
+
- \`shadow_sync_trace({ repoPath, sinceCommit?, enableContextPivot?, enableMergeSentinel? })\`
|
|
1314
|
+
- For an explicit rebuild:
|
|
1315
|
+
- \`shadow_sync_index({ repoPath, deep: true })\`
|
|
1316
|
+
- For repair only:
|
|
1317
|
+
- \`shadow_sync_repair({ repoPath })\`
|
|
1291
1318
|
|
|
1292
|
-
|
|
1319
|
+
## Health checks
|
|
1320
|
+
|
|
1321
|
+
- \`shadow_ops_health({ repoPath })\`
|
|
1322
|
+
- \`shadow_env_diagnose({ repoPath })\`
|
|
1323
|
+
|
|
1324
|
+
## Rules
|
|
1325
|
+
|
|
1326
|
+
- Prefer \`shadow_sync_trace\` over \`shadow_sync_index\` unless you specifically want a rebuild.
|
|
1327
|
+
- Use \`deep: true\` sparingly; it is the expensive option.
|
|
1293
1328
|
`,shadow_synthesize:`---
|
|
1294
1329
|
name: synthesize
|
|
1295
1330
|
description: Distill mission logs into Architectural Decision Records (ADRs) and persist them to the Shadow Engine and Git Notes. Use when completing missions, creating ADRs, synthesizing architectural decisions, or when the user asks about decision records, mission completion, or architectural documentation.
|
|
1296
1331
|
---
|
|
1297
1332
|
|
|
1298
|
-
#
|
|
1333
|
+
# Synthesize
|
|
1334
|
+
|
|
1335
|
+
Use this skill when a mission needs to become durable project memory.
|
|
1299
1336
|
|
|
1300
|
-
|
|
1337
|
+
## Primary path
|
|
1301
1338
|
|
|
1302
|
-
|
|
1339
|
+
- Complete the mission:
|
|
1340
|
+
- \`shadow_ops_track({ repoPath, missionId, status: "completed" })\`
|
|
1341
|
+
- Verify the synthesized record:
|
|
1342
|
+
- \`shadow_ops_chronicle({ repoPath, limit: 5 })\`
|
|
1303
1343
|
|
|
1304
|
-
##
|
|
1344
|
+
## Secondary tools
|
|
1305
1345
|
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
- Format the ADR using markdown and **Liquid Anchors**.
|
|
1310
|
-
- Persist the record to SQLite and **Git Notes**.
|
|
1311
|
-
- **Cascade**: If all sibling missions under the same parent are completed, the parent mission auto-completes with its own ADR synthesis.
|
|
1312
|
-
2. **Verify**: Check the synthesized record via \`shadow_ops_chronicle\` (limit: 5, repoPath).
|
|
1313
|
-
3. **Manual Synthesis**: Use \`shadow_ops_synthesize\` only to **re-generate** an existing record or for specific partial distillations.
|
|
1314
|
-
4. **Pre-synthesis Compression** (optional): For missions with many raw logs, \`shadow_ops_crystallize\` (missionId, repoPath) compresses logs into a crystal summary before synthesis for cleaner ADRs.
|
|
1346
|
+
- \`shadow_ops_synthesize({ repoPath, missionId })\` only when you need to regenerate the ADR after the mission is already complete.
|
|
1347
|
+
- \`shadow_ops_crystallize({ repoPath, missionId })\` before completion if the mission has many raw logs.
|
|
1348
|
+
- \`shadow_ops_crystallize_theme({ repoPath, theme, missionIds? })\` when you want a cross-mission architectural thread.
|
|
1315
1349
|
|
|
1316
|
-
##
|
|
1350
|
+
## Rules
|
|
1317
1351
|
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
| **View Chronicle** | \`shadow_ops_chronicle\` | View the combined narrative feed. |
|
|
1352
|
+
- Completion auto-triggers synthesis and parent cascade behavior.
|
|
1353
|
+
- Do not maintain parallel ADR markdown files unless the user explicitly wants one.
|
|
1354
|
+
`,shadow_trace_impact:`---
|
|
1355
|
+
name: trace-impact
|
|
1356
|
+
description: Map the blast radius of a change by analyzing impact, flow traces, cross-repo dependencies, and boundary maps. Use when analyzing change impact, assessing risk, tracing dependencies, or when the user asks about change impact, blast radius, or dependency analysis.
|
|
1357
|
+
---
|
|
1325
1358
|
|
|
1326
|
-
|
|
1359
|
+
# Trace Impact
|
|
1327
1360
|
|
|
1328
|
-
|
|
1361
|
+
Use this skill to answer "what breaks if we touch this?"
|
|
1329
1362
|
|
|
1330
|
-
|
|
1363
|
+
## Core workflow
|
|
1331
1364
|
|
|
1332
|
-
1.
|
|
1333
|
-
2.
|
|
1334
|
-
3.
|
|
1335
|
-
4.
|
|
1336
|
-
5.
|
|
1365
|
+
1. \`shadow_ops_context({ repoPath, compact: true })\`
|
|
1366
|
+
2. \`shadow_analyze_impact({ repoPath, symbolName, filePath?, depth: 3 })\`
|
|
1367
|
+
3. \`shadow_analyze_deps({ repoPath, filePath, direction: "imported_by" })\`
|
|
1368
|
+
4. \`shadow_analyze_deps({ repoPath, filePath, direction: "imports" })\`
|
|
1369
|
+
5. \`shadow_analyze_flow({ repoPath, filePath, symbolName? })\`
|
|
1337
1370
|
|
|
1338
|
-
##
|
|
1371
|
+
## Add precision
|
|
1339
1372
|
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1373
|
+
- \`shadow_analyze_explain_diff({ repoPath, baseCommit?, headCommit?, staged? })\` for a semantic read of an actual diff.
|
|
1374
|
+
- \`shadow_analyze_type_graph({ repoPath, symbolName, filePath?, direction?, relationship? })\` when the change is type-heavy.
|
|
1375
|
+
- \`shadow_analyze_debt({ repoPath, mode: "circular-deps" })\` for cycle risk.
|
|
1376
|
+
- \`shadow_recon_topography({ repoPath })\` for layer-crossing risk.
|
|
1377
|
+
- \`shadow_workspace_fuse({ repoPaths, name? })\` before cross-repo analysis.
|
|
1378
|
+
- \`shadow_analyze_mesh({ repoPath, topic, includeCrossRepo: true })\` when the affected boundary is a known route or event.
|
|
1345
1379
|
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
5. **Health Check**:
|
|
1359
|
-
- \`shadow_analyze_debt\` (mode: "circular-deps", repoPath) \u2014 Any import cycles?
|
|
1360
|
-
- \`shadow_analyze_debt\` (mode: "dead-code", limit: 50, repoPath) \u2014 Unused exports?
|
|
1361
|
-
6. **Cross-Repo Check** (if multi-repo):
|
|
1362
|
-
- \`shadow_workspace_fuse\` (repoPaths, repoPath).
|
|
1363
|
-
- \`shadow_search_symbol\` (query, limit: 50, repoPath).
|
|
1364
|
-
7. **Boundary Map**: \`shadow_recon_topography\` (repoPath) \u2014 Layer crossing check.
|
|
1365
|
-
8. **Log Risk**: \`shadow_ops_log\` (missionId, type: "discovery", content, symbolName, repoPath).
|
|
1366
|
-
|
|
1367
|
-
## \u{1F6E0} Precise Tooling
|
|
1368
|
-
|
|
1369
|
-
| Impact Layer | Atomic Tool |
|
|
1370
|
-
| :------------------- | :------------------------------------------------------------------------- |
|
|
1371
|
-
| **Session Start** \u{1F680} | \`shadow_ops_context\` (repoPath) \u2014 **START HERE** for context |
|
|
1372
|
-
| **Hologram** | \`shadow_recon_hologram\` (repoPath) \u2014 if you need standalone |
|
|
1373
|
-
| **Blast Radius** | \`shadow_analyze_impact\` (symbolName, depth: 3) |
|
|
1374
|
-
| **Dependents** | \`shadow_analyze_deps\` (filePath, direction: "imported_by") |
|
|
1375
|
-
| **Dependencies** | \`shadow_analyze_deps\` (filePath, direction: "imports") |
|
|
1376
|
-
| **Flow Path** | \`shadow_analyze_flow\` (symbolName, filePath) |
|
|
1377
|
-
| **Circular Deps** | \`shadow_analyze_debt\` (mode: "circular-deps") |
|
|
1378
|
-
| **Dead Code** | \`shadow_analyze_debt\` (mode: "dead-code", **confidenceThreshold: "high"**) |
|
|
1379
|
-
| **File Discovery** | \`shadow_search_path\` (query, **ranked: true**) \u2014 gravity-sorted |
|
|
1380
|
-
| **Workspace Fuse** | \`shadow_workspace_fuse\` (repoPaths, repoPath) |
|
|
1381
|
-
| **Topography** | \`shadow_recon_topography\` |
|
|
1382
|
-
|
|
1383
|
-
## \u{1F4A1} Intelligence Options
|
|
1384
|
-
|
|
1385
|
-
- **\`shadow_search_path\` with \`ranked: true\`**: Find related files sorted by gravity (high-import files first) with layer classification. Helps identify which affected files are architecturally critical.
|
|
1386
|
-
- **\`shadow_analyze_debt\` confidence levels**: Use \`confidenceThreshold: "high"\` to focus on likely dead code, avoiding noise from test fixtures and migrations.
|
|
1387
|
-
|
|
1388
|
-
_Note: **Start with \`shadow_ops_context\`** for instant gravity zones + architectural context. Use depth higher than 3 for impact analysis only if the symbol is a fundamental primitive (e.g., RepositoryFactory)._
|
|
1389
|
-
|
|
1390
|
-
## \u{1F6E0} Risk Classification
|
|
1391
|
-
|
|
1392
|
-
- **Critical Risk**: Symbol in gravity zones (top 10) + >20 dependents + crosses layers
|
|
1393
|
-
- **High Risk**: >10 dependents OR crosses layers (e.g., Test -> Logic)
|
|
1394
|
-
- **Medium Risk**: 5-10 dependents within same layer
|
|
1395
|
-
- **Low Risk**: <5 dependents, same layer, no circular deps
|
|
1396
|
-
`,shadow_understand:'---\nname: understand\ndescription: Find the high-signal path to understanding complex logic through intent retrieval, topological placement, relational analysis, and mechanics inspection. Use when understanding architecture, analyzing complex code, tracing logic flow, or when the user asks about how something works, architectural patterns, or code comprehension.\n---\n\n# Architectural Understanding\n\nFind the high-signal path to understanding complex logic.\n\n## Workflow\n\n1. **Session Context (The Fast Lane)**: `shadow_ops_context` (repoPath) \u2014 **ONE CALL** returns hologram + chronicle(5) + briefing (relevance-ranked candidates).\n - Skip to step 3 if you have what you need from context alone.\n2. **Optional Expanded Context** (only if shadow_ops_context wasn\'t enough):\n - `shadow_recon_topography` (repoPath) \u2014 Detailed layer breakdown beyond hologram summary.\n - `shadow_recon_tree` (subPath: "src/services", maxDepth: 2, repoPath) \u2014 Visual file hierarchy.\n - `shadow_ops_briefing` (scope: "mission", missionId, altitude: "ground") \u2014 Full mission detail with raw logs, working set, collisions.\n3. **Relational Analysis (The Who)**:\n - `shadow_analyze_impact` (symbolName, filePath, depth: 3, repoPath) \u2014 Blast radius.\n - `shadow_analyze_deps` (filePath, direction: "imported_by", repoPath) \u2014 Who depends on this?\n - `shadow_search_concept` (query, repoPath) \u2014 Semantic search.\n - `shadow_analyze_mesh` (repoPath) \u2014 When the system is event-driven: map all HTTP routes, socket events, pubsub topics and their producers/consumers.\n - `shadow_analyze_type_graph` (filePath, repoPath) \u2014 When understanding a type system: interface/class inheritance chains.\n4. **Mechanics (The How)**:\n - **For Logic**: `shadow_analyze_flow` (symbolName, filePath, repoPath) \u2014 Trace execution.\n - **For Objects**: `shadow_inspect_file` (filePath, detailLevel: "signatures", repoPath) \u2014 All exports.\n - **For Symbol Deep Dive**: `shadow_inspect_symbol` (symbolName, filePath, context: "full", repoPath) \u2014 With deps.\n - **For Change History**: `shadow_analyze_explain_diff` (fromCommit, toCommit, repoPath) \u2014 Semantic narrative of what changed and why between commits.\n5. **Synthesis**: `shadow_ops_log` (missionId, type: "discovery", content, symbolName, repoPath).\n\n## Precise Tooling\n\n| Discovery Layer | Atomic Tool |\n| :----------------- | :--------------------------------------------------------------------------------------------------- |\n| **Session Start** | `shadow_ops_context` (repoPath) \u2014 **START HERE** |\n| **Hologram** | `shadow_recon_hologram` (repoPath) \u2014 if you need standalone hologram |\n| **History** | `shadow_ops_chronicle` (limit: 5) \u2014 if you need more than 5 from context |\n| **Layers** | `shadow_recon_topography` \u2014 detailed breakdown |\n| **Mission Detail** | `shadow_ops_briefing` (altitude: "ground") \u2014 full logs + working set |\n| **Blast Radius** | `shadow_analyze_impact` (symbolName, depth: 3) |\n| **Dependents** | `shadow_analyze_deps` (filePath, direction: "imported_by") |\n| **Flow Trace** | `shadow_analyze_flow` (symbolName, filePath) |\n| **Structure** | `shadow_inspect_file` (detailLevel: "signatures") |\n| **Deep Dive** | `shadow_inspect_symbol` (context: "full") |\n| **File Discovery** | `shadow_search_path` (query, **ranked: true**) \u2014 gravity-sorted results with layer classification |\n| **Event Mesh** | `shadow_analyze_mesh` (repoPath) \u2014 HTTP routes, socket events, pubsub topics + producers/consumers |\n| **Type Graph** | `shadow_analyze_type_graph` (filePath) \u2014 interface/class inheritance chains |\n| **Explain Diff** | `shadow_analyze_explain_diff` (fromCommit, toCommit) \u2014 semantic narrative of changes between commits |\n\n_Note: **ALWAYS start with `shadow_ops_context`** for instant architectural context + history + mission state in ONE call. Use `context: "definition"` for token-efficient single symbol inspection._\n\n## Intelligence Options\n\n- **`shadow_search_path` with `ranked: true`**: Results sorted by gravity (high-import files first) with layer classification (Entry/Logic/Data). Use when you need to find the most architecturally important files matching a pattern.\n- **`shadow_search_concept` with `compact: true`**: Omits code snippets for ~60% token savings. Use for broad exploration before deep dives.\n- **Briefing altitude levels**: Use `orbit` for quick status, `atmosphere` for strategy + crystals, `ground` for raw logs + collisions.\n- **`shadow_ops_crystallize`**: If a mission has excessive raw logs, crystallize them first for leaner briefings.\n',shadow_workspace:`---
|
|
1397
|
-
name: workspace
|
|
1398
|
-
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.
|
|
1380
|
+
## Closeout
|
|
1381
|
+
|
|
1382
|
+
- \`shadow_ops_log({ repoPath, missionId?, type: "discovery", content, symbolName?, filePath? })\`
|
|
1383
|
+
- \`shadow_ops_handoff({ repoPath, missionId?, kind: "impact_map", findings, risks?, gaps? })\`
|
|
1384
|
+
|
|
1385
|
+
## Rules
|
|
1386
|
+
|
|
1387
|
+
- Keep \`depth: 3\` by default; only widen for foundational primitives.
|
|
1388
|
+
- \`shadow_analyze_mesh\` requires a concrete \`topic\`.
|
|
1389
|
+
`,shadow_understand:`---
|
|
1390
|
+
name: understand
|
|
1391
|
+
description: Find the high-signal path to understanding complex logic through intent retrieval, topological placement, relational analysis, and mechanics inspection. Use when understanding architecture, analyzing complex code, tracing logic flow, or when the user asks about how something works, architectural patterns, or code comprehension.
|
|
1399
1392
|
---
|
|
1400
1393
|
|
|
1401
|
-
#
|
|
1394
|
+
# Understand
|
|
1395
|
+
|
|
1396
|
+
Use this skill to build the shortest reliable path from "what is this?" to "I can explain or change it."
|
|
1402
1397
|
|
|
1403
|
-
|
|
1398
|
+
## Start broad
|
|
1404
1399
|
|
|
1405
|
-
|
|
1400
|
+
1. \`shadow_ops_context({ repoPath, compact: true })\`
|
|
1401
|
+
2. Expand only as needed:
|
|
1402
|
+
- \`shadow_recon_tree({ repoPath, subPath?, maxDepth? })\`
|
|
1403
|
+
- \`shadow_recon_topography({ repoPath })\`
|
|
1404
|
+
- \`shadow_ops_briefing({ repoPath, scope: "mission", missionId, altitude: "ground" })\`
|
|
1406
1405
|
|
|
1407
|
-
|
|
1408
|
-
2. **Federated Search**: \`shadow_workspace_fuse\` (repoPath, repoPaths).
|
|
1409
|
-
3. **Link Missions**: \`shadow_workspace_link\` (parentRepoPath, parentMissionId, childRepoPath, childMissionId, relationship, repoPath).
|
|
1410
|
-
4. **Verify Graph**: \`shadow_ops_graph\` (missionId, depth, repoPath).
|
|
1406
|
+
## Relational analysis
|
|
1411
1407
|
|
|
1412
|
-
|
|
1408
|
+
- \`shadow_search_concept({ repoPath, query, compact: true })\`
|
|
1409
|
+
- \`shadow_search_symbol({ repoPath, query, matchMode? })\`
|
|
1410
|
+
- \`shadow_analyze_impact({ repoPath, symbolName, filePath?, depth: 3 })\`
|
|
1411
|
+
- \`shadow_analyze_deps({ repoPath, filePath, direction: "imported_by" })\`
|
|
1412
|
+
- \`shadow_analyze_type_graph({ repoPath, symbolName, filePath?, direction?, relationship? })\`
|
|
1413
|
+
- \`shadow_analyze_mesh({ repoPath, topic, type? })\` when you have a concrete route or event fragment
|
|
1413
1414
|
|
|
1414
|
-
|
|
1415
|
-
| :------------ | :---------------------- | :----------------------------------------------- |
|
|
1416
|
-
| **List** | \`shadow_workspace_list\` | \`{ repoPath, repoPaths: [...] }\` |
|
|
1417
|
-
| **Fuse** | \`shadow_workspace_fuse\` | \`{ repoPath, repoPaths: [...] }\` |
|
|
1418
|
-
| **Link** | \`shadow_workspace_link\` | \`{ parentMissionId: 1, childMissionId: 2, ... }\` |
|
|
1419
|
-
| **Visualize** | \`shadow_ops_graph\` | \`{ missionId: 1, depth: 3, repoPath }\` |
|
|
1415
|
+
## Mechanics
|
|
1420
1416
|
|
|
1421
|
-
|
|
1417
|
+
- \`shadow_inspect_file({ repoPath, filePath, detailLevel: "signatures" })\`
|
|
1418
|
+
- \`shadow_inspect_symbol({ repoPath, symbolName, filePath?, context: "definition" | "full" })\`
|
|
1419
|
+
- \`shadow_analyze_flow({ repoPath, filePath, symbolName? })\`
|
|
1420
|
+
- \`shadow_analyze_explain_diff({ repoPath, baseCommit?, headCommit?, staged? })\`
|
|
1422
1421
|
|
|
1423
|
-
##
|
|
1422
|
+
## Closeout
|
|
1424
1423
|
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1424
|
+
- \`shadow_ops_log({ repoPath, missionId?, type: "discovery", content, symbolName?, filePath? })\`
|
|
1425
|
+
|
|
1426
|
+
## Rules
|
|
1427
|
+
|
|
1428
|
+
- Start broad and narrow down; do not jump straight to full-symbol inspection unless you already know the target.
|
|
1429
|
+
- \`shadow_analyze_type_graph\` requires \`symbolName\`.
|
|
1430
|
+
- \`shadow_analyze_mesh\` requires \`topic\`.
|
|
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(`
|
|
1429
1434
|
`)?s:`${s}
|
|
1430
1435
|
`}
|
|
1431
1436
|
${t}
|
|
@@ -1434,4 +1439,367 @@ ${t}
|
|
|
1434
1439
|
`).replace(/\n{3,}/g,`
|
|
1435
1440
|
|
|
1436
1441
|
`).trimEnd()}
|
|
1437
|
-
`}async function el(s=!1,e=!1,t=mr,n=[]){_e.intro("\u{1F311} Liquid Shadow: Tactical Onboarding");let i=om.homedir(),r=0,o=cm(t),a=Array.isArray(n)?n:[],c=e||await _e.confirm({message:"Deploy Autonomous Reasoning Skills? (Injects /onboard, /understand, etc.)",initialValue:!0});if(_e.isCancel(c)){_e.outro("Onboarding aborted.");return}let l=e||await _e.confirm({message:"Connect to MCP Reasoning Engines? (Claude Code, Claude Desktop, Gemini CLI, Codex)",initialValue:!0});if(_e.isCancel(l)){_e.outro("Onboarding aborted.");return}if(!c&&!l){_e.outro("No actions selected. Operational state unchanged.");return}let p=_e.spinner();p.start("Establishing intelligence assets..."),c&&(r=dr(!0)),l&&(dm(i,o,a,!0),mm(i,o,a,!0)),p.stop("Intelligence layer established."),r>0?_e.note(`Successfully deployed ${r} tactical skills.`,"Manifest"):_e.note("No new skills deployed (up to date or scope skipped).","Manifest"),_e.outro("\u{1F311} Liquid Shadow is operational.")}function dm(s,e,t,n){let i=[{name:"Claude Code",path:mn.join(s,".claude.json"),extraFields:{type:"stdio"},createIfMissing:!1},{name:"Claude Desktop",path:mn.join(s,"Library","Application Support","Claude","claude_desktop_config.json"),createIfMissing:!1},{name:"Gemini CLI",path:mn.join(s,".gemini","settings.json"),createIfMissing:!0},{name:"Antigravity IDE",path:mn.join(s,".gemini","antigravity","mcp_config.json"),createIfMissing:!1}];for(let r of i){if(!At.existsSync(r.path))if(r.createIfMissing)At.mkdirSync(mn.dirname(r.path),{recursive:!0}),At.writeFileSync(r.path,"{}");else{ft.debug(`${r.name} config not found at ${r.path}, skipping.`);continue}try{let o=JSON.parse(At.readFileSync(r.path,"utf8"));if(o.mcpServers||(o.mcpServers={}),o.mcpServers[Vt]){if(!n){ft.info(`${r.name}: ${Vt} already configured.`);continue}ft.info(`${r.name}: updating existing ${Vt} configuration.`)}o.mcpServers[Vt]={command:e,args:t,env:{},...r.extraFields??{}},At.writeFileSync(r.path,JSON.stringify(o,null,2)),ft.info(`Updated ${r.name} config at ${r.path}`)}catch(o){ft.error(`Failed to update ${r.name} config at ${r.path}: ${o}`)}}}function mm(s,e,t,n){let i=mn.join(s,".codex","config.toml");if(!At.existsSync(i)){ft.debug(`Codex config not found at ${i}, skipping.`);return}try{let r=At.readFileSync(i,"utf8"),o=`[mcp_servers.${Vt}]`,a=pm(e,t);if(r.includes(o)&&!n){ft.info(`Codex: ${Vt} already configured.`);return}let c=um(r,o,a);At.writeFileSync(i,c),ft.info(`Updated Codex config at ${i}`)}catch(r){ft.error(`Failed to update Codex config at ${i}: ${r}`)}}Nt();import{readFileSync as hm}from"node:fs";var hn={name:"@precisionutilityguild/liquid-shadow",version:"0.0.0",license:"UNLICENSED",description:"Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem"};function tl(){let s=JSON.parse(hm(Le("package.json"),"utf8"));return{name:typeof s.name=="string"&&s.name.trim().length>0?s.name:hn.name,version:typeof s.version=="string"&&s.version.trim().length>0?s.version:hn.version,license:typeof s.license=="string"&&s.license.trim().length>0?s.license:hn.license,description:typeof s.description=="string"&&s.description.trim().length>0?s.description:hn.description}}function ke(s){let e=process.cwd();return ls(e,s.flags)}process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),ne().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),ne().then(()=>process.exit(1))});var hr=hn;try{hr=tl()}catch(s){console.error("Failed to parse package.json, using defaults",s)}var le=fm().name("liquid-shadow").version(hr.version).description(hr.description).scriptName("liquid-shadow");le.command("index","Index the repository for AI analysis",{parameters:["[dir]"],flags:{output:{type:String,alias:"o",description:"Export to JSON file instead of indexing"},level:{type:String,alias:"l",description:"Detail level",default:"detailed"},subPath:{type:String,description:"Only process files within this subpath"},force:{type:Boolean,description:"Force re-indexing of all files",default:!1},deep:{type:Boolean,description:"Perform deep semantic indexing (headings + symbol embeddings)",default:!0}}}).on("index",async s=>{let e=ke(s),t={...s.flags,dir:s.flags.dir??e.dir,level:s.flags.level??e.level,deep:s.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await Na(s.parameters.dir||e.dir,t)});le.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=ke(s);await ao(s.parameters.dir||e.dir)});le.command("dashboard","Operational intelligence dashboard (TUI)",{parameters:["[dir]"]}).on("dashboard",async s=>{let e=ke(s);await vs(s.parameters.dir||e.dir)});le.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=ke(s);await go(s.parameters.dir||e.dir)});le.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=ke(s);await Oa(s.parameters.dir||e.dir)});le.command("tree","Visualize repository structure as a tree",{parameters:["[dir]"],flags:{subPath:{type:String,description:"Subpath to visualize"},depth:{type:String,alias:"d",description:"Max depth",default:"3"}}}).on("tree",async s=>{let e=ke(s);await Aa(s.parameters.dir||e.dir,{...s.flags,dir:s.flags.dir??e.dir})});le.command("recon","Repository reconnaissance and architecture analysis",{parameters:["<mode>","[dir]"],flags:{subPath:{type:String,description:"Subpath to focus on"}}}).on("recon",async s=>{let e=ke(s);await Xa(s.parameters.mode,s.parameters.dir||e.dir,{...s.flags})});le.command("trace","Trace execution flow for a given file/symbol",{parameters:["<file>","[symbolName]"],flags:{dir:{type:String,alias:"d",default:"."}}}).on("trace",async s=>{let e=ke(s);await qa(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});le.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"],flags:{contextPivot:{type:Boolean,default:!1,description:"Opt in to suspend other-branch missions and resume current-branch missions"},mergeSentinel:{type:Boolean,default:!1,description:"Opt in to auto-complete missions from merged branches"}}}).on("sync",async s=>{let e=ke(s);await Ka(s.parameters.dir||e.dir,{contextPivot:!!s.flags.contextPivot,mergeSentinel:!!s.flags.mergeSentinel})});le.command("search-config","Search for configuration values",{parameters:["[key]"],flags:{dir:{type:String,alias:"d",default:"."},kind:{type:String,description:"Filter by config kind"}}}).on("search-config",async s=>{let e=ke(s);await uc(s.parameters.key,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-concept","Search for files by concept/intent (Semantic)",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-concept",async s=>{let e=ke(s);await cc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-symbol","Search for specific code symbols",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-symbol",async s=>{let e=ke(s);await lc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("search-fuzzy",'Fuzzy search for symbols (e.g., "usc" finds "UserServiceClient")',{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-fuzzy",async s=>{let e=ke(s);await pc(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});le.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async s=>{await dc([s.parameters.action,s.parameters.path])});le.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async s=>{await xc([s.parameters.action,...s.parameters.args])});le.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async s=>{await jc([s.parameters.action,...s.parameters.args])});le.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async s=>{await Gc([s.parameters.mode,...s.parameters.args])});le.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=ke(s);await Jc(s.parameters.dir||e.dir)});le.command("chronicle","Generate a repository-wide narrative feed (ADRs/Epics)",{parameters:["[dir]"],flags:{format:{type:String,alias:"f",description:"Output format (markdown|json)",default:"markdown"},limit:{type:Number,alias:"l",description:"Limit number of entries",default:10},offset:{type:Number,description:"Pagination offset",default:0},since:{type:String,description:"Show entries since date (YYYY-MM-DD)"},until:{type:String,description:"Show entries until date (YYYY-MM-DD)"}}}).on("chronicle",async s=>{let e=ke(s);await Yc(s.parameters.dir||e.dir,{...s.flags,format:s.flags.format,limit:s.flags.limit?parseInt(String(s.flags.limit),10):void 0,offset:s.flags.offset?parseInt(String(s.flags.offset),10):void 0,since:s.flags.since?Math.floor(new Date(String(s.flags.since)).getTime()/1e3):void 0,until:s.flags.until?Math.floor(new Date(String(s.flags.until)).getTime()/1e3):void 0})});le.command("init","Initialize Liquid Shadow skills and configuration",{flags:{force:{type:Boolean,alias:"f",description:"Force overwrite existing skills and MCP server entries",default:!1},yes:{type:Boolean,alias:"y",description:"Skip interactive confirmation (unsafe)",default:!1},mcpCommand:{type:String,description:"Override MCP command used in generated client configs",default:"liquid-shadow-mcp"},mcpArgs:{type:String,description:'Optional MCP args (JSON array recommended, e.g. ["--flag","value"] or quoted string)'}}}).on("init",async s=>{let e;try{e=Xc(s.flags.mcpArgs)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Invalid --mcp-args: ${n}`),process.exit(1);return}await el(s.flags.force,s.flags.yes,s.flags.mcpCommand,e)});le.command("skills","Manage Liquid Shadow reasoning skills",{parameters:["<action>"]}).on("skills",async s=>{let e=s.parameters.action;e==="update"?await Qc():(console.error(`Unknown skills action: ${e}. Available: update`),process.exit(1))});le.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async s=>{await Vc(s.parameters.shell||"")});if(process.argv.length<=2){let s=ls(process.cwd(),{});vs(s.dir)}else le.parse();
|
|
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
|
+
|
|
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)
|
|
1640
|
+
|
|
1641
|
+
Showing ${E.length} of ${u} file(s) (offset: ${n}, limit: ${t})${N}
|
|
1642
|
+
|
|
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
|
+
`)+`
|
|
1645
|
+
|
|
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}"
|
|
1648
|
+
|
|
1649
|
+
Showing ${f.length} of ${u} file(s) (offset: ${n}, limit: ${t})${y}
|
|
1650
|
+
|
|
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}"
|
|
1657
|
+
|
|
1658
|
+
Showing ${x.length} of ${A} file(s) above the ${Math.round(u*100)}% evidence floor (offset: ${n}, limit: ${t})${I}${N}${P}${C}
|
|
1659
|
+
|
|
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}
|
|
1663
|
+
|
|
1664
|
+
`+(O.snippet?`**Matched Snippet**:
|
|
1665
|
+
\`\`\`typescript
|
|
1666
|
+
${O.snippet}
|
|
1667
|
+
\`\`\`
|
|
1668
|
+
|
|
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();
|