@precisionutilityguild/liquid-shadow 1.0.0
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/LICENSE +184 -0
- package/README.md +194 -0
- package/dist/data/migrations/001_initial_schema.sql +79 -0
- package/dist/data/migrations/002_fts_indexes.sql +94 -0
- package/dist/data/migrations/003_mission_system.sql +86 -0
- package/dist/data/migrations/004_event_mesh.sql +17 -0
- package/dist/data/migrations/005_index_metadata.sql +15 -0
- package/dist/data/migrations/006_search_history.sql +17 -0
- package/dist/data/migrations/007_hologram_snapshot.sql +14 -0
- package/dist/entry/cli/index.js +822 -0
- package/dist/entry/mcp/server.js +894 -0
- package/dist/index.js +453 -0
- package/dist/logic/domain/embeddings/worker.js +1 -0
- package/package.json +100 -0
- package/skills/audit/SKILL.md +29 -0
- package/skills/chronicle/SKILL.md +33 -0
- package/skills/continue/SKILL.md +44 -0
- package/skills/mission/SKILL.md +35 -0
- package/skills/onboard/SKILL.md +27 -0
- package/skills/understand/SKILL.md +35 -0
- package/skills/workspace/SKILL.md +25 -0
|
@@ -0,0 +1,822 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var Po=Object.create;var Jn=Object.defineProperty;var Do=Object.getOwnPropertyDescriptor;var Oo=Object.getOwnPropertyNames;var Fo=Object.getPrototypeOf,Ho=Object.prototype.hasOwnProperty;var Wo=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var V=(s,e)=>()=>(s&&(e=s(s=0)),e);var Uo=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ai=(s,e)=>{for(var t in e)Jn(s,t,{get:e[t],enumerable:!0})},jo=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oo(e))!Ho.call(s,i)&&i!==t&&Jn(s,i,{get:()=>e[i],enumerable:!(n=Do(e,i))||n.enumerable});return s};var Bo=(s,e,t)=>(t=s!=null?Po(Fo(s)):{},jo(e||!s||!s.__esModule?Jn(t,"default",{value:s,enumerable:!0}):t,s));import zo from"pino";var Go,qo,_,N=V(()=>{"use strict";Go={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},qo=zo({level:process.env.LOG_LEVEL||"info",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:Go[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),_=qo});import St from"fs";import Yn from"path";import{fileURLToPath as Vo}from"url";function Xo(s){s.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
4
|
+
version INTEGER PRIMARY KEY,
|
|
5
|
+
name TEXT NOT NULL,
|
|
6
|
+
applied_at REAL DEFAULT (unixepoch())
|
|
7
|
+
);
|
|
8
|
+
`)}function Zo(s){Xo(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function ea(){let s=Ko;if(!St.readdirSync(s).some(r=>r.match(/^\d{3}_.*\.sql$/))){let r=Yn.resolve(s,"../../data/migrations");St.existsSync(r)&&St.readdirSync(r).some(l=>l.match(/^\d{3}_.*\.sql$/))&&(s=r)}let n=St.readdirSync(s).filter(r=>r.match(/^\d{3}_.*\.sql$/)).sort(),i=[];for(let r of n){let o=r.match(/^(\d{3})_(.+)\.sql$/);if(!o)continue;let l=parseInt(o[1],10),c=o[2],p=St.readFileSync(Yn.join(s,r),"utf-8").split(/^-- DOWN$/m),d=p[0].trim(),u=p[1]?.trim();i.push({version:l,name:c,up:d,down:u})}return i}function ta(s,e){_t.info({version:e.version,name:e.name},"Applying migration"),s.transaction(()=>{s.exec(e.up),s.prepare("INSERT INTO schema_migrations (version, name) VALUES (?, ?)").run(e.version,e.name)})(),_t.info({version:e.version},"Migration applied successfully")}function Fi(s){let e=Zo(s),n=ea().filter(i=>!e.has(i.version));if(n.length===0){_t.debug("No pending migrations");return}_t.info({count:n.length},"Running pending migrations");for(let i of n)ta(s,i);_t.info("All migrations complete")}var _t,Qo,Ko,Hi=V(()=>{"use strict";N();_t=_.child({module:"migrations"}),Qo=Vo(import.meta.url),Ko=Yn.dirname(Qo)});import na from"better-sqlite3";import Bt from"path";import Vn from"fs";import Wi from"crypto";import ia from"os";function Gt(s){let e=ia.homedir(),t=Bt.join(e,".mcp-liquid-shadow"),n=Bt.join(t,"dbs");Vn.existsSync(n)||Vn.mkdirSync(n,{recursive:!0});let i=Wi.createHash("sha256").update(s).digest("hex").substring(0,12),o=`${Bt.basename(s).replace(/[^a-zA-Z0-9-_]/g,"_")}_${i}.db`;return Bt.join(n,o)}function sa(s,e){let t=e||Gt(s);Ie.info({repoPath:s,dbPath:t},"Initializing database");let n=new na(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),Fi(n),zt.set(s,t),Me.set(t,n),Ie.info({repoPath:s,dbPath:t},"Database initialized successfully"),n}function Qn(s){return Wi.createHash("sha256").update(s,"utf8").digest("hex")}function Ui(s,e){return e?Qn(s)!==e:!0}function ke(s){let e=zt.get(s)||Gt(s),t=Me.get(e);if(t){if(t.open)return t;Me.delete(e)}let n=sa(s);return Me.set(e,n),n}function Ye(s){let e=Gt(s);if(!Vn.existsSync(e))return!1;try{let t=ke(s);return t.prepare(`
|
|
9
|
+
SELECT value FROM index_metadata
|
|
10
|
+
WHERE key = 'index_completed'
|
|
11
|
+
`).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return Ie.debug({repoPath:s,error:t},"Error checking index status"),!1}}function Kn(s,e){let t=ke(s);t.prepare(`
|
|
12
|
+
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
13
|
+
VALUES ('index_completed', 'true', unixepoch())
|
|
14
|
+
`).run(),t.prepare(`
|
|
15
|
+
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
16
|
+
VALUES ('last_indexed_at', ?, unixepoch())
|
|
17
|
+
`).run(Date.now().toString()),e&&t.prepare(`
|
|
18
|
+
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
19
|
+
VALUES ('last_indexed_commit', ?, unixepoch())
|
|
20
|
+
`).run(e),Ie.info({repoPath:s,commitSha:e},"Repository marked as indexed")}function xt(s){try{return ke(s).prepare(`
|
|
21
|
+
SELECT value FROM index_metadata
|
|
22
|
+
WHERE key = 'last_indexed_commit'
|
|
23
|
+
`).get()?.value||null}catch(e){return Ie.debug({repoPath:s,error:e},"Error getting last indexed commit"),null}}function qt(s){let e=zt.get(s)||Gt(s),t=Me.get(e);t&&(t.open&&(Ie.info({repoPath:s,dbPath:e},"Closing database connection"),t.close()),Me.delete(e)),zt.delete(s)}function ji(){for(let[s,e]of Me.entries())try{e.open&&(Ie.info({dbPath:s},"Closing database connection"),e.close())}catch(t){Ie.error({dbPath:s,err:t},"Error closing database execution")}Me.clear()}var Ie,Me,zt,Bi,Ve=V(()=>{"use strict";N();Hi();Ie=_.child({module:"db"});Me=new Map,zt=new Map;process.on("exit",()=>ji());Bi=s=>{Ie.info({signal:s},"Received termination signal, closing databases"),ji(),process.exit(0)};process.on("SIGINT",()=>Bi("SIGINT"));process.on("SIGTERM",()=>Bi("SIGTERM"))});var K,be=V(()=>{"use strict";K=class{db;constructor(e){this.db=e}get database(){return this.db}all(e,...t){return this.db.prepare(e).all(...t)}get(e,...t){return this.db.prepare(e).get(...t)}run(e,...t){return this.db.prepare(e).run(...t).changes}insert(e,...t){return this.db.prepare(e).run(...t).lastInsertRowid}transaction(e){return this.db.transaction(e)()}}});import ra from"path";var Jt,zi=V(()=>{"use strict";be();Jt=class extends K{findByPath(e){return this.get("SELECT * FROM files WHERE path = ?",e)}findAll(e){let t="SELECT * FROM files ORDER BY path ASC";return e&&(t+=` LIMIT ${e}`),this.all(t)}getAllPaths(){return this.all("SELECT path FROM files").map(t=>t.path)}findInSubPath(e,t){let n=ra.resolve(e,t),i=n.endsWith("/")?n:n+"/";return this.all(`
|
|
24
|
+
SELECT * FROM files
|
|
25
|
+
WHERE (path LIKE ? OR path = ?)
|
|
26
|
+
ORDER BY path ASC
|
|
27
|
+
`,`${i}%`,n)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
|
|
28
|
+
SELECT files.*, files_fts.rank
|
|
29
|
+
FROM files_fts
|
|
30
|
+
JOIN files ON files.rowid = files_fts.rowid
|
|
31
|
+
WHERE files_fts MATCH ?
|
|
32
|
+
ORDER BY rank
|
|
33
|
+
LIMIT ?
|
|
34
|
+
`,e,t)}findByPathKeywords(e,t=10){let n=e.map(()=>"LOWER(path) LIKE ?").join(" OR ");return this.all(`
|
|
35
|
+
SELECT * FROM files
|
|
36
|
+
WHERE ${n}
|
|
37
|
+
LIMIT ?
|
|
38
|
+
`,...e.map(i=>`%${i}%`),t)}getContent(e){return this.get("SELECT content FROM file_content WHERE file_path = ?",e)?.content}findContentByToken(e,t=10){return this.all(`
|
|
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 a of o){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let p=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.file_path].score+=p;let d=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.file_path].reasons.push(`${d}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
|
|
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
|
+
`,l);for(let a of c){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let p=a.mission_id?e.includes(a.mission_id):!1,d=p?.1:.2;n[a.file_path].score<5&&(n[a.file_path].score+=d);let u=p?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.file_path].reasons.includes(u)&&n[a.file_path].reasons.length<5&&n[a.file_path].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
|
|
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 = ?"),l=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),a=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),p=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),u=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),h=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),b=this.db.prepare(`
|
|
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(g=>{for(let y of g){let{meta:S,exports:w,imports:C,configs:T,events:I,content:x,classification:$,summary:R,embedding:v}=y;r.run(S.path),o.run(S.path),l.run(S.path),c.run(S.path),a.run(S.path);let P=x?n(x):null;if(b.run(S.path,S.mtime,Date.now(),$||"Unknown",R||"",v?JSON.stringify(v):null,P),w){let L=(H,B,ne)=>{for(let W of B){let D=W.embedding?JSON.stringify(W.embedding):null,M=p.run(H,W.name,W.kind,W.signature,W.doc||"",W.line,W.endLine||W.line,W.classification||"Other",W.capabilities||"[]",ne,D);W.members&&W.members.length>0&&L(H,W.members,M.lastInsertRowid)}};L(S.path,w,null)}if(C)for(let L of C){let H=i(L.module,S.path,t);d.run(S.path,L.module,L.name,H)}if(T)for(let L of T)u.run(S.path,L.key,L.value,L.kind);if(x!==void 0&&m.run(S.path,x),I)for(let L of I)h.run(S.path,L.type,L.name,L.direction,L.line,L.snippet)}})(e)}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}}});var Yt,Gi=V(()=>{"use strict";be();Yt=class extends K{findByNameAndFile(e,t){return this.all("SELECT * FROM exports WHERE file_path = ? AND name = ?",t,e)}findByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ?",e)}findAtLine(e,t){return this.get(`
|
|
101
|
+
SELECT * FROM exports
|
|
102
|
+
WHERE file_path = ? AND start_line <= ? AND end_line >= ?
|
|
103
|
+
ORDER BY (end_line - start_line) ASC -- Get innermost symbol
|
|
104
|
+
LIMIT 1
|
|
105
|
+
`,e,t,t)}findById(e){return this.get("SELECT * FROM exports WHERE id = ?",e)}findHydratedById(e){let t=this.findById(e);if(!t)return;let n=this.all(`
|
|
106
|
+
SELECT id, mission_id, type, content, created_at, confidence
|
|
107
|
+
FROM intent_logs
|
|
108
|
+
WHERE symbol_id = ?
|
|
109
|
+
ORDER BY created_at DESC
|
|
110
|
+
LIMIT 5
|
|
111
|
+
`,e),r=this.get("SELECT COUNT(*) as count FROM intent_logs WHERE symbol_id = ?",e)?.count||0,o=this.all(`
|
|
112
|
+
SELECT m.id, m.name, m.status
|
|
113
|
+
FROM missions m
|
|
114
|
+
JOIN working_set ws ON ws.mission_id = m.id
|
|
115
|
+
WHERE ws.symbol_id = ?
|
|
116
|
+
AND m.status IN ('in-progress', 'planned', 'verifying')
|
|
117
|
+
GROUP BY m.id
|
|
118
|
+
`,e);return{...t,recent_intents:n,intent_log_count:r,active_missions:o}}findRoutesByCapability(e){return this.all(`
|
|
119
|
+
SELECT name, file_path, signature
|
|
120
|
+
FROM exports
|
|
121
|
+
WHERE kind = 'HTTP Route'
|
|
122
|
+
AND capabilities LIKE ?
|
|
123
|
+
`,`%${e}%`)}findRoutesByToken(e,t=5){return this.all(`
|
|
124
|
+
SELECT *
|
|
125
|
+
FROM exports
|
|
126
|
+
WHERE (kind = 'HTTP Route' OR classification = 'Service Boundary')
|
|
127
|
+
AND (name LIKE ? OR signature LIKE ?)
|
|
128
|
+
LIMIT ?
|
|
129
|
+
`,`%${e}%`,`%${e}%`,t)}findByFile(e){return this.all("SELECT * FROM exports WHERE file_path = ? ORDER BY start_line ASC",e)}findByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM exports WHERE file_path IN (${t}) ORDER BY file_path, start_line ASC`,...e)}findSiblings(e){return this.all(`
|
|
130
|
+
SELECT name, kind, signature, start_line, end_line,
|
|
131
|
+
parent_id, id,
|
|
132
|
+
(SELECT name FROM exports WHERE id = e.parent_id) as parent_name
|
|
133
|
+
FROM exports e
|
|
134
|
+
WHERE file_path = ?
|
|
135
|
+
AND parent_id IS NULL
|
|
136
|
+
ORDER BY start_line ASC
|
|
137
|
+
`,e)}findByName(e,t=20){return this.all("SELECT * FROM exports WHERE name = ? LIMIT ?",e,t)}findClassByName(e){return this.get("SELECT * FROM exports WHERE name = ? AND kind = 'ClassDeclaration' LIMIT 1",e)}findDefinitionCandidates(e,t){let n=[e],i=`
|
|
138
|
+
SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
|
|
139
|
+
f.path as file_path, e.classification, e.capabilities,
|
|
140
|
+
p.name as parent_name, p.kind as parent_kind
|
|
141
|
+
FROM exports e
|
|
142
|
+
JOIN files f ON e.file_path = f.path
|
|
143
|
+
LEFT JOIN exports p ON e.parent_id = p.id
|
|
144
|
+
WHERE e.name = ?
|
|
145
|
+
`;return t&&(i+=" AND f.path = ?",n.push(t)),i+=`
|
|
146
|
+
ORDER BY
|
|
147
|
+
CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
|
|
148
|
+
CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
|
|
149
|
+
LIMIT 10
|
|
150
|
+
`,this.all(i,...n)}findMemberCandidates(e,t,n){let i=[e,t],r=`
|
|
151
|
+
SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
|
|
152
|
+
f.path as file_path, e.classification, e.capabilities,
|
|
153
|
+
p.name as parent_name, p.kind as parent_kind
|
|
154
|
+
FROM exports e
|
|
155
|
+
JOIN files f ON e.file_path = f.path
|
|
156
|
+
LEFT JOIN exports p ON e.parent_id = p.id
|
|
157
|
+
WHERE p.name = ? AND e.name = ?
|
|
158
|
+
`;return n&&(r+=" AND f.path = ?",i.push(n)),r+=`
|
|
159
|
+
ORDER BY
|
|
160
|
+
CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
|
|
161
|
+
CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
|
|
162
|
+
LIMIT 10
|
|
163
|
+
`,this.all(r,...i)}findPotentialParents(e){return this.all(`
|
|
164
|
+
SELECT name, kind, file_path
|
|
165
|
+
FROM exports
|
|
166
|
+
WHERE kind IN ('ClassDeclaration', 'ClassExpression', 'TsInterfaceDeclaration')
|
|
167
|
+
AND id IN (
|
|
168
|
+
SELECT rowid FROM content_fts WHERE content MATCH ?
|
|
169
|
+
)
|
|
170
|
+
LIMIT 3
|
|
171
|
+
`,`"${e}"`)}findFuzzyCandidates(e){let t=e.charAt(0).toLowerCase();return this.all(`
|
|
172
|
+
SELECT DISTINCT name FROM exports
|
|
173
|
+
WHERE parent_id IS NULL
|
|
174
|
+
AND (name LIKE ? OR name LIKE ? OR ABS(LENGTH(name) - LENGTH(?)) <= 5)
|
|
175
|
+
ORDER BY ABS(LENGTH(name) - LENGTH(?)) ASC
|
|
176
|
+
LIMIT 1000
|
|
177
|
+
`,t+"%","%"+t+"%",e,e)}findTopLevelByFile(e){return this.all(`
|
|
178
|
+
SELECT * FROM exports
|
|
179
|
+
WHERE file_path = ? AND parent_id IS NULL
|
|
180
|
+
ORDER BY start_line ASC
|
|
181
|
+
`,e)}findFts(e,t=20){return this.all(`
|
|
182
|
+
SELECT e.*
|
|
183
|
+
FROM exports e
|
|
184
|
+
JOIN exports_fts ef ON e.id = ef.rowid
|
|
185
|
+
WHERE ef MATCH ?
|
|
186
|
+
LIMIT ?
|
|
187
|
+
`,e,t)}findByPartialName(e,t=20){return this.all(`
|
|
188
|
+
SELECT * FROM exports
|
|
189
|
+
WHERE lower(name) LIKE ?
|
|
190
|
+
LIMIT ?
|
|
191
|
+
`,`%${e.toLowerCase()}%`,t)}getAllNames(e=5e3){return this.all("SELECT DISTINCT name FROM exports WHERE parent_id IS NULL LIMIT ?",e).map(n=>n.name)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM exports WHERE file_path = ?",e)?.count||0}findDeadExports(e=50,t=!1){let n=t?"":"AND e.file_path NOT LIKE '%/test/%' AND e.file_path NOT LIKE '%/__tests__/%' AND e.file_path NOT LIKE '%.spec.%' AND e.file_path NOT LIKE '%.test.%'";return this.all(`
|
|
192
|
+
SELECT e.name, e.kind, e.file_path, e.start_line
|
|
193
|
+
FROM exports e
|
|
194
|
+
WHERE e.kind IN (
|
|
195
|
+
'FunctionDeclaration', 'ClassDeclaration',
|
|
196
|
+
'TsInterfaceDeclaration', 'TsTypeAliasDeclaration', 'TsEnumDeclaration',
|
|
197
|
+
'ArrowFunctionExpression', 'FunctionExpression'
|
|
198
|
+
)
|
|
199
|
+
AND e.parent_id IS NULL
|
|
200
|
+
${n}
|
|
201
|
+
AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.imported_symbols LIKE '%' || e.name || '%')
|
|
202
|
+
AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
|
|
203
|
+
ORDER BY e.file_path, e.start_line
|
|
204
|
+
LIMIT ?
|
|
205
|
+
`,e)}getGravityMap(e=[],t){let n={},i=`
|
|
206
|
+
SELECT ws.symbol_id, m.name as mission_name, m.status
|
|
207
|
+
FROM working_set ws
|
|
208
|
+
JOIN missions m ON ws.mission_id = m.id
|
|
209
|
+
WHERE (
|
|
210
|
+
(m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
|
|
211
|
+
OR m.id IN (${e.length>0?e.join(","):"-1"})
|
|
212
|
+
)
|
|
213
|
+
AND ws.symbol_id IS NOT NULL
|
|
214
|
+
`,r=[];t&&r.push(t);let o=this.all(i,...r);for(let a of o){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let p=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.symbol_id].score+=p;let d=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.symbol_id].reasons.push(`${d}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
|
|
215
|
+
SELECT symbol_id, type, mission_id
|
|
216
|
+
FROM intent_logs
|
|
217
|
+
WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
|
|
218
|
+
AND symbol_id IS NOT NULL
|
|
219
|
+
ORDER BY created_at DESC
|
|
220
|
+
LIMIT 200
|
|
221
|
+
`,l);for(let a of c){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let p=a.mission_id?e.includes(a.mission_id):!1,d=p?.1:.2;n[a.symbol_id].score<5&&(n[a.symbol_id].score+=d);let u=p?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.symbol_id].reasons.includes(u)&&n[a.symbol_id].reasons.length<5&&n[a.symbol_id].reasons.push(u)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
|
|
222
|
+
SELECT kind, COUNT(*) as c
|
|
223
|
+
FROM exports
|
|
224
|
+
WHERE kind IS NOT NULL AND kind != ''
|
|
225
|
+
GROUP BY kind
|
|
226
|
+
ORDER BY c DESC
|
|
227
|
+
LIMIT ?
|
|
228
|
+
`,e)}getWithEmbeddingsCount(){return this.get("SELECT COUNT(*) as count FROM exports WHERE embedding IS NOT NULL")?.count||0}findByMethodName(e){return this.all(`
|
|
229
|
+
SELECT * FROM exports
|
|
230
|
+
WHERE name = ?
|
|
231
|
+
OR name LIKE ?
|
|
232
|
+
OR name LIKE ?
|
|
233
|
+
LIMIT 10
|
|
234
|
+
`,e,`%.${e}`,`%::${e}`)}}});var qi,Ji=V(()=>{"use strict";qi=`
|
|
235
|
+
WITH RECURSIVE dependency_chain AS (
|
|
236
|
+
-- Base case: Direct dependents of the target symbol
|
|
237
|
+
-- Meaning: Files that import the file where the symbol is defined
|
|
238
|
+
SELECT
|
|
239
|
+
i.file_path as consumer_path,
|
|
240
|
+
i.module_specifier,
|
|
241
|
+
i.imported_symbols,
|
|
242
|
+
f.path as source_path,
|
|
243
|
+
1 as depth,
|
|
244
|
+
i.file_path || '<-' || f.path as path_chain
|
|
245
|
+
FROM imports i
|
|
246
|
+
JOIN files f ON i.resolved_path = f.path
|
|
247
|
+
WHERE f.path = ? -- The file where our changed symbol lives
|
|
248
|
+
AND (
|
|
249
|
+
-- Exact symbol match or wildcard import
|
|
250
|
+
i.imported_symbols LIKE ?
|
|
251
|
+
OR i.imported_symbols = '*'
|
|
252
|
+
OR i.imported_symbols = 'default'
|
|
253
|
+
OR i.imported_symbols = ''
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
UNION ALL
|
|
257
|
+
|
|
258
|
+
-- Recursive step: Find consumers of the consumers
|
|
259
|
+
SELECT
|
|
260
|
+
i.file_path as consumer_path,
|
|
261
|
+
i.module_specifier,
|
|
262
|
+
i.imported_symbols,
|
|
263
|
+
dc.consumer_path as source_path,
|
|
264
|
+
dc.depth + 1,
|
|
265
|
+
i.file_path || '<-' || dc.path_chain
|
|
266
|
+
FROM imports i
|
|
267
|
+
JOIN dependency_chain dc ON i.resolved_path = dc.consumer_path
|
|
268
|
+
WHERE dc.depth < ? -- Max depth limit
|
|
269
|
+
AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection: ensure we haven't visited this file in this chain
|
|
270
|
+
)
|
|
271
|
+
SELECT DISTINCT
|
|
272
|
+
dc.consumer_path,
|
|
273
|
+
dc.depth,
|
|
274
|
+
dc.source_path,
|
|
275
|
+
dc.imported_symbols
|
|
276
|
+
FROM dependency_chain dc
|
|
277
|
+
ORDER BY dc.depth, dc.consumer_path;
|
|
278
|
+
`});var Vt,Yi=V(()=>{"use strict";be();Ji();Vt=class extends K{findByFile(e){return this.all("SELECT * FROM imports WHERE file_path = ?",e)}findByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM imports WHERE file_path IN (${t}) ORDER BY file_path`,...e)}getAllResolved(){return this.all(`
|
|
279
|
+
SELECT * FROM imports
|
|
280
|
+
WHERE resolved_path IS NOT NULL AND resolved_path != ''
|
|
281
|
+
`)}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(`
|
|
282
|
+
SELECT *
|
|
283
|
+
FROM imports
|
|
284
|
+
WHERE file_path = ?
|
|
285
|
+
AND (imported_symbols LIKE ? OR imported_symbols = '*')
|
|
286
|
+
LIMIT 1
|
|
287
|
+
`,e,`%${t}%`)}findProxies(e){return this.all(`
|
|
288
|
+
SELECT i.file_path
|
|
289
|
+
FROM imports i
|
|
290
|
+
JOIN exports e ON i.file_path = e.file_path
|
|
291
|
+
WHERE i.resolved_path = ?
|
|
292
|
+
AND (e.kind = 'ExportAllDeclaration' OR e.kind = 'ExportMapping')
|
|
293
|
+
`,e)}findVerifiedDependents(e,t){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.all(`
|
|
294
|
+
SELECT i.file_path, i.imported_symbols, f.classification, f.summary
|
|
295
|
+
FROM imports i
|
|
296
|
+
JOIN files f ON i.file_path = f.path
|
|
297
|
+
WHERE i.resolved_path IN (${n})
|
|
298
|
+
AND (i.imported_symbols LIKE ? OR i.imported_symbols = '' OR i.imported_symbols = '*')
|
|
299
|
+
LIMIT 10
|
|
300
|
+
`,...e,`%${t}%`)}countVerifiedDependents(e,t){if(e.length===0)return 0;let n=e.map(()=>"?").join(", ");return this.get(`
|
|
301
|
+
SELECT COUNT(*) as count FROM imports
|
|
302
|
+
WHERE resolved_path IN (${n})
|
|
303
|
+
AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
|
|
304
|
+
`,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(qi,e,t,n)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}}});var Qt,Vi=V(()=>{"use strict";be();Qt=class extends K{findById(e){return this.get("SELECT * FROM missions WHERE id = ?",e)}findByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM missions WHERE id IN (${t})`,...e)}findActive(e){let t="SELECT * FROM missions WHERE status IN ('in-progress', 'planned', 'verifying')",n=[];return e&&(t+=" AND git_branch = ?",n.push(e)),t+=` ORDER BY
|
|
305
|
+
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
306
|
+
created_at ASC`,this.all(t,...n)}findAll(e){let t="SELECT * FROM missions",n=[];return e&&(t+=" WHERE status = ?",n.push(e)),t+=` ORDER BY
|
|
307
|
+
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
308
|
+
created_at ASC`,this.all(t,...n)}findRecentCompleted(e=3){return this.all(`
|
|
309
|
+
SELECT * FROM missions
|
|
310
|
+
WHERE status = 'completed'
|
|
311
|
+
ORDER BY updated_at DESC, id DESC
|
|
312
|
+
LIMIT ?
|
|
313
|
+
`,e)}create(e){return this.insert(`
|
|
314
|
+
INSERT INTO missions (name, goal, strategy_graph, status, git_branch, commit_sha, parent_id, verification_context, outcome_contract)
|
|
315
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
316
|
+
`,e.name,e.goal,e.strategy_graph,e.status,e.git_branch,e.commit_sha,e.parent_id,e.verification_context,e.outcome_contract)}addArtifact(e,t,n,i){this.run("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,t,n,i?JSON.stringify(i):null)}getArtifacts(e){return this.all("SELECT * FROM mission_artifacts WHERE mission_id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE missions SET ${i}, updated_at = unixepoch() WHERE id = ?`,...r)}updateStatus(e,t,n){n?this.run("UPDATE missions SET status = ?, updated_at = unixepoch(), commit_sha = ? WHERE id = ?",t,n,e):this.run("UPDATE missions SET status = ?, updated_at = unixepoch() WHERE id = ?",t,e)}getWorkingSet(e){return this.all("SELECT file_path, type FROM working_set WHERE mission_id = ?",e)}clearWorkingSet(e){this.run("DELETE FROM working_set WHERE mission_id = ?",e)}addToWorkingSet(e,t,n="file"){this.run("INSERT OR IGNORE INTO files (path, mtime, last_scanned_at) VALUES (?, unixepoch(), unixepoch())",t),this.run("INSERT INTO working_set (mission_id, file_path, type) VALUES (?, ?, ?)",e,t,n)}findColdMissions(e,t=10){return this.all(`
|
|
317
|
+
SELECT m.id, COUNT(il.id) as log_count
|
|
318
|
+
FROM missions m
|
|
319
|
+
LEFT JOIN intent_logs il ON il.mission_id = m.id
|
|
320
|
+
WHERE m.updated_at < ?
|
|
321
|
+
AND m.status != 'distilled'
|
|
322
|
+
GROUP BY m.id
|
|
323
|
+
HAVING log_count > ?
|
|
324
|
+
`,e,t).map(i=>i.id)}getStats(){let e=this.get(`
|
|
325
|
+
SELECT
|
|
326
|
+
COUNT(*) as total,
|
|
327
|
+
SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
|
|
328
|
+
SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
|
|
329
|
+
FROM missions
|
|
330
|
+
`);return{total:e?.total||0,completed:e?.completed||0,active:e?.active||0}}getAnalytics(){let e=this.getStats(),t=e.total>0?Math.round(e.completed/e.total*100):0,n=this.get(`
|
|
331
|
+
SELECT AVG(updated_at - created_at) AS avg_duration
|
|
332
|
+
FROM missions
|
|
333
|
+
WHERE status = 'completed' AND updated_at > created_at
|
|
334
|
+
`),i=n?.avg_duration!=null?Math.round(n.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,o=Math.floor(Date.now()/1e3)-720*3600,l=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),a=l?.n??0,p=c?.n??0,d=`${a} completed in last 7 days, ${p} in last 30 days.`;if(i!=null){let u=Math.round(i/60);d+=` Avg mission duration: ${u} min.`}return{completionRate:t,averageDurationSeconds:i,completedLast7Days:a,completedLast30Days:p,velocityNote:d}}suspendByBranch(e){this.run(`UPDATE missions
|
|
335
|
+
SET status = 'suspended', updated_at = unixepoch()
|
|
336
|
+
WHERE git_branch = ? AND status IN ('in-progress', 'planned', 'verifying')`,e)}resumeByBranch(e){this.run(`UPDATE missions
|
|
337
|
+
SET status = 'in-progress', updated_at = unixepoch()
|
|
338
|
+
WHERE git_branch = ? AND status = 'suspended'`,e)}findMergedMissions(e,t){if(t.length===0)return[];let n=t.filter(r=>r!==e);if(n.length===0)return[];let i=n.map(()=>"?").join(",");return this.all(`SELECT * FROM missions
|
|
339
|
+
WHERE status IN ('in-progress', 'planned', 'verifying', 'suspended')
|
|
340
|
+
AND git_branch IN (${i})`,...n)}findByCommitShas(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.all(`SELECT * FROM missions WHERE commit_sha IN (${t})`,...e)}findByParentId(e){return this.all("SELECT * FROM missions WHERE parent_id = ?",e)}hasChildren(e){return!!this.get("SELECT 1 FROM missions WHERE parent_id = ? LIMIT 1",e)}hasNoSteps(e){if(!e.strategy_graph)return!0;try{let t=JSON.parse(e.strategy_graph),n=t?.steps??t;return!Array.isArray(n)||n.length===0}catch{return!0}}findParentOnlyIds(e){return e.filter(t=>t.parent_id!=null||!this.hasChildren(t.id)?!1:this.hasNoSteps(t)).map(t=>t.id)}createLink(e,t,n,i,r){this.db.exec(`
|
|
341
|
+
CREATE TABLE IF NOT EXISTS cross_repo_links (
|
|
342
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
343
|
+
mission_id INTEGER NOT NULL,
|
|
344
|
+
linked_repo_path TEXT NOT NULL,
|
|
345
|
+
linked_mission_id INTEGER NOT NULL,
|
|
346
|
+
relationship TEXT,
|
|
347
|
+
direction TEXT,
|
|
348
|
+
created_at REAL DEFAULT (unixepoch()),
|
|
349
|
+
FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
|
|
350
|
+
);
|
|
351
|
+
CREATE INDEX IF NOT EXISTS idx_cross_repo_mission ON cross_repo_links(mission_id);
|
|
352
|
+
`),this.run(`
|
|
353
|
+
INSERT INTO cross_repo_links (mission_id, linked_repo_path, linked_mission_id, relationship, direction)
|
|
354
|
+
VALUES (?, ?, ?, ?, ?)
|
|
355
|
+
`,e,t,n,i,r)}getLinks(e){try{return this.all(`
|
|
356
|
+
SELECT linked_repo_path, linked_mission_id, relationship, direction
|
|
357
|
+
FROM cross_repo_links
|
|
358
|
+
WHERE mission_id = ?
|
|
359
|
+
`,e)}catch{return[]}}findLastMission(){return this.get("SELECT * FROM missions ORDER BY updated_at DESC, id DESC LIMIT 1")}findActiveByPriority(){return this.get("SELECT * FROM missions WHERE status IN ('in-progress', 'active', 'verifying') ORDER BY CASE WHEN status = 'in-progress' THEN 0 ELSE 1 END, created_at ASC LIMIT 1")}}});var Kt,Qi=V(()=>{"use strict";be();Kt=class extends K{findByMission(e,t=50){return this.all(`
|
|
360
|
+
SELECT * FROM intent_logs
|
|
361
|
+
WHERE mission_id = ?
|
|
362
|
+
ORDER BY created_at DESC
|
|
363
|
+
LIMIT ?
|
|
364
|
+
`,e,t)}findRecentDecisionActivity(e=10){return this.all(`
|
|
365
|
+
SELECT * FROM intent_logs
|
|
366
|
+
WHERE type IN ('decision', 'system', 'fix', 'heritage', 'adr')
|
|
367
|
+
ORDER BY created_at DESC
|
|
368
|
+
LIMIT ?
|
|
369
|
+
`,e)}create(e){return this.insert(`
|
|
370
|
+
INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
|
|
371
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
372
|
+
`,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let i=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${i} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
|
|
373
|
+
SELECT id, file_path, symbol_name, signature
|
|
374
|
+
FROM intent_logs
|
|
375
|
+
WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
|
|
376
|
+
`)}findOrphans(){return this.all(`
|
|
377
|
+
SELECT il.id, il.symbol_id, il.file_path, il.symbol_name
|
|
378
|
+
FROM intent_logs il
|
|
379
|
+
WHERE (il.symbol_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM exports e WHERE e.id = il.symbol_id))
|
|
380
|
+
OR (il.symbol_id IS NULL AND il.type != 'lapsed' AND il.type != 'system' AND il.type != 'adr')
|
|
381
|
+
`)}findLogsForMissingFiles(){return this.all(`
|
|
382
|
+
SELECT il.id
|
|
383
|
+
FROM intent_logs il
|
|
384
|
+
WHERE il.file_path IS NOT NULL
|
|
385
|
+
AND NOT EXISTS (
|
|
386
|
+
SELECT 1 FROM files f WHERE f.path = il.file_path
|
|
387
|
+
)
|
|
388
|
+
`)}markAsLapsed(e){this.run(`
|
|
389
|
+
UPDATE intent_logs
|
|
390
|
+
SET symbol_id = NULL,
|
|
391
|
+
type = 'lapsed',
|
|
392
|
+
content = 'Lapsed: ' || content
|
|
393
|
+
WHERE id = ?
|
|
394
|
+
`,e)}importHeritage(e,t,n,i){this.run(`
|
|
395
|
+
INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
|
|
396
|
+
VALUES ('heritage', ?, ?, ?, ?, 0)
|
|
397
|
+
`,e,t,n,i)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}}});var Xt,Ki=V(()=>{"use strict";be();Xt=class extends K{findByKey(e,t=20){return this.all(`
|
|
398
|
+
SELECT file_path, key, value, kind
|
|
399
|
+
FROM configs
|
|
400
|
+
WHERE key LIKE ? OR value LIKE ?
|
|
401
|
+
LIMIT ?
|
|
402
|
+
`,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",i=[];return e&&(n+=" WHERE kind = ?",i.push(e)),n+=" LIMIT ?",i.push(t),this.all(n,...i)}findEnvValue(e){return this.get("SELECT value FROM configs WHERE key LIKE ? OR key = ? LIMIT 1",`%:env:${e}`,e)?.value}countByKind(e){return this.get("SELECT COUNT(*) as count FROM configs WHERE kind = ?",e)?.count||0}getAll(){return this.all("SELECT key, value, kind, file_path FROM configs")}}});var Zt,Xi=V(()=>{"use strict";be();Zt=class extends K{search(e,t=10){return this.all(`
|
|
403
|
+
SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
|
|
404
|
+
FROM content_fts
|
|
405
|
+
WHERE content_fts MATCH ?
|
|
406
|
+
LIMIT ?
|
|
407
|
+
`,e,t)}}});var Zi,en,es=V(()=>{"use strict";be();Zi=500,en=class extends K{record(e,t,n=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,n),this.pruneIfNeeded()}findRecent(e=20){return this.all("SELECT id, query, mode, branch, created_at FROM search_history ORDER BY created_at DESC LIMIT ?",e)}findRecentByQueryPrefix(e,t=10){return e.trim()?this.all(`SELECT id, query, mode, branch, created_at FROM search_history
|
|
408
|
+
WHERE query LIKE ? ORDER BY created_at DESC LIMIT ?`,`${e}%`,t):this.findRecent(t)}pruneIfNeeded(){(this.get("SELECT COUNT(*) as count FROM search_history")?.count??0)<=Zi||this.run(`DELETE FROM search_history WHERE id NOT IN (
|
|
409
|
+
SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
|
|
410
|
+
)`,Zi)}}});var tn,ts=V(()=>{"use strict";be();tn=class extends K{getSection(e){return this.get("SELECT section, data, updated_at FROM hologram_snapshot WHERE section = ?",e)}getAllSections(){return this.all("SELECT section, data, updated_at FROM hologram_snapshot ORDER BY section")}upsertSection(e,t){this.run(`
|
|
411
|
+
INSERT INTO hologram_snapshot (section, data, updated_at)
|
|
412
|
+
VALUES (?, ?, unixepoch())
|
|
413
|
+
ON CONFLICT(section) DO UPDATE SET
|
|
414
|
+
data = excluded.data,
|
|
415
|
+
updated_at = excluded.updated_at
|
|
416
|
+
`,e,t)}deleteSection(e){this.run("DELETE FROM hologram_snapshot WHERE section = ?",e)}deleteAll(){this.run("DELETE FROM hologram_snapshot")}hasSection(e){return(this.get("SELECT COUNT(*) as count FROM hologram_snapshot WHERE section = ?",e)?.count??0)>0}}});var k,F=V(()=>{"use strict";Ve();zi();Gi();Yi();Vi();Qi();Ki();Xi();es();ts();k=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=ke(e),o=t.files?.database,l=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!l)return t;this.repositoryCache.delete(e)}let n=ke(e),i={files:new Jt(n),exports:new Yt(n),imports:new Vt(n),missions:new Qt(n),intentLogs:new Kt(n),configs:new Xt(n),content:new Zt(n),searchHistory:new en(n),hologram:new tn(n)};return this.repositoryCache.set(e,i),i}static closeInstance(e){this.repositoryCache.delete(e),qt(e)}static clearCache(e){this.repositoryCache.delete(e)}}});var ss=Uo((pp,Xn)=>{var sn=process||{},ns=sn.argv||[],nn=sn.env||{},oa=!(nn.NO_COLOR||ns.includes("--no-color"))&&(!!nn.FORCE_COLOR||ns.includes("--color")||sn.platform==="win32"||(sn.stdout||{}).isTTY&&nn.TERM!=="dumb"||!!nn.CI),aa=(s,e,t=s)=>n=>{let i=""+n,r=i.indexOf(e,s.length);return~r?s+ca(i,e,t,r)+e:s+i+e},ca=(s,e,t,n)=>{let i="",r=0;do i+=s.substring(r,n)+t,r=n+e.length,n=s.indexOf(e,r);while(~n);return i+s.substring(r)},is=(s=oa)=>{let e=s?aa:()=>String;return{isColorSupported:s,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Xn.exports=is();Xn.exports.createColors=is});var lr,pr,ur,dr,mr,hr,fr,gr,yr,br,Er,Sr,_r,xr,_i,Rr,Tr,vr,wr=V(()=>{"use strict";lr=[/\/pages\/(?!_)[^/]+\.(tsx?|jsx?)$/i,/\/pages\/.*\/index\.(tsx?|jsx?)$/i,/\/app\/.*\/page\.(tsx?|jsx?)$/i,/\/app\/.*\/layout\.(tsx?|jsx?)$/i,/\/app\/api\/.*\/route\.(ts|js)$/i,/\/pages\/api\/.*\.(ts|js)$/i],pr=[/\.(routes?|router|controller|handler|endpoint|api)\.(ts|js|tsx|jsx)$/i,/\/routes?\//i,/\/controllers?\//i,/index\.(ts|js|tsx|jsx)$/i],ur=[/\/components?\/.*\.(tsx|jsx)$/i,/\/features?\/.*\.(tsx|jsx)$/i,/\/views?\/.*\.(tsx|jsx)$/i,/\/screens?\/.*\.(tsx|jsx)$/i,/\/widgets?\/.*\.(tsx|jsx)$/i],dr=[/\.(service|usecase|interactor|manager|facade)\.(ts|js)$/i,/\/services?\//i,/\/usecases?\//i,/\/domain\//i,/\/business\//i],mr=[/\/mcp\/handlers?\/[^/]+\.(ts|js)$/i,/\/mcp\/tools?\/[^/]+\.(ts|js)$/i,/\/mcp\/server\.(ts|js)$/i,/\/mcp\/index\.(ts|js)$/i],hr=[/\/mcp\/utils?\.(ts|js)$/i,/\/mcp\/schemas?\.(ts|js)$/i,/\/mcp\/resources?\.(ts|js)$/i],fr=[/\/commands?\/[^/]+\.(ts|js|py|php)$/i,/\/cli\/[^/]+\.(ts|js|py|php)$/i,/\/bin\/[^/]+\.(ts|js|py|php)$/i,/cli\.(ts|js|py|php)$/i,/main\.(ts|js|py|php)$/i],gr=[/\/parser\/[^/]+\.(ts|js)$/i,/\/ast\/[^/]+\.(ts|js)$/i,/\.(parser|visitor|walker|transformer)\.(ts|js)$/i],yr=[/\/core\/[^/]+\.(ts|js)$/i,/\/engine\/[^/]+\.(ts|js)$/i,/\/processing\/[^/]+\.(ts|js)$/i,/\/analysis\/[^/]+\.(ts|js)$/i,/\.(analyzer|processor|scanner|indexer|resolver)\.(ts|js)$/i],br=[/\/ui\/[^/]+\.(ts|js|tsx|jsx)$/i,/\/display\/[^/]+\.(ts|js)$/i,/\/output\/[^/]+\.(ts|js)$/i,/\.(formatter|renderer|printer)\.(ts|js)$/i],Er=[/\/stores?\//i,/\/slices?\//i,/\/reducers?\//i,/\/atoms?\//i,/\/selectors?\//i,/\.(store|slice|reducer|atom|selector)\.(ts|js)$/i,/.*Slice\.(ts|js)$/i,/.*Store\.(ts|js)$/i],Sr=[/\/hooks?\//i,/\/contexts?\//i,/\/providers?\//i,/use[A-Z].*\.(ts|js)$/,/.*Context\.(ts|tsx|js|jsx)$/i,/.*Provider\.(ts|tsx|js|jsx)$/i],_r=[/\/schemas?\//i,/\/validations?\//i,/\.(schema|validation|validator)\.(ts|js)$/i],xr=[/\.(types?|dto|interface|interfaces)\.(ts|js)$/i,/types\.ts$/i,/\/types?\//i,/\/dtos?\//i,/\/interfaces?\//i,/\/contracts?\//i,/\.d\.ts$/i],_i=[/\.(model|entity|schema|repository|repo|dao|migration|query|mutation|resolver|connection|db)\.(ts|js)$/i,/queries\.(ts|js)$/i,/mutations\.(ts|js)$/i,/resolvers\.(ts|js)$/i,/connection\.(ts|js)$/i,/\/models?\//i,/\/entities?\//i,/\/repositories?\//i,/\/repos?\//i,/\/data\//i,/\/database\//i,/\/prisma\//i,/\/drizzle\//i,/\/api\/.*client\.(ts|js|tsx)$/i,/(^|\/)[A-Z0-9_-]*API\.(tsx?|js|jsx)$/],Rr=[/\.(util|utils|helper|helpers|lib|common|shared)\.(ts|js)$/i,/\/utils?\//i,/\/helpers?\//i,/\/lib\//i,/\/common\//i,/\/shared\//i],Tr=["express","fastify","koa","hapi","restify","next","nuxt","gatsby","remix","@nestjs/common","@nestjs/core","react-router","vue-router","@angular/router","zod","joi","yup","valibot","superstruct"],vr=["prisma","@prisma/client","typeorm","sequelize","mongoose","drizzle-orm","knex","pg","mysql","sqlite","better-sqlite3","mongodb","redis","ioredis","zustand","redux","recoil","jotai","mobx"]});var Ir,kr,Cr,Lr,$r=V(()=>{"use strict";Ir=[/urls\.py$/i,/wsgi\.py$/i,/asgi\.py$/i,/manage\.py$/i,/main\.py$/i,/app\.py$/i,/\/endpoints?\/.*\.py$/i,/\/commands?\/.*\.py$/i],kr=[/views\.py$/i,/forms\.py$/i,/serializers\.py$/i,/admin\.py$/i,/apps\.py$/i,/tasks\.py$/i,/middlewares?\.py$/i,/signals?\.py$/i,/context_processors\.py$/i],Cr=[/models\.py$/i,/\/models\/.*\.py$/i,/\/migrations\/.*\.py$/i,/schema\.py$/i,/documents\.py$/i],Lr=["django.urls","django.http","flask","fastapi","chalice","tornado"]});var Nr,Ar,Mr,Pr,Dr=V(()=>{"use strict";Nr=[/\/routes?\/.*\.php$/i,/\/controllers?\/.*\.php$/i,/index\.php$/i,/server\.php$/i,/artisan$/i,/console$/i],Ar=[/\/services?\/.*\.php$/i,/\/providers?\/.*\.php$/i,/\/middleware\/.*\.php$/i,/\/jobs?\/.*\.php$/i,/\/listeners?\/.*\.php$/i,/\/events?\/.*\.php$/i,/\/observers?\/.*\.php$/i,/\/console\/commands\/.*\.php$/i,/\/actions?\/.*\.php$/i,/\/traits?\/.*\.php$/i,/\/concerns?\/.*\.php$/i,/\/contracts?\/.*\.php$/i],Mr=[/\/models?\/.*\.php$/i,/\/eloquent\/.*\.php$/i,/\/migrations?\/.*\.php$/i,/\/seeders?\/.*\.php$/i,/\/factories?\/.*\.php$/i,/\/repositories?\/.*\.php$/i,/\/resources?\/.*\.php$/i],Pr=["laravel","symfony","slim","cakephp","codeigniter"]});import Or from"path";function Dt(s,e,t){let n=[],i="Unknown",r=0;t||(t=dc(s,e));let{inDegree:o,outDegree:l}=t,c=(u,m,h,b)=>{for(let E of u)if(E.test(s))return n.push(`${b}: ${E.source}`),i=m,r+=h,!0;return!1},a=!1;if(a||(a=c(lr,"Entry",45,"Next.js entry")),a||(a=c(mr,"Entry",40,"MCP handler")),a||(a=c(fr,"Entry",40,"CLI command")),a||(a=c(_i,"Data",45,"Data layer/Repository")),a||(a=c(Er,"Data",35,"State management")),a||(a=c(ur,"Logic",40,"React component")),a||(a=c(dr,"Logic",35,"Logic pattern")),a||(a=c(gr,"Logic",35,"Parser/AST")),a||(a=c(yr,"Logic",35,"Core module")),a||(a=c(br,"Logic",30,"UI layer")),a||(a=c(xr,"Types",35,"Type definition")),a||(a=c(Ir,"Entry",40,"Python Entry")),a||(a=c(Cr,"Data",40,"Python Data")),a||(a=c(kr,"Logic",35,"Python Logic")),a||(a=c(Nr,"Entry",40,"PHP Entry")),a||(a=c(Mr,"Data",40,"PHP Data")),a||(a=c(Ar,"Logic",35,"PHP Logic")),a||(a=c(Sr,"Logic",35,"Hook/Context")),!a){for(let u of hr)if(u.test(s)){n.push(`MCP utility: ${u.source}`),/schemas?/i.test(s)?i="Types":/resources?/i.test(s)?i="Data":i="Utility",r+=35,a=!0;break}}a||c(_r,"Data",35,"Schema definition")&&(a=!0),a||(c(_i,"Data",30,"Path matches data pattern")||c(Rr,"Utility",25,"Path matches utility pattern")||c(pr,"Entry",30,"Path matches entry pattern"))&&(a=!0);for(let u of lc)if(u.test(s)){n.push(`Test file: ${u.source}`),i="Test",r=50,a=!0;break}a||c(pc,"Infrastructure",40,"Infrastructure")&&(a=!0);for(let u of uc)u.test(s)&&(n.push(`Monorepo component: ${u.source}`),/\/apps\/[^/]+\/src\/pages\//i.test(s)&&(n.push("Monorepo App Entry"),i==="Unknown"&&(i="Entry"),r+=20),/\/packages\/[^/]+\/src\//i.test(s)&&(r+=10));let d=e.imports.getImportsForFile(s).map(u=>u.module_specifier.toLowerCase());for(let u of vr)if(d.some(m=>m.includes(u))){n.push(`Imports JS data library: ${u}`),(i==="Unknown"||i==="Data")&&(i="Data",r+=25);break}for(let u of Lr)if(d.some(m=>m.includes(u))){n.push(`Imports Python framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let u of Pr)if(d.some(m=>m.includes(u))){n.push(`Imports PHP framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}for(let u of Tr)if(d.some(m=>m.includes(u))){n.push(`Imports JS framework: ${u}`),(i==="Unknown"||i==="Entry")&&(i="Entry",r+=20);break}if(o===0&&l>0&&(n.push("Entry point: nothing imports this file (in-degree=0)"),i==="Unknown"?(i="Entry",r+=30):i==="Entry"&&(r+=15)),o>5&&l<=2&&(n.push(`High reuse: ${o} files import this (candidate for Utility)`),i==="Unknown"?(i="Utility",r+=25):i==="Utility"&&(r+=10)),i==="Unknown"&&o>0&&l>0){let u=o/(o+l);u>.3&&u<.7&&(n.push(`Balanced traffic: in=${o}, out=${l} (likely Logic layer)`),i="Logic",r+=25)}return i==="Unknown"&&(n.push("No strong classification signals detected"),r=10),r=Math.min(r,100),{layer:i,confidence:r,signals:n}}function dc(s,e){let t=e.imports.countDependents(s),n=e.imports.countByFile(s);return{inDegree:t,outDegree:n}}function ut(s,e){let t=s.files.getAllPaths().map(h=>({path:h})),n=new Map,i={Entry:[],Logic:[],Data:[],Utility:[],Infrastructure:[],Test:[],Types:[],Unknown:[]};for(let h of t){let b=Dt(h.path,s);n.set(h.path,b),i[b.layer].push({path:h.path,classification:b})}let r={Entry:We(i.Entry,e),Logic:We(i.Logic,e),Data:We(i.Data,e),Utility:We(i.Utility,e),Infrastructure:We(i.Infrastructure,e),Test:We(i.Test,e),Types:We(i.Types,e),Unknown:We(i.Unknown,e)},o={};t.forEach(h=>{let b=Or.extname(h.path).toLowerCase();b&&(o[b]=(o[b]||0)+1)});let l={".ts":"TypeScript",".tsx":"Typescript (React)",".js":"JavaScript",".jsx":"JavaScript (React)",".py":"Python",".php":"PHP",".go":"Go",".rs":"Rust",".java":"Java",".cs":"C#",".rb":"Ruby",".vue":"Vue"},c={};Object.entries(o).forEach(([h,b])=>{let E=l[h];E&&(c[E]=(c[E]||0)+b)});let a=Object.entries(c).sort((h,b)=>b[1]-h[1]),p=a.length>0?a[0][0]:"Unknown",{pattern:d,patternConfidence:u,insights:m}=mc(r,t.length,s);return{pattern:d,patternConfidence:u,layers:r,insights:m,primaryStack:p}}function We(s,e){return s.sort((t,n)=>n.classification.confidence-t.classification.confidence),{count:s.length,topFiles:s.slice(0,5).map(t=>({path:Or.relative(e,t.path),confidence:t.classification.confidence,signals:t.classification.signals.slice(0,2)}))}}function mc(s,e,t){let n=[],i="Unknown",r=0,o=s.Entry.count/e*100,l=s.Logic.count/e*100,c=s.Data.count/e*100,a=s.Utility.count/e*100,p=s.Unknown.count/e*100;o>5&&l>10&&c>5&&p<40?(i="Layered",r=60+Math.min(30,(100-p)/3),n.push(`Clear layer separation: Entry (${o.toFixed(1)}%), Logic (${l.toFixed(1)}%), Data (${c.toFixed(1)}%)`)):a>20?(i="Modular",r=50+a/2,n.push(`High shared module usage: ${a.toFixed(1)}% utility files`)):p>60&&(i="Monolithic",r=40+p/4,n.push(`Limited architectural structure: ${p.toFixed(1)}% files with unclear layer assignment`));let d=t.configs.countByKind("Service");return d>3&&(i="Microservices",r=55+d*5,n.push(`Detected ${d} service definitions (likely microservices)`)),s.Entry.count===0&&n.push("\u26A0\uFE0F No clear entry points detected - consider adding route/controller files"),s.Data.count===0&&n.push("\u26A0\uFE0F No data layer detected - repository may not use traditional ORM patterns"),a>30&&n.push(`High utility concentration (${a.toFixed(1)}%) - good reusability`),{pattern:i,patternConfidence:Math.min(100,r),insights:n}}var lc,pc,uc,Ot=V(()=>{"use strict";wr();$r();Dr();lc=[/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/tests?\.py$/i,/\/__tests__\//i,/\/tests?\//i,/\.e2e\.(ts|js)$/i,/\.integration\.(ts|js)$/i],pc=[/Dockerfile/i,/docker-compose/i,/\.ya?ml$/i,/nginx\.conf/i,/\/infra\//i,/\/deploy\//i,/\/k8s\//i,/\/kubernetes\//i,/\/terraform\//i,/\/ansible\//i,/package\.json/i,/tsconfig.*\.json/i,/\.env/i],uc=[/\/apps\/[^/]+\//i,/\/services\/[^/]+\//i,/\/packages\/[^/]+\//i,/\/backends\/[^/]+\//i,/\/backends_python\/[^/]+\//i]});var Fr={};Ai(Fr,{HologramService:()=>de});var ye,de,dt=V(()=>{"use strict";F();Ot();N();ye=_.child({module:"hologram"}),de=class{repos;repoPath;constructor(e){this.repoPath=e,this.repos=k.getInstance(e)}updateTopography(e){ye.debug({repoPath:this.repoPath},"Updating topography snapshot");let t=Object.values(e.layers).reduce((r,o)=>r+o.count,0),n={};for(let[r,o]of Object.entries(e.layers)){let l=t>0?o.count/t*100:0;n[r]={count:o.count,percentage:Math.round(l*10)/10,topFiles:o.topFiles.slice(0,3).map(c=>({path:c.path,confidence:c.confidence}))}}let i={pattern:e.pattern,patternConfidence:e.patternConfidence,layerDistribution:n,insights:e.insights,updatedAt:Date.now()};this.repos.hologram.upsertSection("topography",JSON.stringify(i)),ye.info({repoPath:this.repoPath},"Topography snapshot updated")}updateGravityZones(e){ye.debug({repoPath:this.repoPath,count:e.length},"Updating gravity zones");let t={hotspots:e.slice(0,10),updatedAt:Date.now()};this.repos.hologram.upsertSection("gravity",JSON.stringify(t)),ye.info({repoPath:this.repoPath},"Gravity zones updated")}updateGhostBridges(e){ye.debug({repoPath:this.repoPath,count:e.length},"Updating ghost bridges");let t={bridges:e.slice(0,20),updatedAt:Date.now()};this.repos.hologram.upsertSection("ghosts",JSON.stringify(t)),ye.info({repoPath:this.repoPath},"Ghost bridges updated")}getSnapshot(){let e=this.repos.hologram.getAllSections(),t={metadata:{repoPath:this.repoPath,lastUpdated:Date.now(),version:"1.0.0"}};for(let n of e)try{let i=JSON.parse(n.data);switch(n.section){case"topography":t.topography=i;break;case"gravity":t.gravity=i;break;case"ghosts":t.ghosts=i;break}}catch(i){ye.error({repoPath:this.repoPath,section:n.section,error:i},"Failed to parse hologram section")}return t}getSection(e){let t=this.repos.hologram.getSection(e);if(!t)return null;try{return JSON.parse(t.data)}catch(n){return ye.error({repoPath:this.repoPath,section:e,error:n},"Failed to parse section"),null}}computeGravityZones(){ye.debug({repoPath:this.repoPath},"Computing gravity zones from import graph");let e=this.repos.files.getAllPaths(),t=new Map;for(let i of e){let r=Dt(i,this.repos);if(r.layer==="Test"||r.layer==="Unknown")continue;let o=this.repos.exports.findByFile(i);if(o.length===0)continue;let l=this.repos.imports.countDependents(i),c=this.repos.imports.countByFile(i),a=l*2+c;if(a>0){let p=o.find(u=>u.kind!=="TsTypeAliasDeclaration"&&u.kind!=="TsInterfaceDeclaration")||o[0],d=`${i}::${p.name}`;t.set(d,{symbol:p.name,filePath:i,inDegree:l,outDegree:c,gravity:a})}}let n=Array.from(t.values()).sort((i,r)=>r.gravity-i.gravity).slice(0,20);return ye.info({repoPath:this.repoPath,count:n.length},"Gravity zones computed"),n}isInitialized(){return this.repos.hologram.getAllSections().length>0}clear(){this.repos.hologram.deleteAll(),ye.info({repoPath:this.repoPath},"Hologram cleared")}}});var xo={};Ai(xo,{GraphExporterService:()=>$i});var _o,$i,Ro=V(()=>{"use strict";F();N();_o=_.child({module:"graph-exporter"}),$i=class{constructor(e){this.repoPath=e;this.repos=k.getInstance(e)}repos;async generateGraph(e={}){let{includeCompleted:t=!0,format:n="mermaid",focusMissionId:i,depth:r=10,limit:o=100}=e;_o.info({focusMissionId:i,depth:r,format:n,includeCompleted:t},"Generating mission graph");let l=this.buildMissionTree(i,t,r,o);return n==="json"?JSON.stringify(l,null,2):this.generateMermaidDiagram(l)}buildMissionTree(e,t,n,i){let r;if(e){let c=this.repos.missions.findById(e);r=c?[c]:[]}else r=this.repos.missions.findAll().filter(a=>!a.parent_id),t||(r=r.filter(a=>a.status!=="completed"));let o=0,l=[];for(let c of r){if(o>=i)break;let a=this.buildNode(c,t,n,1,{count:o,max:i});a&&(l.push(a),o+=this.countNodes(a))}return l}buildNode(e,t,n,i,r){if(i>n||r.count>=r.max)return null;let o;if(e.strategy_graph)try{let p=JSON.parse(e.strategy_graph);o=this.parseStrategySteps(p)}catch(p){_o.debug({missionId:e.id,err:p},"Failed to parse strategy graph")}let l={id:e.id,name:e.name,status:e.status,goal:e.goal,branch:e.git_branch||void 0,children:[],steps:o},c=this.repos.missions.findByParentId(e.id),a=t?c:c.filter(p=>p.status!=="completed");for(let p of a){if(r.count>=r.max)break;let d=this.buildNode(p,t,n,i+1,r);d&&(l.children.push(d),r.count++)}return l}parseStrategySteps(e){let t=[];return Array.isArray(e)?e.map((n,i)=>({id:n.id||`step-${i}`,description:n.description||n.content||n.name||`Step ${i+1}`,status:n.status,dependencies:n.dependencies||n.deps})):e.steps&&Array.isArray(e.steps)?this.parseStrategySteps(e.steps):typeof e=="object"?Object.entries(e).map(([n,i])=>({id:n,description:i.description||i.content||n,status:i.status,dependencies:i.dependencies||i.deps})):t}countNodes(e){let t=1;for(let n of e.children)t+=this.countNodes(n);return t}generateMermaidDiagram(e){let t=["graph TD"];for(let n of e)this.addMermaidNode(n,t);return t.join(`
|
|
417
|
+
`)}addMermaidNode(e,t,n){let i=`M${e.id}`,r=this.getStatusIcon(e.status),o=this.getStatusClass(e.status),l=`${r} ${e.name}`;if(t.push(` ${i}["${this.escapeMermaid(l)}"]:::${o}`),n&&t.push(` ${n} --> ${i}`),e.steps&&e.steps.length>0&&e.steps.length<=10)for(let c of e.steps){let a=`S${e.id}_${c.id}`,p=c.status||"pending",d=this.getStatusIcon(p),u=this.getStatusClass(p),m=`${d} ${c.description}`;if(t.push(` ${a}["${this.escapeMermaid(m)}"]:::${u}`),t.push(` ${i} -.-> ${a}`),c.dependencies&&c.dependencies.length>0)for(let h of c.dependencies){let b=`S${e.id}_${h}`;t.push(` ${b} --> ${a}`)}}for(let c of e.children)this.addMermaidNode(c,t,i);n||(t.push(""),t.push(" classDef completed fill:#90EE90,stroke:#2E8B57,stroke-width:2px"),t.push(" classDef inProgress fill:#87CEEB,stroke:#4682B4,stroke-width:2px"),t.push(" classDef planned fill:#FFE4B5,stroke:#DAA520,stroke-width:2px"),t.push(" classDef suspended fill:#D3D3D3,stroke:#808080,stroke-width:2px"),t.push(" classDef failed fill:#FFB6C1,stroke:#DC143C,stroke-width:2px"),t.push(" classDef pending fill:#FFF8DC,stroke:#B8860B,stroke-width:1px"))}getStatusIcon(e){return{completed:"\u2713","in-progress":"\u26A1",planned:"\u{1F4CB}",suspended:"\u23F8",failed:"\u2717",pending:"\u25CB",verifying:"\u{1F50D}"}[e]||"\u25CB"}getStatusClass(e){return{completed:"completed","in-progress":"inProgress",planned:"planned",suspended:"suspended",failed:"failed",pending:"pending",verifying:"inProgress"}[e]||"pending"}escapeMermaid(e){return e.replace(/"/g,"#quot;").replace(/\n/g," ").replace(/\[/g,"#91;").replace(/]/g,"#93;").slice(0,100)}}});import"dotenv/config";import{Cli as cl}from"clerc";N();import Mi from"fs";import Jo from"path";import Pi from"js-yaml";var Di={ignore:[],include:[],maxDepth:10},Yo=[{name:".liquid-shadow.yaml",parse:s=>Pi.load(s)??{}},{name:".liquid-shadow.yml",parse:s=>Pi.load(s)??{}},{name:".ls.json",parse:s=>JSON.parse(s)},{name:".liquid-shadow.json",parse:s=>JSON.parse(s)},{name:".ls.rc",parse:s=>JSON.parse(s)},{name:".liquid-shadow.rc",parse:s=>JSON.parse(s)}];function we(s){for(let{name:e,parse:t}of Yo){let n=Jo.join(s,e);if(Mi.existsSync(n))try{let i=Mi.readFileSync(n,"utf8"),r=t(i);return _.info({repoPath:s,configFile:e},"Loaded repository configuration"),{...Di,...r}}catch(i){_.error({repoPath:s,file:e,err:i},"Failed to parse configuration file")}}return Di}function Oi(s,e){let n=we(s).cli??{};return{dir:e.dir??n.dir??".",level:e.level??n.level,deep:e.deep!==void 0?e.deep:n.deep}}F();import Ra from"path";var ee=Bo(ss(),1);import*as Ee from"@clack/prompts";var z={red:ee.default.red,green:ee.default.green,yellow:ee.default.yellow,blue:ee.default.blue,magenta:ee.default.magenta,cyan:ee.default.cyan,white:ee.default.white,gray:ee.default.gray,bold:ee.default.bold,dim:ee.default.dim,italic:ee.default.italic,underline:ee.default.underline,inverse:ee.default.inverse},Pe=s=>s.replace(/\x1b\[[0-9;]*m/g,""),le=s=>Ee.intro(ee.default.bgCyan(ee.default.black(ee.default.bold(` ${s} `)))),Rt=s=>Ee.outro(ee.default.cyan(s)),te=(s,e,t="blue")=>{let n=e.split(`
|
|
418
|
+
`),i=Pe(s),r=Math.max(i.length+4,...n.map(c=>Pe(c).length))+2,o="\u2500".repeat(r),l=z[t];console.log(l(`\u250C${o}\u2510`)),console.log(l("\u2502 ")+z.bold(s).padEnd(r+(s.length-i.length)-1)+l("\u2502")),console.log(l(`\u251C${o}\u2524`)),n.forEach(c=>{let a=Pe(c),p=" ".repeat(r-a.length-1);console.log(l("\u2502 ")+c+p+l("\u2502"))}),console.log(l(`\u2514${o}\u2518`))},rn=(s,e)=>{let t=s.map((i,r)=>Math.max(Pe(i).length,...e.map(o=>Pe(o[r]||"").length))+2),n=z.cyan("\u2502");console.log(n),console.log(n+" "+s.map((i,r)=>z.bold(z.cyan(i)).padEnd(t[r]+(i.length-Pe(i).length))).join(z.gray(" "))+" "),e.forEach(i=>{console.log(n+" "+i.map((r,o)=>(r||"").padEnd(t[o]+(r.length-Pe(r).length))).join(z.gray(" "))+" ")}),console.log(n)},rs=(s,e="\u2022")=>{s.forEach(t=>{console.log(`${z.cyan("\u2502")} ${z.cyan(e)} ${t}`)})},os=(s,e=40)=>{let t=Math.max(...s.map(i=>i.value)),n=Math.max(...s.map(i=>Pe(i.label).length));console.log(z.cyan("\u2502")),s.forEach(i=>{let r=Math.round(i.value/t*e),o="\u2588".repeat(r)+z.dim("\u2591".repeat(e-r)),l=i.color?z[i.color]:z.cyan,c=i.label.padEnd(n);console.log(`${z.cyan("\u2502")} ${z.bold(c)} ${l(o)} ${z.white(i.value.toString())}`)}),console.log(z.cyan("\u2502"))},Zn=(s,e="")=>{s.forEach((t,n)=>{let i=n===s.length-1,r=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=t.color?z[t.color]:t.children?z.blue:z.white,l=t.info?` ${z.gray(`(${t.info})`)}`:"";if(console.log(`${z.cyan("\u2502")} ${e}${z.gray(r)}${o(t.name)}${l}`),t.children&&t.children.length>0){let c=e+(i?" ":"\u2502 ");Zn(t.children,c)}})},ue=()=>Ee.spinner();async function on(s,e,t){if(e.length===0)return;let n=await Ee.select({message:s,options:e.map(i=>({value:i.value,label:i.label,...i.hint!=null&&{hint:i.hint}})),...t?.limit!=null&&{maxItems:t.limit}});if(!Ee.isCancel(n))return n}var la=s=>{console.error("");let e=s instanceof Error?s.message:String(s);console.error(` ${z.red("\u2716")} ${z.bold("Error: ")} ${e}`),s instanceof Error&&"cause"in s&&console.error(` ${z.dim("Cause: "+String(s.cause))}`),console.error(""),process.exit(1)},U=async s=>{try{await s()}catch(e){la(e)}},f=z;N();N();import{Worker as fa}from"node:worker_threads";import{cpus as ga}from"node:os";import{fileURLToPath as ya}from"node:url";import{dirname as ba,join as ls}from"node:path";import{existsSync as ps}from"node:fs";import{fileURLToPath as pa}from"node:url";import{dirname as ei,join as cs,resolve as ua}from"node:path";import{existsSync as da}from"node:fs";var ma=pa(import.meta.url),as=ei(ma);function ha(){let s=as;for(;s!==ei(s);){if(da(cs(s,"package.json")))return s;s=ei(s)}return ua(as,"..","..")}function an(...s){return cs(ha(),...s)}var ds=ya(import.meta.url),us=ba(ds);function Ea(){if(ds.endsWith(".ts")){let e=ls(us,"worker.ts");if(ps(e))return e}let s=ls(us,"worker.js");return ps(s)?s:an("dist/logic/domain/embeddings/worker.js")}var Tt=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;cacheDir;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,ga().length-1),this.cacheDir=e.cacheDir??"./.cache",this.initTimeout=e.initTimeout??6e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{_.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((n,i)=>{e=setTimeout(()=>i(new Error(`Worker pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0,_.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,_.info({numWorkers:this.workers.length},"Embedding worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=Ea();_.debug({workerPath:e},"Resolved worker path");for(let t=0;t<this.numWorkers;t++)await this.createWorker(e,t),await new Promise(n=>setTimeout(n,50))}async createWorker(e,t){return new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new fa(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),l={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){_.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(l),_.debug({workerIndex:t},"Worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(l,c.id,c.embeddings||[]):c.type==="error"&&c.id&&this.handleTaskError(l,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),_.error({err:c,workerIndex:t},"Worker error"),l.currentTaskId&&this.handleTaskError(l,l.currentTaskId,c),!this.initialized){i(c);return}let a=this.workers.indexOf(l);a!==-1&&this.workers.splice(a,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{_.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&_.warn({workerIndex:t,code:c},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let i=this.pendingTasks.get(t);i&&(this.pendingTasks.delete(t),i.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=32,n){if(this.initialized||await this.initialize(),e.length===0)return[];let i=[];for(let a=0;a<e.length;a+=t)i.push(e.slice(a,a+t));let r=new Array(i.length),o=0,l=i.map((a,p)=>new Promise((d,u)=>{let h={id:`task_${++this.taskIdCounter}`,texts:a,resolve:b=>{if(r[p]=b,o++,n){let E=Math.min(o*t,e.length);n(E,e.length)}d()},reject:b=>{if(r[p]=new Array(a.length).fill(null),o++,_.warn({err:b,chunkIndex:p},"Chunk embedding failed"),n){let E=Math.min(o*t,e.length);n(E,e.length)}d()}};this.taskQueue.push(h),this.processQueue()}));await Promise.all(l);let c=[];for(let a of r)c.push(...a);return _.info({total:e.length,successful:c.filter(a=>a!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),c}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}_.info({numWorkers:this.workers.length},"Shutting down embedding worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,_.info("Embedding worker pool shutdown complete")}},it=null;function ti(s){return it||(it=new Tt(s)),it}async function cn(){it&&(await it.shutdown(),it=null)}var vt=null;async function Sa(){return vt||(vt=await import("@xenova/transformers"),vt.env.cacheDir="./.cache",vt.env.allowLocalModels=!1),vt}var _a=128,ms=!1;function ln(s){ms=s,_.info({useWorkerThreads:s},"Worker thread mode updated")}var ni=null;async function hs(){return ni||(ni=(async()=>{_.info("Loading embedding model (all-MiniLM-L6-v2)...");let{pipeline:s}=await Sa();return await s("feature-extraction","Xenova/all-MiniLM-L6-v2")})()),ni}async function ii(s){try{let t=await(await hs())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return _.error({err:e},"Failed to generate embedding"),null}}async function si(s,e=_a,t){return s.length===0?[]:ms?ti().generateEmbeddings(s,e,t):xa(s,e,t)}async function xa(s,e,t){let n=new Array(s.length).fill(null),i=await hs();for(let r=0;r<s.length;r+=e){let o=Math.min(r+e,s.length),l=s.slice(r,o);try{let c=await i(l,{pooling:"mean",normalize:!0}),[a,p]=c.dims;for(let d=0;d<a;d++){let u=d*p,m=u+p;n[r+d]=Array.from(c.data.slice(u,m))}}catch(c){_.error({err:c,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let a=0;a<l.length;a++)try{let p=l[a];if(!p||p.trim().length===0)continue;let d=await i(p,{pooling:"mean",normalize:!0});n[r+a]=Array.from(d.data)}catch{n[r+a]=null}}t&&t(o,s.length)}return _.debug({total:s.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function ri(s,e){let t=0,n=0,i=0;for(let r=0;r<s.length;r++)t+=s[r]*e[r],n+=s[r]*s[r],i+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(i))}Ve();N();async function G(s){_.info("Performing graceful shutdown...");try{await cn()}catch(e){_.error({err:e},"Error shutting down worker pool")}try{s&&qt(s)}catch(e){_.error({err:e},"Error closing database")}_.info("Shutdown complete")}async function fs(s){let e=Ra.resolve(s);try{await U(async()=>{let t=k.getInstance(e),n=we(e),i=n.ignore&&n.ignore.length>0,r=t.files.getCount(),o=t.exports.getCount(),l=t.files.getLatestScanTime(),c=t.exports.getKindDistribution(5);te("Repo Status",`${f.bold("Files")}: ${f.cyan(r.toString())}
|
|
419
|
+
${f.bold("Symbols")}: ${f.cyan(o.toString())}
|
|
420
|
+
${f.bold("Last Scan")}: ${l?f.yellow(new Date(l).toLocaleString()):f.red("Never")}
|
|
421
|
+
${f.bold("Config")}: ${i?f.green("Active"):f.gray("Default")}`,"blue"),c.length>0&&(console.log(""),console.log(` ${f.bold("Symbol Distribution (Top 5) ")}`),os(c.map(a=>({label:a.kind,value:a.c,color:"cyan"})),30))})}finally{await G(e)}}F();Ve();import Ta from"path";N();import re from"fs";import Qe from"path";var st=_.child({module:"git-hooks"}),pn={"post-merge":`#!/bin/sh
|
|
422
|
+
# Liquid Shadow: Auto-refresh index after merge/pull
|
|
423
|
+
# Generated by liquid-shadow
|
|
424
|
+
|
|
425
|
+
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
426
|
+
|
|
427
|
+
# Run liquid-shadow sync in background to avoid blocking git operations
|
|
428
|
+
nohup npx @precisionutilityguild/liquid-shadow sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
429
|
+
|
|
430
|
+
exit 0
|
|
431
|
+
`,"post-checkout":`#!/bin/sh
|
|
432
|
+
# Liquid Shadow: Auto-refresh index after branch checkout
|
|
433
|
+
# Generated by liquid-shadow
|
|
434
|
+
|
|
435
|
+
# Only run on branch checkouts, not file checkouts
|
|
436
|
+
# $3 is 1 for branch checkout, 0 for file checkout
|
|
437
|
+
if [ "$3" = "1" ]; then
|
|
438
|
+
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
439
|
+
|
|
440
|
+
# Run liquid-shadow sync in background
|
|
441
|
+
nohup npx @precisionutilityguild/liquid-shadow sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
442
|
+
fi
|
|
443
|
+
|
|
444
|
+
exit 0
|
|
445
|
+
`,"post-commit":`#!/bin/sh
|
|
446
|
+
# Liquid Shadow: Trigger symbol shift detection after commit
|
|
447
|
+
# Generated by liquid-shadow
|
|
448
|
+
|
|
449
|
+
REPO_PATH="$(git rev-parse --show-toplevel)"
|
|
450
|
+
|
|
451
|
+
# Run liquid-shadow sync in background
|
|
452
|
+
nohup npx @precisionutilityguild/liquid-shadow sync "$REPO_PATH" > /dev/null 2>&1 &
|
|
453
|
+
|
|
454
|
+
exit 0
|
|
455
|
+
`};function gs(s){let{repoPath:e,enableAutoRefresh:t=!0,enableSymbolHealing:n=!0}=s,i=Qe.join(e,".git","hooks"),r=[],o=[],l=[];if(!re.existsSync(Qe.join(e,".git")))return l.push("Not a git repository"),{installed:r,skipped:o,errors:l};re.existsSync(i)||re.mkdirSync(i,{recursive:!0});let c=[];t&&c.push("post-merge","post-checkout"),n&&c.push("post-commit");for(let a of c){let p=Qe.join(i,a),d=pn[a];if(!d){l.push(`No template found for hook: ${a}`);continue}try{if(re.existsSync(p)){let u=re.readFileSync(p,"utf-8");if(u.includes("liquid-shadow")||u.includes("mcp-liquid-shadow")){o.push(a),st.info({hookName:a},"Hook already installed, skipping");continue}let m=`${p}.backup-${Date.now()}`;re.copyFileSync(p,m),st.info({hookName:a,backupPath:m},"Backed up existing hook")}re.writeFileSync(p,d,{mode:493}),r.push(a),st.info({hookName:a},"Installed git hook")}catch(u){l.push(`Failed to install ${a}: ${u}`),st.error({hookName:a,err:u},"Failed to install hook")}}return{installed:r,skipped:o,errors:l}}function ys(s){let e=Qe.join(s,".git","hooks"),t=[],n=[];if(!re.existsSync(e))return{removed:t,errors:n};let i=Object.keys(pn);for(let r of i){let o=Qe.join(e,r);try{if(re.existsSync(o)){let l=re.readFileSync(o,"utf-8");(l.includes("liquid-shadow")||l.includes("mcp-liquid-shadow"))&&(re.unlinkSync(o),t.push(r),st.info({hookName:r},"Removed git hook"))}}catch(l){n.push(`Failed to remove ${r}: ${l}`),st.error({hookName:r,err:l},"Failed to remove hook")}}return{removed:t,errors:n}}function un(s){let e=Qe.join(s,".git","hooks"),t=[],n=[];if(!re.existsSync(e))return{installed:t,notInstalled:Object.keys(pn)};let i=Object.keys(pn);for(let r of i){let o=Qe.join(e,r);if(re.existsSync(o)){let l=re.readFileSync(o,"utf-8");l.includes("liquid-shadow")||l.includes("mcp-liquid-shadow")?t.push(r):n.push(r)}else n.push(r)}return{installed:t,notInstalled:n}}var oi=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];searchHistoryFailureCount=0;recordIndexStart(){this.indexRuns+=1}recordIndexCacheHit(){this.indexCacheHits+=1}recordIndexEnd(e){this.lastIndexDurationMs=e,this.lastIndexCompletedAt=Date.now()}recordIndexPhase(e,t){this.lastRunPhases.push({phase:e,durationMs:t})}clearIndexPhases(){this.lastRunPhases=[]}recordQueryStart(){let e=performance.now();return()=>{this.queryCount+=1;let t=performance.now()-e;if(this.lastQueryLatencyMs=t,this.recentLatencies.push(t),this.recentLatencies.length>100){let n=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-n+t}else this.recentLatencySumMs+=t,this.recentLatencyCount=this.recentLatencies.length}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((n,i)=>n+i,0)/e:null;return{index:{runs:this.indexRuns,cacheHits:this.indexCacheHits,lastDurationMs:this.lastIndexDurationMs,lastCompletedAt:this.lastIndexCompletedAt,lastRunPhases:[...this.lastRunPhases]},query:{count:this.queryCount,lastLatencyMs:this.lastQueryLatencyMs,recentLatencySumMs:this.recentLatencySumMs,recentLatencyCount:e,avgLatencyMs:t,searchHistoryFailures:this.searchHistoryFailureCount},uptimeMs:Date.now()-this.startTime}}reset(){this.indexRuns=0,this.indexCacheHits=0,this.lastIndexDurationMs=null,this.lastIndexCompletedAt=null,this.lastRunPhases=[],this.queryCount=0,this.lastQueryLatencyMs=null,this.recentLatencySumMs=0,this.recentLatencyCount=0,this.recentLatencies=[],this.searchHistoryFailureCount=0}},De=new oi;function bs(){De.recordIndexStart()}function ai(){De.recordIndexCacheHit()}function Es(s){De.recordIndexEnd(s)}function dn(s,e){De.recordIndexPhase(s,e)}function Ss(){De.clearIndexPhases()}function mn(){return De.recordQueryStart()}function rt(){De.recordSearchHistoryFailure()}function _s(){return De.getSnapshot()}async function xs(s){let e=Ta.resolve(s);try{await U(async()=>{let t=k.getInstance(e),n=un(e),i=_s(),r=Math.floor(i.uptimeMs/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=l>0?`${l}h ${o%60}m`:o>0?`${o}m ${r%60}s`:`${r}s`,a=i.index.lastCompletedAt?new Date(i.index.lastCompletedAt).toLocaleString():"Never",p=i.index.lastDurationMs?`${(i.index.lastDurationMs/1e3).toFixed(2)}s`:"N/A",d=i.query.avgLatencyMs?`${i.query.avgLatencyMs.toFixed(2)}ms`:"N/A",u=i.query.lastLatencyMs?`${i.query.lastLatencyMs.toFixed(2)}ms`:"N/A",m=i.index.runs>0?(i.index.cacheHits/i.index.runs*100).toFixed(1):"0.0";te("Performance Metrics",`${f.bold("Uptime")}: ${f.cyan(c)}
|
|
456
|
+
${f.bold("Indexed")}: ${Ye(e)?f.green("Yes"):f.red("No")}
|
|
457
|
+
${f.bold("Files")}: ${f.cyan(t.files.getCount().toString())}
|
|
458
|
+
${f.bold("Exports")}: ${f.cyan(t.exports.getCount().toString())}
|
|
459
|
+
${f.bold("Imports")}: ${f.cyan(t.imports.getCount().toString())}
|
|
460
|
+
${f.bold("Last Indexed Commit")}: ${xt(e)?f.yellow(xt(e).substring(0,7)):f.red("None")}
|
|
461
|
+
${f.bold("Git Hooks")}: ${n.installed?f.green("Installed"):f.yellow("Not Installed")}`,"blue"),console.log(""),te("Index Metrics",`${f.bold("Total Runs")}: ${f.cyan(i.index.runs.toString())}
|
|
462
|
+
${f.bold("Cache Hits")}: ${f.cyan(i.index.cacheHits.toString())}
|
|
463
|
+
${f.bold("Cache Hit Rate")}: ${f.cyan(`${m}%`)}
|
|
464
|
+
${f.bold("Last Duration")}: ${f.yellow(p)}
|
|
465
|
+
${f.bold("Last Completed")}: ${f.yellow(a)}`,"cyan"),i.index.lastRunPhases.length>0&&(console.log(""),console.log(` ${f.bold("Last Index Run Phases:")}`),i.index.lastRunPhases.forEach(h=>{let b=`${(h.durationMs/1e3).toFixed(2)}s`;console.log(` ${f.gray(h.phase.padEnd(20))} ${f.cyan(b)}`)})),console.log(""),te("Query Metrics",`${f.bold("Total Queries")}: ${f.cyan(i.query.count.toString())}
|
|
466
|
+
${f.bold("Avg Latency")}: ${f.yellow(d)}
|
|
467
|
+
${f.bold("Last Latency")}: ${f.yellow(u)}
|
|
468
|
+
${f.bold("Search History Failures")}: ${i.query.searchHistoryFailures>0?f.red(i.query.searchHistoryFailures.toString()):f.green("0")}`,"green")})}finally{await G(e)}}import Xs from"path";N();import Qs from"path";import Qa from"ignore";import Ks from"fs";import hn from"path";var va=50;function wt(s,e,t,n){let i={name:hn.basename(e)||e,type:"directory",path:e,children:[]};return s.forEach(r=>{let l=hn.relative(e,r.path).split(hn.sep),c=i;for(let a=0;a<l.length;a++){let p=l[a];if(n!==void 0&&a>=n)return;let d=a===l.length-1;if(n===1&&a===0&&d)return;let u=n!==void 0&&a===n-1&&!d,m=hn.join(e,...l.slice(0,a+1)),h=c.children?.find(b=>b.name===p);if(!h){if(c.children&&c.children.length>=va){c.children.find(g=>g.type==="truncated")||c.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}h={name:p,type:d?"file":"directory",path:m,children:d||u?void 0:[],summary:d?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},h.summary&&(t==="structure"||t==="signatures")&&(delete h.summary.chunks,delete h.summary.imports),c.children?.push(h)}c=h}}),i}import wa from"fast-glob";import li from"fs";import Ia from"ignore";import Ts from"path";var fn=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],Rs=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"],ot={MAX_DEPTH:10,MIN_DEPTH:1,MAX_LIMIT:500,MIN_LIMIT:1,MAX_QUERY_LENGTH:500,DEFAULT_DEPTH:3,DEFAULT_LIMIT:10},oe={FILTERED_QUERY_LIMIT_MULTIPLIER:3,SCORE_BASE:1e3,EXACT_MATCH_BONUS:500,RECENT_FILE_BOOST:80,OLDER_FILE_BOOST:30,RECENT_FILE_THRESHOLD_DAYS:7,OLDER_FILE_THRESHOLD_DAYS:30,FUZZY_MATCH_LIMIT:30,ENABLE_LEXICAL_SCORING:process.env.ENABLE_LEXICAL_SCORING!=="false",LEXICAL_WEIGHT:parseFloat(process.env.LEXICAL_WEIGHT??String(.4)),GRAVITY_STRUCTURAL_WEIGHT:.5},ci={SECONDS_PER_DAY:86400,SECONDS_PER_YEAR:31536e3},gn={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function pi(s,e=[]){let t=Ia(),n=Ts.join(s,".gitignore");return li.existsSync(n)&&t.add(li.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await wa(Rs,{cwd:s,absolute:!0,ignore:fn})).filter(o=>{let l=Ts.relative(s,o);return!t.ignores(l)}).map(o=>({path:o,mtime:li.statSync(o).mtimeMs}))}import Na from"@swc/core";import mi from"fs";function vs(s){let e=s.split(`
|
|
469
|
+
`),t=[],n=0;for(let i of e)t.push(n),n+=i.length+1;return t}function J(s,e){for(let t=0;t<e.length;t++)if(e[t+1]>s||t===e.length-1)return t+1;return 1}function Y(s,e){return e.slice(0,s).toString("utf8").length}function ws(s,e,t){let n=s.start-e,i=s.end-e;return n<0||i>t.length?"":t.slice(n,i).toString("utf8")}function Is(s){let e=[],t=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=t.exec(s))!==null;)e.push({start:n.index,end:n.index+n[0].length,text:n[0]});return e}function Se(s,e,t){for(let n of e){if(n.start===s)return n.text;if(n.start>s&&n.start<s+50){let i=t.substring(s,n.start);if(/^\s*$/.test(i))return n.text}if(n.end<=s&&n.end>s-50){let i=t.substring(n.end,s);if(/^\s*$/.test(i))return n.text}}return""}function ks(s){if(!s)return"";let t=s.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
|
|
470
|
+
`)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function yn(s,e,t){let n=s.toLowerCase(),i=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||i.startsWith("use")?"Hook":n.includes("models/")||i.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||i.endsWith("service")||i.endsWith("controller")||i.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||i.endsWith("repository")||i.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function It(s){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(s)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(s)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(s)||/\.query\s*\(|\.execute\s*\(/i.test(s)&&/db|database|client|pool/i.test(s))&&e.push("Database"),(/\bfs\./i.test(s)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(s)||/import\s+.*\bfs\b/.test(s))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(s)||/\bdocument\.cookie\b/.test(s))&&e.push("Browser Storage"),e}function Ce(s,e){if(!s)return"";let t=s.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,i=0,r=t.length;for(let o=0;o<t.length;o++){let l=t[o];if(l==="(")n++;else if(l===")")n--;else if(l==="<")i++;else if(l===">")i--;else if(l==="{"){if(n===0&&i===0){r=o;break}}else if(l==="; "&&n===0&&i===0){r=o;break}else if(l==="="&&t[o+1]===">"&&n===0&&i===0){r=o+2;break}}return t.substring(0,r).trim()}function Cs(s){let e=[];for(let t of s)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join("","")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function Ls(s,e,t,n,i,r,o,l){let c=[];for(let a of s){if(a.type==="ExportDeclaration"){let p=a.declaration,d=p.type,u="";d==="VariableDeclaration"?u=p.declarations.map(y=>y.id.value).join("",""):u=p.id?.value||p.identifier?.value||"anonymous";let m=Y(a.span.start-e,t),h=Y(a.span.end-e,t),b=Se(m,r,n),E=l(a.span),g=[];if(a.type==="ExportDeclaration"&&(d==="ClassDeclaration"||d==="ClassExpression")){let y=p.body||[];for(let S of y)if(S.type==="ClassMethod"||S.type==="ClassProperty"){let w=S.key.value;if(!w)continue;let C=Y(S.span.start-e,t),T=Y(S.span.end-e,t),I=l(S.span),x=Se(C,r,n);g.push({name:w,kind:S.type,signature:Ce(I,S.type),line:J(C,i),endLine:J(T,i),doc:x,classification:S.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(d==="FunctionDeclaration"&&p.body?.type==="BlockStatement")g=ui(p.body.stmts,e,t,n,i,r,l);else if(d==="VariableDeclaration"){for(let y of p.declarations)if(y.init&&(y.init.type==="ArrowFunctionExpression"||y.init.type==="FunctionExpression")&&y.init.body?.type==="BlockStatement"){g=ui(y.init.body.stmts,e,t,n,i,r,l);break}}c.push({name:u,kind:d,signature:Ce(E,d),line:J(m,i),endLine:J(h,i),doc:b,classification:yn(o,u,d),capabilities:JSON.stringify(It(E)),members:g})}if(a.type==="ExportNamedDeclaration"){for(let p of a.specifiers)if(p.type==="ExportSpecifier"){let d=Y(a.span.start-e,t),u=Y(a.span.end-e,t),m=Se(d,r,n);c.push({name:p.exported?.value||p.orig.value,kind:"ExportSpecifier",signature:`export { ${p.orig.value} }`,line:J(d,i),endLine:J(u,i),doc:m,classification:"Export mapping",capabilities:"[]"})}}if(a.type==="ExportDefaultDeclaration"){let p=Y(a.span.start-e,t),d=Y(a.span.end-e,t),u=Se(p,r,n),m=l(a.span),h=[];if(a.decl.type==="ClassExpression"||a.decl.type==="ClassDeclaration"){let b=a.decl.body||[];for(let E of b)if(E.type==="ClassMethod"||E.type==="ClassProperty"){let g=E.key.value;if(!g)continue;let y=Y(E.span.start-e,t),S=Y(E.span.end-e,t),w=l(E.span),C=Se(y,r,n);h.push({name:g,kind:E.type,signature:Ce(w,E.type),line:J(y,i),endLine:J(S,i),doc:C,classification:E.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(a.decl.type==="FunctionExpression"||a.decl.type==="FunctionDeclaration"||a.decl.type==="ArrowFunctionExpression")&&a.decl.body?.type==="BlockStatement"&&(h=ui(a.decl.body.stmts,e,t,n,i,r,l));c.push({name:"default",kind:"DefaultExport",signature:Ce(m,"DefaultExport"),line:J(p,i),endLine:J(d,i),doc:u,classification:"Default Export",capabilities:JSON.stringify(It(m)),members:h})}if(a.type==="ExportAllDeclaration"){let p=Y(a.span.start-e,t),d=Y(a.span.end-e,t),u=a.source.value,m=Se(p,r,n);c.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${u}"`,line:J(p,i),endLine:J(d,i),doc:m,classification:"Re-export",capabilities:"[]"})}}return c}function ui(s,e,t,n,i,r,o){let l=[];for(let c of s){if(c.type==="VariableDeclaration")for(let a of c.declarations){let p=[],d=u=>{if(u.type==="Identifier")p.push({name:u.value,span:u.span});else if(u.type==="ArrayPattern")for(let m of u.elements)m&&d(m);else if(u.type==="ObjectPattern")for(let m of u.properties)m.type==="AssignmentPatternProperty"?p.push({name:m.key.value,span:m.span}):m.type==="KeyValuePatternProperty"&&d(m.value)};d(a.id);for(let u of p){let m=Y(u.span.start-e,t),h=Y(u.span.end-e,t),b=o(u.span),E=Se(m,r,n);l.push({name:u.name,kind:"VariableDeclaration",signature:Ce(b,"VariableDeclaration"),line:J(m,i),endLine:J(h,i),doc:E,classification:"Internal Variable",capabilities:"[]"})}}if(c.type==="FunctionDeclaration"){let a=c.identifier?.value||c.ident?.value||"anonymous",p=Y(c.span.start-e,t),d=Y(c.span.end-e,t),u=o(c.span),m=Se(p,r,n);l.push({name:a,kind:"FunctionDeclaration",signature:Ce(u,"FunctionDeclaration"),line:J(p,i),endLine:J(d,i),doc:m,classification:"Internal Function",capabilities:"[]"})}if(c.type==="ReturnStatement"&&c.argument?.type==="ObjectExpression")for(let a of c.argument.properties){let p="",d=a.span||a.key?.span||a.ident?.span;if(a.type==="KeyValueProperty"){let u=a.key;p=u?.value||u?.raw||(u?.type==="Identifier"?u.value:"")}else a.type==="MethodProperty"?p=a.key?.value||a.key?.raw||"":a.type==="ShorthandProperty"?p=a.ident?.value||"":a.type==="Identifier"&&(p=a.value||"");if(p&&d){let u=Y(d.start-e,t),m=Y(d.end-e,t),h=o(d),b=Se(u,r,n);l.push({name:p,kind:"ReturnProperty",signature:Ce(h,"ReturnProperty"),line:J(u,i),endLine:J(m,i),doc:b,classification:"Return Member",capabilities:"[]"})}}if(c.type==="ExpressionStatement"&&c.expression.type==="CallExpression"){let a=c.expression;if(a.callee.type==="MemberExpression"&&(a.callee.property?.value==="on"||a.callee.property?.value==="once")){let p=a.arguments[0]?.expression?.value,d=a.arguments[1]?.expression;if(p&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let u=Y(d.span.start-e,t),m=Y(d.span.end-e,t),h=o(d.span);l.push({name:`on:${p}`,kind:d.type,signature:Ce(h,d.type),line:J(u,i),endLine:J(m,i),doc:"",classification:"Event Handler",capabilities:"[]"})}}}}return l}function $s(s,e,t,n,i){let r=[];function o(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let c=ka(l);if(c){let a=Y(l.span.start-e,t);r.push({...c,line:J(a,n),snippet:i(l.span)})}}for(let c of Object.keys(l)){if(c==="span")continue;let a=l[c];Array.isArray(a)?a.forEach(o):typeof a=="object"&&o(a)}}}return s.forEach(o),r}function ka(s){let{callee:e,arguments:t}=s;if(!t||t.length===0)return null;if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};let i=["get","post","put","delete","patch"];if(i.includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value;if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}if(i.includes(n)&&t[0].expression.type==="StringLiteral"&&e.object.type==="Identifier"&&["axios","http","request"].includes(e.object.value))return{type:"api_route",name:t[0].expression.value,direction:"produce"}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function kt(s){let{classification:e,capabilities:t,exports:n,fileName:i}=s,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(h=>r[h]).filter(Boolean).join(" and "),c={Component:(h,b)=>{let E=b.find(y=>y.kind==="FunctionDeclaration"||y.kind==="ClassDeclaration")?.name,g=E?`React component: ${E}`:"React UI component";return h?`${g} with ${h}`:g},Hook:(h,b)=>{let E=b.find(y=>y.name.startsWith("use"))?.name,g=E?`Custom React hook: ${E}`:"Custom React hook";return h?`${g} for ${h}`:g},Service:(h,b)=>{let g=`Service layer: ${b[0]?.name||"Service"}`;return h?`${g} handling ${h}`:g},Repository:(h,b)=>`Data repository: ${b[0]?.name||"Repository"} for ${h||"data access"}`,"Type Definition":(h,b)=>`Type definitions: ${b.slice(0,3).map(g=>g.name).join("")}${b.length>3?"...":""}`,Model:(h,b)=>`Data model: ${b[0]?.name||"Model"}`,"HTTP Route":(h,b)=>{let E=b.filter(g=>g.classification==="Service Boundary");return E.length>0?`API endpoints: ${E.slice(0,3).map(g=>g.name).join("")}`:"API route handler"},"Micro IR (PHP)":(h,b)=>{let E=b.some(y=>y.classification==="Service Boundary"),g=b.find(y=>y.kind==="ClassDeclaration")?.name;return E?"PHP controller with API routes":g?`PHP class: ${g}`:"PHP module"},"Micro IR (Python)":(h,b)=>{let E=b.some(y=>y.classification==="Service Boundary"),g=b.find(y=>y.kind==="ClassDeclaration")?.name;return E?"Python API handler with routes":g?`Python class: ${g}`:"Python module"},"Micro IR (Go/TS) ":(h,b)=>{let E=b.some(y=>y.kind==="TypeDeclaration"),g=b.filter(y=>y.kind==="FunctionDeclaration");return E&&g.length>0?`Go package: types and ${g.length} function(s)`:E?"Go package: type definitions":g.length>0?`Go package: ${g[0].name} and ${g.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(h,b)=>{let E=b.find(S=>S.kind==="TraitDeclaration")?.name,g=b.find(S=>S.kind==="StructDeclaration")?.name,y=b.filter(S=>S.kind==="FunctionDeclaration");return E?h.includes("Rust trait")?`Rust module: trait ${E}`:`Rust module: ${E}`:g?`Rust module: struct ${g}`:y.length>0?`Rust module: ${y.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return i?`Module: ${i}`:"Module with no exports";let a=n.filter(h=>h.kind==="FunctionDeclaration"),p=n.filter(h=>h.kind==="ClassDeclaration"),d=n.filter(h=>h.kind==="TsInterfaceDeclaration"||h.kind==="TsTypeAliasDeclaration"),u=[];if(p.length>0&&u.push(`Class: ${p[0].name}`),a.length>0){let h=a.slice(0,2).map(b=>b.name).join("");u.push(`Functions: ${h}`)}d.length>0&&u.push(`Types: ${d.length}`);let m=u.length>0?u.join(" | "):`Module with ${n.length} export(s)`;return o?`${m} \u2014 ${o}`:m}function Ns(s){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&Q(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&Q(n,e);for(let i in n){if(i==="span"||i==="comments"||i==="interpreter")continue;let r=n[i];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return s.forEach(n=>t(n)),Array.from(e)}function Q(s,e){if(s){if(s.type==="TsTypeAnnotation"){Q(s.typeAnnotation,e);return}s.type==="TsTypeReference"&&(s.typeName?.type==="Identifier"&&e.add(s.typeName.value),s.typeName?.type==="TsQualifiedName"&&As(s.typeName,e),s.typeParams&&Q(s.typeParams,e)),s.type==="TsArrayType"&&Q(s.elementType,e),s.type==="TsUnionType"&&s.types?.forEach(t=>Q(t,e)),s.type==="TsIntersectionType"&&s.types?.forEach(t=>Q(t,e)),s.type==="TsTupleType"&&s.elemTypes?.forEach(t=>Q(t.ty,e)),(s.type==="TsFunctionType"||s.type==="TsConstructorType")&&(s.params?.forEach(t=>Q(t.typeAnnotation,e)),s.typeAnnotation&&Q(s.typeAnnotation,e)),s.type==="TsTypeParameterDeclaration"&&s.params?.forEach(t=>{t.constraint&&Q(t.constraint,e),t.default&&Q(t.default,e)}),s.type==="TsTypeParameterInstantiation"&&s.params?.forEach(t=>Q(t,e)),s.type==="TsMappedType"&&s.typeAnnotation&&Q(s.typeAnnotation,e),s.type==="TsIndexedAccessType"&&(Q(s.objectType,e),Q(s.indexType,e)),s.type==="TsConditionalType"&&(Q(s.checkType,e),Q(s.extendsType,e),Q(s.trueType,e),Q(s.falseType,e)),s.type==="TsTypeLiteral"&&s.members?.forEach(t=>{t.typeAnnotation&&Q(t.typeAnnotation,e)})}}function As(s,e){s.type==="TsQualifiedName"?(s.left&&As(s.left,e),s.right?.value&&e.add(s.right.value)):s.type==="Identifier"&&e.add(s.value)}import Os from"path";import di from"path";N();import Ps from"path";import Ca from"fs";import{fileURLToPath as La}from"url";import*as Ke from"web-tree-sitter";var Ru=Ps.dirname(La(import.meta.url)),Ms=_.child({module:"parser:tree-sitter"}),bn=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=Ke.Parser||Ke;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=an("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!Ca.existsSync(t))return Ms.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await Ke.Language.load(t);return this.languages.set(e,n),n}catch(n){return Ms.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
|
|
471
|
+
(function_definition name: (name) @name) @func
|
|
472
|
+
(class_declaration name: (name) @name) @class
|
|
473
|
+
(interface_declaration name: (name) @name) @interface
|
|
474
|
+
(trait_declaration name: (name) @name) @trait
|
|
475
|
+
(method_declaration name: (name) @name) @method
|
|
476
|
+
(namespace_use_declaration (namespace_use_clause (qualified_name) @name)) @import
|
|
477
|
+
`;case".py":return`
|
|
478
|
+
(function_definition name: (identifier) @name) @func
|
|
479
|
+
(class_definition name: (identifier) @name) @class
|
|
480
|
+
(import_statement name: (dotted_name) @name) @import
|
|
481
|
+
(import_from_statement module_name: (dotted_name) @name) @import
|
|
482
|
+
`;case".go":return`
|
|
483
|
+
(function_declaration name: (identifier) @name) @func
|
|
484
|
+
(method_declaration name: (identifier) @name) @func
|
|
485
|
+
(type_declaration (type_spec name: (identifier) @name)) @type
|
|
486
|
+
(import_spec path: (interpreted_string_literal) @name) @import
|
|
487
|
+
`;case".rs":return`
|
|
488
|
+
(function_item name: (identifier) @name) @func
|
|
489
|
+
(struct_item name: (_type_identifier) @name) @struct
|
|
490
|
+
(enum_item name: (_type_identifier) @name) @enum
|
|
491
|
+
(trait_item name: (_type_identifier) @name) @trait
|
|
492
|
+
(type_item name: (_type_identifier) @name) @type
|
|
493
|
+
(use_declaration argument: (_) @name) @import
|
|
494
|
+
`;default:return""}}mapKind(e,t){if(e==="import")return"ImportDeclaration";if(t===".php"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration";if(e==="interface")return"InterfaceDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="method")return"MethodDeclaration"}if(t===".py"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration"}if(t===".go"){if(e==="func")return"FunctionDeclaration";if(e==="type")return"TypeDeclaration"}if(t===".rs"){if(e==="func")return"FunctionDeclaration";if(e==="struct")return"StructDeclaration";if(e==="enum")return"EnumDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(e){return e==="import"?"Dependency":e==="func"||e==="method"?"Function":e==="class"||e==="interface"||e==="trait"||e==="struct"||e==="enum"||e==="type"?"Class":"Other"}async parse(e,t){await this.ensureInitialized();let n=Ps.extname(e).toLowerCase(),i=await this.getLanguage(n);if(!i||!this.parser)return[];this.parser.setLanguage(i);let r=this.parser.parse(t),o=t.split(`
|
|
495
|
+
`),l=this.getQueries(n);if(!l)return[];let a=new Ke.Query(i,l).matches(r.rootNode),p=[];for(let d of a){let u=d.captures.find(b=>b.name==="name")?.node,m=d.captures[0].node,h=d.captures[0].name;if(u){let b=m.startPosition.row+1,E=m.endPosition.row+1,g=o[m.startPosition.row].trim();p.push({name:u.text,kind:this.mapKind(h,n),classification:this.mapClassification(h),signature:g,line:b,endLine:E,doc:"",capabilities:"{}"})}}return p}};var En=class{parse(e,t=!1){let n=[],i=[],r=e.split(`
|
|
496
|
+
`),o="",l="",c=0,a=0,p=-1,d=-1,u=[],m=[],h=!1,b=t?"api":"",E="",g=/^namespace\s+([a-zA-Z0-9_\\]+);/,y=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,S=/^interface\s+([a-zA-Z0-9_]+)/,w=/^trait\s+([a-zA-Z0-9_]+)/,C=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,T=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,I=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,x=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,$=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let R=0;R<r.length;R++){let v=r[R].trim();if(!v)continue;let P=(v.match(/{/g)||[]).length,L=(v.match(/}/g)||[]).length,H=a;if(a+=P-L,l&&a<=d){let O=n.find(A=>A.name===l&&A.line===c);O&&(O.endLine=R+1),l="",d=-1}if(o&&a<=p){let O=n.find(A=>A.name===o&&(A.kind==="ClassDeclaration"||A.kind==="TraitDeclaration"||A.kind==="InterfaceDeclaration"));O&&(O.endLine=R+1),o="",p=-1}let B=v.match($);if(B&&(b=B[1]),v.includes("});")&&(b=""),v.startsWith("/**")){h=!0,m=[];continue}if(h){v.endsWith("*/")?h=!1:m.push(v.replace(/^\*\s?/,""));continue}let ne=v.match(I);if(ne){u.push(ne[1]);continue}let W=v.match(g);if(W){E=W[1]||"",u=[],m=[];continue}let D=v.match(y);if(D){o=D[1],p=a-P;let O={attributes:u};E&&(O.namespace=E),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:R+1,endLine:R+1,doc:m.join(`
|
|
497
|
+
`).trim(),capabilities:JSON.stringify(O),members:[]}),u=[],m=[];continue}let M=v.match(S);if(M){let O=M[1];o=O,p=a-P,n.push({name:O,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${O}`,line:R+1,endLine:R+1,doc:m.join(`
|
|
498
|
+
`).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let ce=v.match(w);if(ce){let O=ce[1];o=O,p=a-P,n.push({name:O,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${O}`,line:R+1,endLine:R+1,doc:m.join(`
|
|
499
|
+
`).trim(),capabilities:JSON.stringify({attributes:u}),members:[]}),u=[],m=[];continue}let Et=v.match(C);if(Et){let O=Et[1],A=!!o;l=O,c=R+1,d=a-P;let Je=!1,Te={};for(let ie of u)ie.toLowerCase().includes("route")&&(Je=!0,Te={type:"route",method:"GET",path:"/"});let ve=m.join(`
|
|
500
|
+
`).trim();if(Je){let ie=Te.path||"/";n.push({name:ie,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${O}`,line:R+1,endLine:R+1,doc:ve,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${O}`:O,...Te})}),i.push({type:"api_route",name:ie,direction:"consume",line:R+1,snippet:v})}n.push({name:O,kind:A?"MethodDeclaration":"FunctionDeclaration",classification:A?"Method":"Function",signature:`${A?o+":: ":""}${O}`,line:R+1,endLine:R+1,doc:ve,capabilities:JSON.stringify({attributes:u})}),u=[],m=[];continue}let Ge=v.match(T);if(Ge){let O=Ge[1]||"",A=Ge[2]||O.split("\\").pop()||"";n.push({name:A,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${O}`,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:O})}),u=[],m=[];continue}let nt=v.match(x);if(nt){let O=nt[1].toUpperCase(),A=nt[2];if(v.includes("Route::")||v.includes("router->")||v.includes("action")||v.includes(",")&&!v.includes("view(")){if(b){let Ae=b.startsWith("/")?b:`/${b}`,qn=A.startsWith("/")?A:`/${A}`;A=(Ae+qn).replace(/\/+/g,"/")}let Te=null,ve=v.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(ve)Te=`${ve[1]}@${ve[2]}`;else if(v.includes("::class")){let Ae=v.match(/([a-zA-Z0-9_]+)::class/);Ae&&(Te=Ae[1])}let ie=v;!v.endsWith(");")&&R+1<r.length&&(ie+=" "+r[R+1].trim(),!ie.endsWith(");")&&R+2<r.length&&(ie+=" "+r[R+2].trim())),n.push({name:A,kind:"HTTP Route",classification:"Service Boundary",signature:ie,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"route",method:O,path:A,handler:Te})}),i.push({type:"api_route",name:A,direction:"consume",line:R+1,snippet:ie,method:O,url:A}),m=[];continue}}let jt=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,qe=v.match(jt);if(qe){let O=(qe[1]||qe[3]).toUpperCase(),A=(qe[2]||qe[4]).trim();(A.startsWith("'")&&A.endsWith("'")||A.startsWith('"')&&A.endsWith('"'))&&(A=A.substring(1,A.length-1)),i.push({type:"api_route",name:A,direction:"produce",line:R+1,snippet:v,method:O,url:A})}!v.startsWith("#[")&&!v.startsWith("//")&&!v.startsWith("*")&&!h&&(u=[],m=[])}return{nodes:n,events:i}}};var Sn=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],i=e.split(`
|
|
501
|
+
`),r=[{indent:-1,name:"root",type:"root"}],o=[],l=/^class\s+([a-zA-Z0-9_]+)/,c=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,a=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,p=/^@(.*)/;function d(g){return g.trim().split(/[.(]/)[0]?.trim()||g}function u(g){let y=g.decorators.map(w=>d(w.raw)),S={decorators:g.decorators,decoratorNames:y};return g.async===!0&&(S.async=!0),JSON.stringify(S)}let m=!1,h="",b=[],E=[];for(let g=0;g<i.length;g++){let y=i[g],S=y.trim();if(!S||S.startsWith("#"))continue;let w=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,C=S.match(w);if(C&&(this.currentRoutePrefix=C[2]),m){if(S.endsWith(h)||S.includes(h)){m=!1;let D=S.replace(h,"").trim();D&&b.push(D);let M=r[r.length-1];M.node&&(M.node.doc=b.join(`
|
|
502
|
+
`).trim()),b=[]}else b.push(S);continue}let T=y.search(/\S/),I=y.trim(),x=I.match(/^(['"]{3})/);if(x){let D=x[1],M=r[r.length-1];if(M.node&&!M.node.doc){if(I.substring(3).includes(D)){let ce=I.replace(new RegExp(D,"g"),"").trim();M.node.doc=ce}else{m=!0,h=D;let ce=I.substring(3).trim();ce&&b.push(ce)}continue}}for(;r.length>1&&r[r.length-1].indent>=T;)r.pop();let $=r[r.length-1],R=I.match(p);if(R){o.push({raw:R[1].trim(),line:g+1});continue}let v=I.match(l);if(v){let D=v[1],M={name:D,kind:"ClassDeclaration",classification:"Class",signature:`class ${D}`,line:g+1,endLine:g+1,doc:"",capabilities:u({decorators:o}),members:[]};E.push(M),$.node?($.node.members||($.node.members=[]),$.node.members.push(M)):t.push(M),r.push({indent:T,name:D,type:"class",node:M}),o=[];continue}let P=I.match(c);if(P){let D=!!P[1],M=P[1]||P[2],ce=$.type==="class",Et=!1,Ge={};for(let A of o)if(A.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){Et=!0;let Te=["get","post","put","delete","patch"].find(Ae=>A.raw.toLowerCase().includes(`.${Ae}`))?.toUpperCase()||"GET",ve=A.raw.match(/['"]([^'"]+)['"]/),ie=ve?ve[1]:"/";if(this.currentRoutePrefix){let Ae=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,qn=ie.startsWith("/")?ie:`/${ie}`;ie=Ae+qn}Ge={type:"route",method:Te,path:ie}}if(Et){let A=Ge.path||"",Je={name:A||M,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${M}`,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({handler:ce?`${$.name}.${M}`:M,async:D,...Ge})};E.push(Je),t.push(Je),n.push({type:"api_route",name:A,direction:"consume",line:g+1,snippet:I})}let nt=o.some(A=>A.raw==="staticmethod"),jt=o.some(A=>A.raw==="classmethod"),qe=`${D?"async ":""}${ce?(nt?"@staticmethod ":jt?"@classmethod ":"")+$.name+".":""}${M}`,O={name:M,kind:D&&ce?"AsyncMethodDeclaration":D?"AsyncFunctionDeclaration":ce?"MethodDeclaration":"FunctionDeclaration",classification:ce?nt||jt?"Static Method":"Method":"Function",signature:qe,line:g+1,endLine:g+1,doc:"",capabilities:u({decorators:o,async:D}),members:[]};E.push(O),$.node?($.node.members||($.node.members=[]),$.node.members.push(O)):t.push(O),r.push({indent:T,name:M,type:"function",node:O}),o=[];continue}let L=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,H=I.match(L);if(H){let D=H[1].replace(/^\^/,""),M={name:D,kind:"HTTP Route",classification:"Service Boundary",signature:I.trim(),line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:D})};E.push(M),t.push(M),n.push({type:"api_route",name:D,direction:"consume",line:g+1,snippet:I});continue}let B=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,ne=I.match(B);if(ne){let D=ne[1].toUpperCase(),M=ne[2].trim();(M.startsWith("'")&&M.endsWith("'")||M.startsWith('"')&&M.endsWith('"'))&&(M=M.substring(1,M.length-1)),n.push({type:"api_route",name:M,direction:"produce",line:g+1,snippet:I,method:D,url:M})}let W=I.match(a);if(W){let D=W[1]||W[2],M={name:D,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${D}`,line:g+1,endLine:g+1,doc:"",capabilities:JSON.stringify({type:"import",module:D})};E.push(M),t.push(M),o=[];continue}o=[],$.node&&($.node.endLine=g+1)}return{nodes:E,events:n}}};var Ds=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function",signature:s[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:s=>({name:s[1],kind:"MethodDeclaration",classification:"Method",signature:s[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:s=>({name:s[1],kind:"ImportSpecifier",classification:"Dependency",signature:s[0],meta:{type:"import",path:s[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function",signature:s[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"StructDeclaration",classification:"Class",signature:s[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"EnumDeclaration",classification:"Class",signature:s[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"TraitDeclaration",classification:"Class",signature:s[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:s=>({name:s[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:s[0],meta:{type:"import",path:s[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:s=>({name:s[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:s=>({name:s[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:s=>({name:s[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:s=>({name:s[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:s[1]}})}]}];function $a(s,e){let t=[];if(s===".go"&&e.some(n=>n.kind==="TypeDeclaration")&&t.push("Go type"),s===".rs"&&(e.some(n=>n.kind==="TraitDeclaration")&&t.push("Rust trait"),e.some(n=>n.kind==="StructDeclaration")&&t.push("Rust struct"),e.some(n=>n.kind==="EnumDeclaration")&&t.push("Rust enum")),s===".py"){for(let n of e)if(n.capabilities)try{if(JSON.parse(n.capabilities).decoratorNames?.length){t.push("Python decorators");break}}catch{}e.some(n=>n.kind==="AsyncFunctionDeclaration"||n.kind==="AsyncMethodDeclaration")&&t.push("Async")}return t}var _n=class{phpParser=new En;pythonParser=new Sn;treeSitterParser=new bn;supports(e){return Ds.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=di.extname(e).toLowerCase(),i=[],r=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let c=this.pythonParser.parse(t);i=c.nodes,r=c.events}else if(n===".php"){let c=e.toLowerCase().endsWith("api.php"),a=this.phpParser.parse(t,c);i=a.nodes,r=a.events}else try{i=await this.treeSitterParser.parse(e,t)}catch{}if(i.length>0){let c=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",a=i.filter(m=>m.classification!=="Dependency"),p=i.filter(m=>m.classification==="Dependency"),d=$a(n,i),u=kt({classification:c,capabilities:d,exports:a.map(m=>({name:m.name,kind:m.kind,classification:m.classification})),fileName:di.basename(e)});return{exports:a,imports:p.map(m=>({module:m.name,name:m.name,kind:m.kind,classification:m.classification})),events:r,classification:c,summary:u||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Ds.find(c=>c.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};for(let c of o.rules){c.regex.lastIndex=0;let a;for(;(a=c.regex.exec(t))!==null;){let p=c.onMatch(a),d=t.substring(0,a.index).split(`
|
|
503
|
+
`).length;i.push({name:p.name||"anonymous",kind:p.kind||"Unknown",classification:p.classification||"Other",signature:p.signature||a[0],line:d,endLine:d,doc:"",capabilities:JSON.stringify(p.meta||{})})}}let l=kt({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:i.map(c=>({name:c.name,kind:c.kind,classification:c.classification})),fileName:di.basename(e)});return{exports:i,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:l||"Module",parseStatus:i.length>0?"success":"partial"}}};N();var hi=new _n;async function Ct(s){let e=Os.extname(s);if(hi.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=mi.readFileSync(s,"utf-8");return await hi.parse(s,r)}catch(r){return _.error({filePath:s,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:r.message}}let t;try{t=mi.readFileSync(s)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),i=vs(n);try{let r=s.endsWith(".tsx"),o=Na.parseSync(n,{syntax:"typescript",tsx:r,decorators:!0,comments:!0}),l=o.span.start,c=Is(n),a=g=>ws(g,l,t),p=Cs(o.body),d=Ns(o.body);d.length>0&&_.debug({filePath:s,count:d.length},"Extracted type references"),d.forEach(g=>{p.push({module:"__type_reference__",name:g})});let u=Ls(o.body,l,t,n,i,c,s,a),m=$s(o.body,l,t,i,a),h=yn(s,"","Module"),b=c.length>0&&c[0].start===0?c[0].text:u.find(g=>g.doc)?.doc||"",E=ks(b);if(!E&&u.length>0){let g=It(n);E=kt({classification:h,capabilities:g,exports:u.map(y=>({name:y.name,kind:y.kind,classification:y.classification})),fileName:Os.basename(s)})}return{exports:u,imports:p,events:m,classification:h,summary:E,parseStatus:"success"}}catch(r){_.warn({filePath:s,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=mi.readFileSync(s,"utf-8"),l=await hi.parse(s,o);return{...l,classification:l.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return _.error({filePath:s,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}N();import Vs from"p-limit";Ve();import Ja from"path";import yi from"fs";import Ya from"os";import he from"path";import ct from"fs";import{loadConfig as Ma,createMatchPath as Pa}from"tsconfig-paths";import Oe from"path";import Lt from"fs";var Fe=class extends Error{constructor(t,n,i){super(n);this.code=t;this.cause=i;this.name="FileSystemError"}};function Fs(s){let e;try{e=Lt.statSync(s).isDirectory()?s:Oe.dirname(s)}catch(t){throw t.code==="ENOENT"?new Fe("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new Fe("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new Fe("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==Oe.dirname(e);){let t=Oe.join(e,"tsconfig.json");if(Lt.existsSync(t))return e;e=Oe.dirname(e)}return null}function Hs(s){let e;try{e=Lt.statSync(s).isDirectory()?s:Oe.dirname(s)}catch(t){throw t.code==="ENOENT"?new Fe("FILE_NOT_FOUND",`Start path does not exist: ${s}`,t):t.code==="EACCES"||t.code==="EPERM"?new Fe("PERMISSION_DENIED",`Permission denied accessing: ${s}`,t):new Fe("UNKNOWN",`Failed to access path: ${s}`,t)}for(;e!==Oe.dirname(e);){let t=Oe.join(e,"package.json");if(Lt.existsSync(t))try{if(JSON.parse(Lt.readFileSync(t,"utf8")).workspaces)return e}catch{}e=Oe.dirname(e)}return null}import at from"path";import Xe from"fs";function Ws(s,e){let t=new Map,n=e.workspaces||[];for(let i of n){let r=i.replace("/*",""),o=at.join(s,r);if(!Xe.existsSync(o))continue;let l=Xe.readdirSync(o);for(let c of l){let a=at.join(o,c,"package.json");if(Xe.existsSync(a))try{let p=JSON.parse(Xe.readFileSync(a,"utf8"));p.name&&t.set(p.name,{name:p.name,path:at.dirname(a),main:p.main||"dist/index.js"})}catch{}}}return t}function Us(s){let e=new Map;try{let t=JSON.parse(Xe.readFileSync(s,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[i,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),l=at.dirname(s),c=at.resolve(l,o),a=at.join(c,"package.json");if(Xe.existsSync(a))try{let p=JSON.parse(Xe.readFileSync(a,"utf8"));e.set(i,{name:i,path:c,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import js from"path";import me from"fs";var Aa=[".ts",".tsx",".d.ts",".js",".jsx"];function He(s){let e=js.extname(s);if(e===".js"||e===".jsx"){let t=s.slice(0,-e.length),n=e===".jsx"?[".tsx",".ts"]:[".ts",".tsx"];for(let i of n){let r=t+i;if(me.existsSync(r)&&me.statSync(r).isFile())return r}if(me.existsSync(s)&&me.statSync(s).isFile())return s}if(me.existsSync(s)&&me.statSync(s).isFile())return s;for(let t of Aa){let n=s+t;if(me.existsSync(n)&&me.statSync(n).isFile())return n}if(me.existsSync(s)&&me.statSync(s).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=js.join(s,"index"+t);if(me.existsSync(n))return n}return""}var Rn=new Map;function xn(s){let e=Fs(s);if(!e)return null;if(Rn.has(e))return Rn.get(e)||null;let t=Ma(e);if(t.resultType==="failed")return Rn.set(e,null),null;let n=t,i=n.absoluteBaseUrl;!i&&n.paths&&Object.keys(n.paths).length>0&&(i=n.configFileAbsolutePath?he.dirname(n.configFileAbsolutePath):e);let r=Pa(i,n.paths,n.mainFields,n.addMatchAll),o=Hs(e),l=new Map;if(o){let d=he.join(o,"package.json");if(ct.existsSync(d))try{let u=JSON.parse(ct.readFileSync(d,"utf8"));l=Ws(o,u)}catch{}}let c=he.join(e,"package.json");ct.existsSync(c)&&Us(c).forEach((u,m)=>l.set(m,u));let a={baseUrl:i||"",paths:n.paths,matchPath:r,workspacePackages:l,imports:new Map},p=he.join(e,"package.json");if(ct.existsSync(p))try{let d=JSON.parse(ct.readFileSync(p,"utf8"));if(d.imports){for(let[u,m]of Object.entries(d.imports))if(typeof m=="string"||typeof m=="object"&&m!==null){let h=m;Array.isArray(m)&&(h=m[0]),typeof h=="object"&&(h=h.default||h.node),typeof h=="string"&&a.imports.set(u,h)}}}catch{}return Rn.set(e,a),a}function $t(s,e,t){if(!s)return"";if(s.includes(".")&&!s.startsWith(".")&&!s.startsWith("/")&&!s.endsWith(".js")&&!s.endsWith(".ts")&&!s.endsWith(".json")){let i=s.split(".")[0];if(i&&i!==s){let r=$t(i,e,t);if(r)return r}}if(s.startsWith(".")){let i=he.dirname(e),r=he.resolve(i,s);return He(r)}let n=xn(e);if(n){let i=n.matchPath(s);if(i)return He(i);if(!s.startsWith("@")||s.startsWith("@/")){let o=he.resolve(n.baseUrl,s),l=He(o);if(l)return l}for(let[o,l]of n.imports.entries())if(o.includes("*")){let c="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",a=new RegExp(c),p=s.match(a);if(p){let d=p[1],u=l.replace("*",d),m=he.resolve(n.baseUrl,u);return He(m)}}else if(o===s){let c=he.resolve(n.baseUrl,l);return He(c)}let r=n.workspacePackages.get(s);if(r){let o=he.join(r.path,"src/index.ts");if(ct.existsSync(o))return o;let l=he.join(r.path,r.main),c=He(l);if(c)return c}}return""}import Da from"fs";import Oa from"path";import zs from"js-yaml";function Bs(s){let e=Oa.basename(s),t=Da.readFileSync(s,"utf8"),n=[];if(e.endsWith(".prisma"))return Ua(t,s);if(e.endsWith(".graphql")||e.endsWith(".gql"))return ja(t,s);let i="Configuration";return e==="lerna.json"?za(t,s):e==="turbo.json"?Ga(t,s):e==="pnpm-workspace.yaml"?qa(t,s):(e.includes("Dockerfile")?(i="Infrastructure (Docker) ",Fa(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(i="Infrastructure (YAML) ",Ha(t,n)):e.startsWith(".env")?(i="Configuration (Env) ",Wa(t,n)):e==="package.json"&&(i="Project Manifest",Ba(t,n)),{configs:n,classification:i})}function Fa(s,e){let t=s.split(`
|
|
504
|
+
`);for(let n of t){let i=n.trim();if(i.startsWith("FROM "))e.push({key:"base_image",value:i.substring(5).trim(),kind:"Image"});else if(i.startsWith("EXPOSE "))e.push({key:"port",value:i.substring(7).trim(),kind:"Port"});else if(i.startsWith("ENV ")){let r=i.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],l=r.slice(1).join("= ").trim()||"undefined",c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function Ha(s,e){try{let t=zs.load(s);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[i,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${i}`,value:i,kind:"Service"}),o.image&&e.push({key:`service:${i}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(l=>{e.push({key:`service:${i}:port`,value:String(l),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(l=>{let[c,...a]=l.split("= ");c&&a.length>0&&e.push({key:`service:${i}:env:${c}`,value:a.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[l,c]of Object.entries(o.environment))e.push({key:`service:${i}:env:${l}`,value:String(c),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(l=>{e.push({key:`service:${i}:depends_on`,value:l,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let l of Object.keys(o.depends_on))e.push({key:`service:${i}:depends_on`,value:l,kind:"Dependency"})}let n=(i,r="")=>{if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,l]of Object.entries(i)){let c=r?`${r}.${o}`:o;if(t.services&&(c.startsWith("services.")||c==="services")){l&&typeof l=="object"&&!Array.isArray(l)&&n(l,c);continue}if(l&&typeof l=="object"&&!Array.isArray(l))n(l,c);else{let a=String(l),p="Env";o.toLowerCase().includes("image")&&(p="Image"),o.toLowerCase().includes("port")&&(p="Port"),o.toLowerCase().includes("service")&&(p="Service"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(p="Service"),e.push({key:c,value:a.length>100?a.substring(0,97)+"...":a,kind:p})}}};n(t)}catch{let n=s.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(i=>{let r=i.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function Wa(s,e){let t=s.split(`
|
|
505
|
+
`);for(let n of t){let i=n.trim();if(i&&!i.startsWith("#")){let r=i.split("=");if(r[0]){let o=r[0].trim(),l=r.slice(1).join("=");l=l.trim().replace(/^['"](.*)['"]$/,"$1");let c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function Ua(s,e){let t=[],n="Contract (Prisma) ",i=/^model\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(s))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let l=/provider\s*=\s*"([^"]+)"/,c=s.match(l);return c&&t.push({key:"datasource_provider",value:c[1],kind:"Database Config"}),{classification:n,configs:t}}function ja(s,e){let t=[],n="Contract (GraphQL) ",i=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=i.exec(s))!==null;){let o=r[0],l="GraphQL Type";o.startsWith("input")&&(l="GraphQL Input"),o.startsWith("interface")&&(l="GraphQL Interface"),o.startsWith("enum")&&(l="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:l})}return{classification:n,configs:t}}function Ba(s,e){try{let t=JSON.parse(s);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"Service"}),t.workspaces){let r=Array.isArray(t.workspaces)?t.workspaces.join("",""):JSON.stringify(t.workspaces);e.push({key:"workspaces",value:r,kind:"Env"})}if(t.scripts){let r=["start","dev","build","test","docker"];for(let o of Object.keys(t.scripts))r.some(l=>o.includes(l))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},i=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(i.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Service"})}}catch{}}function za(s,e){let t=[],n="Monorepo (Lerna) ";try{let i=JSON.parse(s);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),i.version&&t.push({key:"lerna_version",value:i.version,kind:"Monorepo"}),i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),i.npmClient&&t.push({key:"npm_client",value:i.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n}}function Ga(s,e){let t=[],n="Monorepo (Turborepo) ";try{let i=JSON.parse(s);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),i.pipeline)for(let r of Object.keys(i.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=i.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(i.tasks)for(let r of Object.keys(i.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n}}function qa(s,e){let t=[],n="Monorepo (pnpm) ";try{let i=zs.load(s);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),i&&i.packages&&(Array.isArray(i.packages)?i.packages:[i.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n}}F();import{execSync as Ze}from"child_process";import fi from"path";import gi from"fs";function se(s){try{if(!gi.existsSync(fi.join(s,".git")))return null;let e=Ze("git rev-parse --abbrev-ref HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return e==="HEAD"?Ze("git rev-parse --short HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():e.replace(/[\/\\:*"<>|?]/g,"-")}catch{return null}}function fe(s){try{return gi.existsSync(fi.join(s,".git"))?Ze("git rev-parse HEAD",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function Gs(s,e=50){try{let t=Ze(`git rev-list --max-count=${e} HEAD`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return t?t.split(`
|
|
506
|
+
`):[]}catch{return[]}}function qs(s,e,t){try{return Ze(`git merge-tree --write-tree ${e} ${t}`,{cwd:s,stdio:["ignore","ignore","ignore"]}),!1}catch{return!0}}function Js(s,e){try{if(!gi.existsSync(fi.join(s,".git")))return!0;let t=fe(s);return!t||e&&e!==t&&Ze(`git diff --name-only ${e} ${t}`,{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()?!0:Ze("git status --porcelain",{cwd:s,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim().length>0}catch{return!0}}F();N();import{execSync as Ys}from"child_process";var et=_.child({module:"nano-repair"}),_e=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:i}=k.getInstance(e);this.intentLogs=t,this.exports=n,this.missions=i,this.repoPath=e}detectAndRepairShifts(){let e=this.intentLogs.findRepairableOrphans();if(e.length===0)return{repaired:0,failed:0};et.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let i of e){let r=this.exports.findByNameAndFile(i.symbol_name,i.file_path);if(r.length>0){let l=r.find(c=>c.signature===i.signature)||r[0];this.intentLogs.update(i.id,{symbol_id:l.id}),et.info({logId:i.id,symbol:i.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(i.symbol_name);if(o.length>0){let l=o.filter(c=>c.file_path!==i.file_path);if(l.length>0){let c=l.find(a=>a.signature===i.signature)||l[0];this.intentLogs.update(i.id,{symbol_id:c.id,file_path:c.file_path}),et.info({logId:i.id,symbol:i.symbol_name,oldPath:i.file_path,newPath:c.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&et.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(){let e="HEAD";try{e=Ys("git rev-parse --abbrev-ref HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return{suspended:0,resumed:0,completed:0}}if(!e)return{suspended:0,resumed:0,completed:0};let t=this.missions.findActive(),n=0;for(let o of t)o.git_branch&&o.git_branch!==e&&(this.missions.updateStatus(o.id,"suspended"),et.info({missionId:o.id,branch:o.git_branch,current:e},"Context Pivot: Suspended mission"),n++);this.missions.resumeByBranch(e);let i=[];try{i=Ys(`git branch --merged "${e}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
507
|
+
`).map(l=>l.trim().replace(/^\* /,"")).filter(l=>l&&l!==e)}catch{}let r=0;if(i.length>0){let o=this.missions.findMergedMissions(e,i);for(let l of o)this.missions.updateStatus(l.id,"completed"),et.info({missionId:l.id,branch:l.git_branch},"Merge Sentinel: Auto-completed mission"),r++}return(n>0||r>0)&&et.info({suspended:n,completed:r},"Git-Native Lifecycle Sync complete"),{suspended:n,resumed:-1,completed:r}}};var Gd=Ya.cpus().length||4,Va=gn.DEFAULT_CONCURRENCY;async function j(s,e=Va,t=!1,n=!0,i){let r=k.getInstance(s),o=r.files.database,l=we(s),c=l.concurrency??e;if(bs(),!t&&Ye(s)){let g=xt(s),y=fe(s);if(g&&!Js(s,g))return ai(),_.debug({repoPath:s,commit:y},"Index is current, skipping re-index (fast-path)"),o}xn(s);let a=r.files.findAll(),p=new Map(a.map(g=>[g.path,{mtime:g.mtime,hash:g.content_hash}])),d=Date.now();i?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let u=await pi(s,l.ignore),m=new Map(u.map(g=>[g.path,g.mtime])),h=a.filter(g=>!m.has(g.path)).map(g=>g.path),b=a.length===0,E=[];if(t||b)E.push(...u);else{let g=u.filter(C=>{let T=p.get(C.path);return!T||T.mtime!==C.mtime}),y=Vs(c*4),S=g.map(C=>y(async()=>{let T=p.get(C.path);if(!T||!T.hash)return C;try{let I=await yi.promises.readFile(C.path,"utf8");return Ui(I,T.hash)?C:(r.files.updateMtime(C.path,C.mtime),null)}catch{return null}})),w=await Promise.all(S);E.push(...w.filter(C=>C!==null))}if(h.length===0&&E.length===0){if(ai(),b){let g=fe(s);Kn(s,g||void 0)}return o}if(b?_.info({totalFiles:u.length},"Starting initial repository indexing..."):_.info({toDelete:h.length,toProcess:E.length},"Syncing repository updates..."),h.length>0&&r.files.deletePaths(h),E.length>0){Ss(),n?ln(!0):ln(!1);let g=Vs(c),y=0,S=E.length,w=E.map($=>g(async()=>{try{let R=Ja.basename($.path);if(/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/.test(R)){let P=await Ct($.path),L=yi.readFileSync($.path,"utf8");return y++,(y%50===0||y===S)&&_.info({completed:y,total:S},"Parsing files..."),i?.({phase:"parse",current:y,total:S,message:`Parsing ${R}`}),{meta:$,...P,content:L,embedding:null,kind:"code"}}else{let P=Bs($.path),L=yi.readFileSync($.path,"utf8");return y++,(y%50===0||y===S)&&_.info({completed:y,total:S},"Parsing configs..."),i?.({phase:"parse",current:y,total:S,message:`Parsing config ${R}`}),{meta:$,...P,content:L,embedding:null,kind:"config"}}}catch(R){return y++,_.error({path:$.path,error:R},"Failed to parse file"),{meta:$,exports:[],imports:[],content:"",kind:"error"}}}));_.info({total:S},"Phase 1: Parsing all files...");let C=Date.now(),T=(await Promise.all(w)).filter(Boolean),I=Date.now()-C;if(dn("parse",I),_.info({count:T.length,time:`${(I/1e3).toFixed(1)}s`},"Phase 1 complete"),n){_.info("Phase 2: Generating file semantic embeddings..."),i?.({phase:"embed",current:0,total:T.length,message:"Generating embeddings..."});let $=Date.now(),R=[];if(T.forEach((P,L)=>{"summary"in P&&P.summary&&R.push({fileIdx:L,text:P.summary})}),R.length>0){_.info({count:R.length}," \u2192 Generating file summary embeddings...");let P=R.map(H=>H.text),L=await si(P,128);R.forEach((H,B)=>{T[H.fileIdx].embedding=L[B]}),_.info({count:R.length}," \u2713 File summaries complete")}let v=Date.now()-$;dn("embed",v),_.info({time:`${(v/1e3).toFixed(1)}s`},"Phase 2 complete")}i?.({phase:"persist",current:0,total:T.length,message:"Saving to database..."});let x=Date.now();r.files.batchSaveIndexResults(T,s,Qn,$t),dn("persist",Date.now()-x)}if(b||E.length>0){let g=fe(s);Kn(s,g||void 0)}return(E.length>0||h.length>0)&&new _e(s).detectAndRepairShifts(),Es(Date.now()-d),i?.({phase:"complete",current:E.length,total:E.length,message:"Indexing complete"}),o}F();async function Nt(s,e=gn.DEFAULT_CONCURRENCY,t="detailed",n,i){_.info({repo:s,level:t,subPath:n},"Ensuring cache is up-to-date..."),await j(s,e);let{files:r,exports:o,imports:l}=k.getInstance(s),c=n?r.findInSubPath(s,n):r.findAll(),a=we(s),p=Qa(),d=Qs.join(s,".gitignore");if(Ks.existsSync(d)&&p.add(Ks.readFileSync(d,"utf8")),a.ignore&&a.ignore.length>0&&p.add(a.ignore),p.add(fn),c=c.filter(y=>{let S=Qs.relative(s,y.path);return!p.ignores(S)}),_.info({count:c.length},"Fetching data from DB..."),t==="lite"){let y=c.map(S=>({path:S.path,mtime:S.mtime}));return wt(y,s,t,i)}if(t==="summaries"){let y=c.map(S=>({path:S.path,mtime:S.mtime,classification:S.classification||void 0,summary:S.summary||void 0}));return wt(y,s,t,i)}let u=c.map(y=>y.path),m=o.findByFiles(u),h=t==="detailed"?l.findByFiles(u):[],b=new Map;for(let y of m){let S=b.get(y.file_path)||[];S.push(y),b.set(y.file_path,S)}let E=new Map;for(let y of h){let S=E.get(y.file_path)||[];S.push(y),E.set(y.file_path,S)}let g=c.map(y=>{let w=(b.get(y.path)||[]).map(T=>({name:T.name,kind:T.kind,signature:T.signature,line:T.start_line}));t==="structure"?w=w.map(T=>({name:T.name,kind:T.kind,line:T.line})):t==="signatures"&&(w=w.map(T=>({name:T.name,kind:T.kind,signature:T.signature,line:T.line})));let C=[];return t==="detailed"&&(C=(E.get(y.path)||[]).map(I=>({module:I.module_specifier,resolved_path:I.resolved_path}))),{path:y.path,mtime:y.mtime,classification:y.classification||void 0,summary:y.summary||void 0,exports:w,imports:C.length>0?C:void 0,chunks:[]}});return _.info({count:g.length},"Building hierarchical project tree..."),wt(g,s,t,i)}async function Zs(s,e){let t=Xs.resolve(s),n=parseInt(e.depth);try{await U(async()=>{let i=await Nt(t,5,"lite",e.subPath,n);console.log(""),console.log(` ${f.bold("Repository Structure: ")} ${f.cyan(Xs.basename(t))}`),e.subPath&&console.log(` ${f.bold("Sub-path: ")} ${f.dim(e.subPath)}`),console.log("");let r=o=>{let l=o.type==="truncated",c=o.type==="directory"&&o.children===void 0;return{name:o.name,color:o.type==="directory"?"blue":l?"gray":"white",info:o.type==="file"?o.summary?.classification:c?"truncated":void 0,children:o.children?.map(r)}};Zn([r(i)]),console.log(""),n<10&&(console.log(f.gray(` (Showing depth ${n}. Use --depth to see more)`)),console.log(""))})}finally{await G(t)}}import tr from"path";import Ka from"fs";N();import X from"path";import bi from"fs";var Tn=_.child({module:"path-resolver"}),At=class{repoPath;constructor(e){this.repoPath=X.isAbsolute(e)?X.normalize(e):X.resolve(process.cwd(),e)}resolve(e){if(!e)return this.repoPath;if(e.includes("\0"))throw Tn.error({inputPath:e},"Path contains null bytes - possible attack"),new Error("Invalid path: contains null bytes");let t;if(X.isAbsolute(e)?t=X.normalize(e):t=X.join(this.repoPath,e),t=X.normalize(t),!this.isWithinRoot(t))throw Tn.warn({inputPath:e,resolved:t},"Path traversal attempt blocked"),new Error(`Access denied: path '${e}' is outside the repository root`);return t}resolveAndValidate(e){try{let t=this.resolve(e);return bi.existsSync(t)?t:(Tn.debug({inputPath:e,resolved:t},"Path does not exist"),null)}catch(t){return Tn.error({inputPath:e,error:t},"Error validating path"),null}}isWithinRoot(e){try{let t=X.resolve(e),n=X.resolve(this.repoPath),i=X.relative(n,t);if(i.startsWith("..")||X.isAbsolute(i))return!1;if(bi.existsSync(t)){let o=bi.realpathSync(t),l=X.relative(n,o);if(l.startsWith("..")||X.isAbsolute(l))return!1}return!0}catch{return!1}}getRelative(e){let t=X.normalize(e);return X.relative(this.repoPath,t)}resolveBatch(e){return e.map(t=>this.resolve(t))}static normalize(e){return X.normalize(e)}static isPathWithinRoot(e,t){let n=X.resolve(e),i=X.resolve(t),r=X.relative(n,i);return r===""||!r.startsWith("..")&&!X.isAbsolute(r)}};function er(s){return new At(s)}async function nr(s,e){let t=tr.resolve(s);await U(async()=>{if(le("MCP Liquid Shadow"),console.log(` ${f.bold("Target")}: ${f.cyan(t)}`),console.log(` ${f.bold("Mode")}: ${e.output?f.magenta("File Export"):f.green("Indexing")}`),console.log(""),!e.output){let i=ue();i.start("Indexing repository...");let r="",o=l=>{if(l.phase!==r){r=l.phase;let c={scan:"Scanning",parse:"Parsing",embed:"Generating embeddings",persist:"Saving to database",complete:"Complete"}[l.phase]||l.phase;i.message(`${c}...`)}if(l.total>0&&l.current>0){let c=Math.round(l.current/l.total*100);i.message(`${r==="parse"?"Parsing":"Processing"}: ${l.current}/${l.total} (${c}%)`)}};try{await j(t,void 0,e.force,e.deep??!0,o),i.message("Running symbol healing...");let c=new _e(t).detectAndRepairShifts();i.stop("Indexing complete!"),Rt("Ready to serve AI requests.")}catch(l){throw i.stop(`Indexing failed: ${l.message}`),l}finally{await G(t)}return}let n=ue();n.start(`Generating export (${f.bold(e.level)})...`);try{let i=await Nt(t,5,e.level,e.subPath),r=tr.resolve(e.output);if((process.env.LIQUID_SHADOW_SANDBOX==="1"||process.env.LIQUID_SHADOW_SANDBOX==="true")&&!At.isPathWithinRoot(t,r))throw new Error("Sandbox mode: output path must be inside the repository. Set LIQUID_SHADOW_SANDBOX=0 to allow external paths.");Ka.writeFileSync(r,JSON.stringify(i,null,2)),n.stop(`Export saved to ${f.bold(f.cyan(r))}`),Rt("Export complete.")}catch(i){throw n.stop(`Export failed: ${i.message}`),i}finally{await G(t)}})}import{performance as ir}from"perf_hooks";import Xa from"path";F();async function sr(s){let e=Xa.resolve(s);await U(async()=>{console.log(`
|
|
508
|
+
${f.bold("Performance Benchmark - Liquid Shadow Intelligence")}`),console.log(` ${f.gray("Repository: ")} ${e}`),console.log(` ${f.yellow("Starting fresh index (DB deleted)...")}
|
|
509
|
+
`);let t=ir.now();try{await j(e,10,!0);let n=ir.now()-t,i=k.getInstance(e),r=i.files.getCount(),o=i.exports.getCount(),l=i.exports.getWithEmbeddingsCount();te("Benchmark Results",`${f.bold("Total Time")}: ${n.toFixed(2)}ms (${(n/1e3).toFixed(2)}s)
|
|
510
|
+
${f.bold("Files Processed")}: ${f.cyan(r.toString())}
|
|
511
|
+
${f.bold("Symbols Extracted")}: ${f.cyan(o.toString())}
|
|
512
|
+
${f.bold("Symbols Embedded")}: ${f.cyan(l.toString())} (${(l/o*100).toFixed(1)}%)
|
|
513
|
+
`+"\u2500".repeat(40)+`
|
|
514
|
+
${f.bold("Files/sec")}: ${f.green((r/(n/1e3)).toFixed(2))}
|
|
515
|
+
${f.bold("Symbols/sec")}: ${f.green((o/(n/1e3)).toFixed(2))}
|
|
516
|
+
${f.bold("ms per file")}: ${f.yellow((n/r).toFixed(2))}`,"green")}catch(n){throw console.error(`
|
|
517
|
+
Benchmark failed during execution:`,n),n}finally{await G(e)}})}import In from"path";import pe from"path";import Si from"fs";var Za=/[\x00-\x1f\x7f]/g,ec=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;function Ei(s){if(typeof s!="string")throw new Error("Invalid path: expected string");if(s.includes("\0"))throw new Error("Invalid path: null bytes are not allowed");if(s.replace(Za,"").length!==s.length)throw new Error("Invalid path: control characters are not allowed");return s.trim()}function vn(s,e=4096){if(typeof s!="string")return"";let t=s.replace(ec,"").trim();return t.length>e?t.slice(0,e):t}Ve();function tc(s){let e=pe.isAbsolute(s)?pe.normalize(s):pe.resolve(process.cwd(),s),t=pe.parse(e).root;for(;e!==t;){if(Si.existsSync(pe.join(e,".liquid-shadow.db"))||Si.existsSync(pe.join(e,".git"))||Si.existsSync(pe.join(e,"package.json")))return e;let n=pe.dirname(e);if(n===e)break;e=n}return null}function xe(s){let e=s?.repoPath?String(s.repoPath):void 0,t=s?.filePath?String(s.filePath):void 0;e&&(e=Ei(e)),t&&(t=Ei(t));let n;if(e)pe.isAbsolute(e)||(e=pe.resolve(process.cwd(),e)),n=e;else if(t){let o=pe.resolve(process.cwd(),t);n=tc(pe.dirname(o))||process.cwd()}else n=process.cwd();n=pe.normalize(n);let i=er(n),r;return t&&(r=i.resolve(t)),{...s,repoPath:n,filePath:r,resolver:i}}F();N();import or from"@swc/core";import Mt from"fs";import ge from"path";import{Visitor as nc}from"@swc/core/Visitor.js";var wn=class extends nc{calls=new Set;apiCalls=[];imports=new Map;axiosInstances=new Map;visitImportDeclaration(e){let t=e.source.value;for(let n of e.specifiers)(n.type==="ImportDefaultSpecifier"||n.type==="ImportSpecifier")&&this.imports.set(n.local.value,t);return super.visitImportDeclaration(e)}visitCallExpression(e){if(e.callee.type==="Identifier"){let t=e.callee.value;this.calls.add(t),(t==="axios"||t==="http")&&e.arguments.length>0&&this.extractApiCallFromConfig(e.arguments[0].expression)}else if(e.callee.type==="MemberExpression"){let t=e.callee.property.value,n=r=>{if(!r)return"?";if(r.type==="Identifier")return r.value;if(r.type==="ThisExpression")return"this";if(r.type==="MemberExpression"){let o=n(r.object),l=r.property.value||"?";return`${o}.${l}`}return r.type==="TsNonNullExpression"||r.type==="TsAsExpression"||r.type==="ParenthesisExpression"?n(r.expression):"?"},i=n(e.callee.object);if(i!=="?"&&t){if(this.calls.add(`${i}.${t}`),i==="axios"||i==="http"||this.axiosInstances.has(i)){let r=this.axiosInstances.get(i)||"";this.extractApiCall(t,e.arguments,r)}if((i.toLowerCase().includes("pubsub")||i==="pubSubClient"||i.endsWith(".pubSubClient"))&&t!=="subscribe"){let r=t;if((t==="publish"||t==="publishMessage"||t==="publishTaskByNameAndPayload")&&e.arguments.length>0)for(let o of e.arguments){let l=o.expression;if(l.type==="ObjectExpression"){let c=l.properties.find(a=>a.key?.type==="Identifier"&&(a.key.value==="action"||a.key.value==="type")||a.key?.type==="StringLiteral"&&(a.key.value==="action"||a.key.value==="type"));if(c&&c.value?.type==="StringLiteral"){r=c.value.value;break}}if(l.type==="CallExpression"&&l.callee.type==="MemberExpression"&&l.callee.object.value==="JSON"&&l.callee.property.value==="stringify"&&l.arguments.length>0){let c=l.arguments[0].expression;if(c.type==="ObjectExpression"){let a=c.properties.find(p=>p.key?.type==="Identifier"&&(p.key.value==="action"||p.key.value==="type")||p.key?.type==="StringLiteral"&&(p.key.value==="action"||p.key.value==="type"));if(a&&a.value?.type==="StringLiteral"){r=a.value.value;break}}}}this.apiCalls.push({method:"PUBSUB",url:r})}}}return e.callee.type==="Identifier"&&e.callee.value==="fetch"&&this.extractApiCall("GET",e.arguments),super.visitCallExpression(e)}visitNewExpression(e){return e.callee.type==="Identifier"&&this.calls.add(e.callee.value),super.visitNewExpression(e)}visitVariableDeclarator(e){if(e.init&&e.init.type==="CallExpression"){let t=e.init.callee;if(t.type==="MemberExpression"&&t.property.value==="create"&&t.object.value==="axios"){let i=e.init.arguments[0]?.expression;if(i&&i.type==="ObjectExpression"){let r=i.properties.find(o=>o.key.value==="baseURL");if(r){let o="?";r.value.type==="StringLiteral"?o=r.value.value:r.value.type==="Identifier"&&(o=`\${${r.value.value}}`),e.id.type==="Identifier"&&this.axiosInstances.set(e.id.value,o)}}}}return super.visitVariableDeclarator(e)}extractApiCallFromConfig(e){if(e&&e.type==="ObjectExpression"){let t=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="url"||i.key.type==="StringLiteral"&&i.key.value==="url"),n=e.properties.find(i=>i.key.type==="Identifier"&&i.key.value==="method"||i.key.type==="StringLiteral"&&i.key.value==="method");if(t&&t.value){let i=n?.value?.value||"GET",r=this.resolveUrlValue(t.value);r!=="?"&&this.apiCalls.push({method:i.toUpperCase(),url:r})}}}resolveUrlValue(e){return e.type==="StringLiteral"?e.value:e.type==="TemplateLiteral"?e.quasis.map(t=>t.cooked).join("*"):"?"}visitTsType(e){return e}extractApiCall(e,t,n=""){if(t.length>0){let i=t[0].expression,r=this.resolveUrlValue(i);if(r!=="?"){if(n&&n!=="?"){let o=n.endsWith("/")||r.startsWith("/")?"":"/";r=`${n}${o}${r}`}this.apiCalls.push({method:e.toUpperCase(),url:r})}}}},lt=class{calls=new Set;apiCalls=[];imports=new Map;visit(e,t){if(t===".php"){let n=/(?:([a-zA-Z0-9_$->:\(\)]*)?(?:->|::))?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],l=i[3];if(this.calls.add(o),r&&!["$this","self","parent"].includes(r)&&this.calls.add(`${r}${r.includes("::")?"::":"->"}${o}`),["save","delete","update","create","first","all","where","get","find"].includes(o)&&r&&!["Log","Route","Cache","Config","Http"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}->${o}()`}),o==="publish"&&r&&(r.includes("topic")||r.includes("pubSub"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="Http"||r==="client"||r.endsWith("request")||r.includes("Client")||!r)){let p=l.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),d=p?p[1]:l.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:d})}}}else if(t===".py"){let n=/(?:([a-zA-Z0-9_\.]+)\.)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)/g,i;for(;(i=n.exec(e))!==null;){let r=i[1]||"",o=i[2],l=i[3];if(this.calls.add(o),r&&r!=="self"&&r!=="cls"&&this.calls.add(`${r}.${o}`),["save","delete","update","create","first","all","filter","get"].includes(o)&&r&&!["logger","os","sys"].includes(r)&&this.apiCalls.push({method:"DB",url:`${r}.${o}()`}),o==="publish"&&r&&(r.includes("publisher")||r.includes("client"))&&this.apiCalls.push({method:"PUBSUB",url:"publish"}),["get","post","put","delete","patch","request"].includes(o)&&(r==="requests"||r==="httpx"||r==="client"||r==="http"||!r)){let p=l.match(/(?:url\s*:\s*)?['"]([^'"]+)['"]/),d=p?p[1]:l.split(",")[0].trim()||"unknown";this.apiCalls.push({method:o.toUpperCase(),url:d})}}}else if([".ts",".tsx",".js",".jsx"].includes(t)){let n=/import\s+[\s\S]*?from\s+['"](.*?)['"];?/g,i;for(;(i=n.exec(e))!==null;)this.imports.set("*",i[1]);let r=/(?:([a-zA-Z0-9_$]+)\.)?([a-zA-Z0-9_$]+)\s*\(/g,o;for(;(o=r.exec(e))!==null;){let l=o[1],c=o[2];l?(this.calls.add(`${l}.${c}`),(l.toLowerCase().includes("pubsub")||l==="pubSubClient")&&c!=="subscribe"&&this.apiCalls.push({method:"PUBSUB",url:c})):this.calls.add(c)}}else{let n=/\.([a-zA-Z0-9_]+)\s*\(/g,i;for(;(i=n.exec(e))!==null;)this.calls.add(i[1])}if(t===".php"){let n=/use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/g,i;for(;(i=n.exec(e))!==null;){let r=i[1],o=r.split("\\"),l=i[2]||o[o.length-1];this.imports.set(l,r)}}else if(t===".py"){let n=/from\s+([a-zA-Z0-9_\.]+)\s+import\s+([a-zA-Z0-9_,\s]+)/g,i;for(;(i=n.exec(e))!==null;){let l=i[1];i[2].split(",").map(a=>a.trim()).forEach(a=>{this.imports.set(a,l)})}let r=/^import\s+([a-zA-Z0-9_\.]+)/gm,o;for(;(o=r.exec(e))!==null;){let l=o[1],c=l.split("."),a=c[c.length-1];this.imports.set(a,l)}}}};var ic=new Set(["api","v1","v2","v3","http","https","localhost","admin","internal","public","private","app","src","get","post","put","delete","patch","user","users","id","search","list","create","update","data"]);function rr(s,e){let t=e,n=e.match(/\$\{([^}]+)\}/g);if(n)for(let p of n){let d=p.substring(2,p.length-1),u=s.configs.findEnvValue(d);u&&(t=t.replace(p,u))}let i=t.split("?")[0];try{i.includes("://")&&(i=new URL(i).pathname)}catch{}let r=[],o=i.split("?")[0],l=s.files.findSynapses({type:"api_route",name:o,direction:"consume"});for(let p of l)r.push({file_path:p.file_path,start_line:p.line_number||0,signature:`[Synapse] ${p.name}`,score:1e3});let c=i.split(/[^a-zA-Z0-9-_]/).filter(p=>p.length>=3&&!ic.has(p.toLowerCase())&&!/^\d+$/.test(p));if(c.length>0){let d=[...c].sort((m,h)=>h.length-m.length)[0],u=s.exports.findRoutesByToken(d);for(let m of u){let h=50,b=(m.signature||m.name||"").toLowerCase();for(let E of c)b.includes(E.toLowerCase())&&(h+=20);r.push({file_path:m.file_path,start_line:m.start_line,signature:`[Boundary] ${m.signature||m.name}`,capabilities:m.capabilities||void 0,score:h})}}if(r.length<3){let p=c.map(u=>u.replace(/[^a-zA-Z0-9_]/g,"")).filter(u=>u.length>0).join(" AND ");if(p.length===0)return r;let d=s.content.search(p);for(let u of d){let m=0,h=u.file_path.toLowerCase(),b=u.snippet.toLowerCase();(h.includes("route")||h.includes("controller")||h.includes("handler"))&&(m+=10),(h.includes("src/api")||h.includes("services/api"))&&(m+=5),(b.includes("addroute")||b.includes("@get")||b.includes("router."))&&(m+=15),(b.includes("axios.")||b.includes("fetch("))&&(m-=10),(h.includes(".spec.")||h.includes(".test."))&&(m-=20),m>0&&r.push({file_path:u.file_path,start_line:0,signature:`[FTS Match] ${u.snippet.replace(/\n/g," ")}`,score:m})}}let a=new Map;return r.sort((p,d)=>d.score-p.score).forEach(p=>{a.has(p.file_path)||a.set(p.file_path,p)}),Array.from(a.values()).slice(0,3)}var sc=4,Pt=50,rc=2;async function ar(s){let{repoPath:e,filePath:t,symbolName:n}=xe(s);if(!t)return{isError:!0,content:[{type:"text",text:"Error: 'filePath' is required."}]};let i=t;await j(e);let r=k.getInstance(e);if(!Mt.existsSync(i))return{isError:!0,content:[{type:"text",text:`File not found: ${i}`}]};let o,l=ge.basename(i),c;if(n){let u=r.exports.findByNameAndFile(n,i);if(u.length>0){let m=u[0];o={start:m.start_line,end:m.end_line},l=m.name,c=m.start_line}}let a={type:o?"function":"file",name:l,path:ge.relative(e,i),line:c,children:[]},p=new Set;p.add(i+(n?`:${n}`:""));let d={count:0,truncated:!1};return await pt(i,a,e,r,p,1,d,o),d.truncated&&a.children.push({type:"function",name:"\u26A0\uFE0F Output Truncated",details:`Trace limited to ${Pt} nodes. Use summarize_file on specific files for deeper analysis.`,children:[]}),{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}async function pt(s,e,t,n,i,r,o,l){if(!(r>sc)){if(o.count>=Pt){o.truncated=!0;return}try{let c=Mt.readFileSync(s,"utf8"),a=ge.extname(s).toLowerCase(),d=(c.match(/import\s+[\s\S]*?from\s+['"].*?['"];?/gm)||[]).join(`
|
|
518
|
+
`);l&&(c=c.split(`
|
|
519
|
+
`).slice(l.start-1,l.end).join(`
|
|
520
|
+
`));let u;if(a===".ts"||a===".tsx"||a===".js"||a===".jsx"){u=new wn;let E={syntax:"typescript",tsx:s.endsWith(".tsx"),target:"es2020"};try{let g=l?`${d}
|
|
521
|
+
${c}`:c,y=await or.parse(g,E);u.visitModule(y)}catch{if(l)try{let y=`${d}
|
|
522
|
+
class TraceContext {
|
|
523
|
+
${c}
|
|
524
|
+
}`,S=await or.parse(y,E);u.visitModule(S)}catch{let S=new lt,w=a;S.visit(c,w),u.calls=S.calls,u.apiCalls=S.apiCalls,u.imports=S.imports}else{let y=new lt;y.visit(c,a),u.calls=y.calls,u.apiCalls=y.apiCalls,u.imports=y.imports}}}else u=new lt,u.visit(c,a);_.info({file:ge.basename(s),calls:u.calls.size,apiCalls:u.apiCalls.length,depth:r},"Analyzed file");let m=u.apiCalls.slice(0,10);for(let E of m){if(o.count>=Pt)break;if(o.count++,E.method==="PUBSUB"){let w={type:"event_trigger",name:`PubSub Event: ${E.url}`,details:"Detected via PubSub client usage",children:[]};e.children.push(w);let C=n.exports.findByNameGlobal(E.url).concat(n.exports.findByMethodName(E.url));if(E.url.length>10){let I=E.url.replace(/To[A-Z][a-zA-Z]+$/,"");if(I!==E.url){let x=n.exports.findByNameGlobal(I).concat(n.exports.findByMethodName(I));C.push(...x)}}let T=new Set;for(let I of C){if(T.has(I.file_path)||I.file_path===s)continue;if(T.add(I.file_path),o.count>=Pt)break;o.count++;let x={type:"subscriber",name:`${I.name} (${ge.basename(I.file_path)})`,path:ge.relative(t,I.file_path),line:I.start_line,details:"Potential Subscriber / Handler",children:[]};w.children.push(x),Mt.existsSync(I.file_path)&&!i.has(I.file_path)&&(i.add(I.file_path),await pt(I.file_path,x,t,n,i,r+1,o))}continue}let g={type:"api_call",name:`${E.method} ${E.url}`,details:"Detected via string literal analysis",children:[]};e.children.push(g);let S=rr(n,E.url).slice(0,rc);for(let w of S){if(o.count>=Pt)break;o.count++;let C={type:"route",name:w.signature||"Route Handler",path:w.file_path,line:w.start_line,children:[]};if(g.children.push(C),Mt.existsSync(w.file_path)&&!i.has(w.file_path)&&(i.add(w.file_path),await pt(w.file_path,C,t,n,i,r+1,o)),w.capabilities)try{let T=JSON.parse(w.capabilities);if(T.handler){let[I,x]=T.handler.split("@");if(I){let R=I.split("\\").pop();if(R){let v=n.exports.findClassByName(R);if(v){let P=n.exports.findByNameAndFile(x||"",v.file_path),L,H=v.start_line;P.length>0&&(L={start:P[0].start_line,end:P[0].end_line},H=P[0].start_line);let B={type:"component",name:`${R}${x?" :: "+x:""}`,path:ge.relative(t,v.file_path),line:H,details:"Controller Logic (Macro IR)",children:[]};C.children.push(B),i.has(v.file_path+(x?`:${x}`:""))||(i.add(v.file_path+(x?`:${x}`:"")),await pt(v.file_path,B,t,n,i,r+1,o,L))}}}}}catch{}}}let h=u.calls,b=Array.from(h).sort();for(let E of b)if(u.imports.has(E)){let g=u.imports.get(E);if(!g.startsWith(".")){if(["react","react-dom"].includes(g))continue;e.children.push({type:"function",name:E,details:`External: ${g}`,children:[]});continue}let y=$t(g,s,t);if(y&&Mt.existsSync(y))if(i.has(y))e.children.push({type:"function",name:E,details:"Circular / Already Visited",path:ge.relative(t,y),children:[]});else{i.add(y);let S={type:"file",name:E,details:`Imported from ${ge.basename(y)}`,path:ge.relative(t,y),children:[]};e.children.push(S),await pt(y,S,t,n,i,r+1,o)}}else if(!["log","info","error","warn","print"].includes(E)){let g=n.exports.findByNameGlobal(E);if(g.length===0){let y=E.split(/(?:\.|->|::)+/);if(y.length>1){let S=y[y.length-1];g=n.exports.findByMethodName(S)}}if(g.length>0){let y=g.find(w=>w.file_path===s),S=y||(g.length===1?g[0]:null);if(S){let w=`${S.file_path}:${S.name}`;if(!i.has(w)){i.add(w);let C={type:"component",name:E,details:`Resolved via global index${y?" (local)":""}`,path:ge.relative(t,S.file_path),line:S.start_line,children:[]};e.children.push(C),await pt(S.file_path,C,t,n,i,r+1,o,{start:S.start_line,end:S.end_line})}}}}}catch(c){_.error({filePath:s,error:c.message},"Trace analysis failed"),e.children.push({type:"function",name:"Error",details:c.message,children:[]})}}}async function cr(s,e){let t=In.resolve(e.dir),n=In.isAbsolute(s)?s:In.resolve(t,s);await U(async()=>{le("Execution Trace");let i=ue();i.start(`Tracing ${f.cyan(e.symbolName||In.basename(n))}...`);try{let r=await ar({repoPath:t,filePath:n,symbolName:e.symbolName});i.stop("Trace complete."),r.isError?console.error(f.red(r.content[0].text)):te("Flow Results",r.content[0].text,"magenta")}catch(r){throw i.stop(`Trace failed: ${r.message}`),r}finally{await G(t)}})}import fc from"path";F();dt();N();import{execSync as Hr}from"child_process";import hc from"path";var kn=_.child({module:"shadow-trace"}),mt=class{intentLogs;exports;repoPath;hologramService;constructor(e){let{intentLogs:t,exports:n}=k.getInstance(e);this.intentLogs=t,this.exports=n,this.repoPath=e,this.hologramService=new de(e)}analyzeGhostChanges(e){let t=e?`${e}..HEAD`:"HEAD~1..HEAD",n=[];try{let r=Hr(`git diff --name-only ${t}`,{cwd:this.repoPath,encoding:"utf-8"}).split(`
|
|
525
|
+
`).filter(o=>o.trim()!=="");if(r.length===0)return;kn.info({files:r.length,range:t},"Initiating Shadow Trace analysis...");for(let o of r){let l=hc.join(this.repoPath,o),a=Hr(`git diff -U0 ${t} -- ${o}`,{cwd:this.repoPath,encoding:"utf-8"}).matchAll(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/g);for(let p of a){let d=parseInt(p[2],10),u=this.exports.findAtLine(l,d);u&&(this.intentLogs.create({mission_id:0,file_path:l,symbol_id:u.id,type:"discovery",content:`Shadow Trace: Modified externally in ${t}`,confidence:.8,symbol_name:u.name,signature:u.signature,commit_sha:null}),kn.debug({symbol:u.name},"Logged ghost change"),n.push({from:"external",to:`${o}:${u.name}`,pattern:"git-delta",confidence:.8}))}}n.length>0&&this.hologramService.updateGhostBridges(n),kn.info("Shadow Trace complete.")}catch(i){kn.warn({err:i.message},"Shadow Trace failed: git diff error.")}}};F();import{execSync as ht}from"child_process";var Cn=class{constructor(e,t="refs/notes/shadow"){this.repoPath=e;this.ref=t}addNote(e,t){try{ht(`git notes --ref ${this.ref} add -f -m '${t.replace(/'/g,"'\\''")}' ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch(n){throw new Error(`Failed to add git note to ${e}: ${n.message}`)}}getNote(e){try{return ht(`git notes --ref ${this.ref} show ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}listNotes(){let e=new Map;try{let t=ht(`git notes --ref ${this.ref} list`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(!t)return e;let n=t.split(`
|
|
526
|
+
`);for(let i of n){let[r,o]=i.split(" ");if(o){let l=this.getNote(o);l&&e.set(o,l)}}}catch{}return e}removeNote(e){try{ht(`git notes --ref ${this.ref} remove ${e}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}push(e="origin"){try{ht(`git push ${e} ${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch(t){throw new Error(`Failed to push git notes to ${e}: ${t.message}`)}}fetch(e="origin"){try{ht(`git fetch ${e} ${this.ref}:${this.ref}`,{cwd:this.repoPath,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{}}};N();var ft=_.child({module:"persistence-service"}),Re=class{gitNotes;repoPath;constructor(e){this.repoPath=e,this.gitNotes=new Cn(e)}async syncMissionToGitNotes(e){let{missions:t,intentLogs:n}=k.getInstance(this.repoPath),i=t.findById(e);if(!i)throw new Error(`Mission ${e} not found`);if(!i.commit_sha){ft.warn({missionId:e},"Cannot sync mission without commit_sha");return}ft.info({missionId:e,commitSha:i.commit_sha},"Syncing mission to Git Notes");let r=t.getArtifacts(e),o=n.findByMission(e,1e3),l=o.find(p=>p.type==="adr"),c=o.filter(p=>p.type==="decision").map(p=>({content:p.content,symbol_name:p.symbol_name,created_at:p.created_at})),a={version:"1.0",mission:{name:i.name,goal:i.goal,status:i.status,strategy_graph:i.strategy_graph,git_branch:i.git_branch,commit_sha:i.commit_sha,parent_id:i.parent_id,verification_context:i.verification_context,outcome_contract:i.outcome_contract,created_at:i.created_at,updated_at:i.updated_at},artifacts:r,adr:l?l.content:null,decisions:c};this.gitNotes.addNote(i.commit_sha,JSON.stringify(a,null,2))}async syncAllToGitNotes(){let{missions:e}=k.getInstance(this.repoPath),t=e.findActive(),n=e.findRecentCompleted(10),i=[...t,...n];for(let r of i)try{await this.syncMissionToGitNotes(r.id)}catch(o){ft.error({missionId:r.id,error:o},"Failed to sync mission")}}async recoverFromGitNotes(){let e=this.gitNotes.listNotes(),{missions:t,intentLogs:n}=k.getInstance(this.repoPath),i=0,r=0;for(let[o,l]of e.entries())try{let c=JSON.parse(l);if(c.version!=="1.0")continue;if(t.findByCommitShas([o]).some(u=>u.name===c.mission.name)){ft.debug({commitSha:o,missionName:c.mission.name},"Mission already exists, skipping recovery");continue}let d=t.create({name:c.mission.name,goal:c.mission.goal,status:c.mission.status,strategy_graph:c.mission.strategy_graph,git_branch:c.mission.git_branch,commit_sha:o,parent_id:c.mission.parent_id,verification_context:c.mission.verification_context,outcome_contract:c.mission.outcome_contract});if(i++,c.adr&&(n.create({mission_id:Number(d),symbol_id:null,file_path:null,type:"adr",content:c.adr,confidence:1,symbol_name:null,signature:null,commit_sha:o}),r++),c.decisions&&c.decisions.length>0)for(let u of c.decisions)n.create({mission_id:Number(d),symbol_id:null,file_path:null,type:"decision",content:u.content,confidence:1,symbol_name:u.symbol_name,signature:null,commit_sha:o}),r++;ft.info({commitSha:o,missionName:c.mission.name,logsRecovered:r},"Re-hydrated mission from Git Notes")}catch(c){ft.error({commitSha:o,error:c},"Failed to parse Git Note for recovery")}return{missionsRecovered:i,logsRecovered:r}}};F();Ot();async function Wr(s){let{repoPath:e,sinceCommit:t}=s;try{await j(e),new mt(e).analyzeGhostChanges(t);let i=new _e(e),r=i.detectAndRepairShifts(),o=i.syncLifecycle(),c=await new Re(e).recoverFromGitNotes(),{HologramService:a}=await Promise.resolve().then(()=>(dt(),Fr)),p=new a(e),d=ut(k.getInstance(e),e);p.updateTopography(d);let u=p.computeGravityZones();p.updateGravityZones(u);let m="Shadow Sync complete. Code changes indexed and intent logs updated.";return m+=`
|
|
527
|
+
\u269B\uFE0F Hologram: Refreshed architectural map (${u.length} hotspots).`,r.repaired>0&&(m+=`
|
|
528
|
+
\u2728 Nano-Repair: Fixed ${r.repaired} links.`),c.missionsRecovered>0&&(m+=`
|
|
529
|
+
\u{1F9EC} Re-hydration: Recovered ${c.missionsRecovered} missions.`),{content:[{type:"text",text:m}]}}catch(n){return{content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}}}async function Ur(s,e){let t=fc.resolve(s);await U(async()=>{le("Shadow Sync");let n=ue();n.start("Synchronizing intelligence lifecycle...");try{let i=await Wr({repoPath:t,sinceCommit:e.sinceCommit});n.stop("Sync complete."),i.isError?console.error(f.red(i.content[0].text)):(console.log(""),console.log(i.content[0].text),console.log(""))}catch(i){throw n.stop(`Sync failed: ${i.message}`),i}finally{await G(t)}})}Ot();F();N();dt();import Br from"path";F();Ot();dt();import Le from"path";async function jr(s){let{repoPath:e}=s;await j(e);let t=k.getInstance(e),n=ut(t,e),r=new de(e).getSnapshot(),o=[],l=[],c=Object.values(n.layers.Entry.topFiles).map(u=>u.path),a=new Set(Object.values(n.layers.Data.topFiles).map(u=>u.path));for(let u of c){let m=Le.isAbsolute(u)?u:Le.join(e,u),h=t.imports.findByFile(m);for(let b of h)b.resolved_path&&a.has(Le.relative(e,b.resolved_path))&&o.push(`\u2694\uFE0F LAYER BYPASS: \`${Le.relative(e,u)}\` directly imports Data layer \`${Le.relative(e,b.resolved_path)}\`. Should go through Logic.`)}let p=r.gravity?.hotspots||[];for(let u of p){let m=Dt(u.filePath,t);(m.layer==="Utility"||m.layer==="Unknown")&&u.gravity>50&&l.push(`\u{1F6A8} GRAVITY ANOMALY: \`${Le.relative(e,u.filePath)}\` has high gravity (${u.gravity.toFixed(0)}) but is classified as ${m.layer}. Consider promoting to Core Logic.`)}for(let u of c){let m=Le.isAbsolute(u)?u:Le.join(e,u),h=t.exports.findByFile(m);h.length>10&&l.push(`\u{1F388} ENTRY BLOAT: \`${Le.relative(e,u)}\` exports ${h.length} symbols. Entry handlers should be thin interfaces.`)}let d=`# \u{1F575}\uFE0F Architectural Scout Report
|
|
530
|
+
|
|
531
|
+
`;return o.length===0&&l.length===0?d+=`\u2705 No significant architectural drift detected. The structure remains "Legit".
|
|
532
|
+
`:(o.length>0&&(d+=`## \u274C Structural Violations
|
|
533
|
+
`,o.forEach(u=>d+=`- ${u}
|
|
534
|
+
`),d+=`
|
|
535
|
+
`),l.length>0&&(d+=`## \u26A0\uFE0F Architectural Warnings
|
|
536
|
+
`,l.forEach(u=>d+=`- ${u}
|
|
537
|
+
`),d+=`
|
|
538
|
+
`)),{content:[{type:"text",text:d}]}}async function zr(s,e,t){let n=e?Br.resolve(process.cwd(),e):process.cwd();if(s==="init"){_.info('Running full initialization (same as "index --force")...'),await j(n,void 0,!0,!0);return}if(s==="tree"){_.info('For tree view, please use the "tree" command.');return}if(s==="topography"){await j(n);let i=k.getInstance(n),r=ut(i,n);console.log(`
|
|
539
|
+
\u{1F3D7}\uFE0F Architecture Summary for ${Br.basename(n)}
|
|
540
|
+
`),console.log(`Detected Pattern: **${r.pattern}** (Confidence: ${r.patternConfidence.toFixed(0)}%)`),r.insights.length>0&&(console.log(`
|
|
541
|
+
Insights:`),r.insights.forEach(a=>console.log(`- ${a}`))),console.log(`
|
|
542
|
+
Layer Distribution:`);let o=["Entry","Logic","Data","Utility","Infrastructure","Test","Types","Unknown"],l=Object.values(r.layers).reduce((a,p)=>a+p.count,0),c=a=>{switch(a){case"Entry":return"\u{1F6AA}";case"Logic":return"\u2699\uFE0F";case"Data":return"\u{1F4BE}";case"Utility":return"\u{1F527}";case"Infrastructure":return"\u{1F3D7}\uFE0F";case"Test":return"\u{1F9EA}";case"Types":return"\u{1F4DD}";default:return"\u2753"}};o.forEach(a=>{let p=r.layers[a],d=l>0?(p.count/l*100).toFixed(1):"0.0";console.log(`${c(a)} ${a.padEnd(14)} | ${p.count.toString().padStart(5)} files | ${d}%`)}),console.log(`
|
|
543
|
+
Top Files by Layer:`),o.forEach(a=>{let p=r.layers[a];p.count!==0&&(console.log(`
|
|
544
|
+
${c(a)} ${a}`),p.topFiles.forEach(d=>{console.log(` - ${d.path} (${d.confidence}% conf)`),d.signals.length>0&&console.log(` \u2514\u2500 ${d.signals.slice(0,1).join(", ")}`)}))});return}if(s==="scout"){let i=await jr({repoPath:n});console.log(i.content[0].text);return}if(s==="hologram"){let i=new de(n);console.log(JSON.stringify(i.getSnapshot(),null,2));return}_.error(`Unknown recon mode: ${s}. Available: init, topography, scout, hologram`)}import Ht from"path";F();var Ft=class{static extractSnippet(e,t,n=300){if(!e||!t)return"";let i=t.toLowerCase().split(/\s+/).filter(u=>u.length>2&&!["the","and","for","with","from"].includes(u));if(i.length===0)return e.slice(0,n)+"...";let r=e.split(`
|
|
545
|
+
`),o=new Array(r.length).fill(0);for(let u=0;u<r.length;u++){let m=r[u].toLowerCase(),h=0,b=0;for(let E of i)m.includes(E)&&(h++,b++);(m.includes("export ")||m.includes("class ")||m.includes("function ")||m.includes("interface "))&&(h+=1),o[u]=b*10+h}let l=0,c=-1,a=5;for(let u=0;u<=r.length-a;u++){let m=0;for(let h=0;h<a;h++)m+=o[u+h];m>c&&(c=m,l=u)}if(c<=0)return e.slice(0,n).trim()+"...";let d=r.slice(l,l+a).join(`
|
|
546
|
+
`).trim();return l>0&&(d=`...
|
|
547
|
+
`+d),l+a<r.length&&(d=d+`
|
|
548
|
+
...`),d.length>n?d.slice(0,n)+"...":d}static calculateLexicalScore(e,t){if(!e||!t)return 0;let n=t.toLowerCase().split(/\s+/).filter(o=>o.length>2&&!["the","and","for","with","from"].includes(o));if(n.length===0)return 0;let i=0,r=e.toLowerCase();for(let o of n)if(r.includes(o)){i+=1;let l=new RegExp(`\\b${o}`,"gi"),c=r.match(l);c&&(i+=Math.min(c.length*.2,2)),new RegExp(`(class|function|export|interface|enum|type)\\s+${o}`,"i").test(e)&&(i+=1.5)}return i/n.length}};F();N();var Ue=_.child({module:"clean-sweep"}),xi=class{files;intentLogs;constructor(e){let{files:t,intentLogs:n}=k.getInstance(e);this.files=t,this.intentLogs=n}pruneOrphans(){Ue.info("Starting orphan pruning...");let e=0,t=0,n=this.intentLogs.findOrphans();Ue.info({orphanCount:n.length},"Found orphaned logs");for(let o of n)o.file_path&&this.files.exists(o.file_path)?(this.intentLogs.markAsLapsed(o.id),t++,Ue.debug({logId:o.id,symbolName:o.symbol_name},"Converted to lapsed intent")):(this.intentLogs.delete(o.id),e++,Ue.debug({logId:o.id},"Deleted orphaned log"));let i=this.intentLogs.findLogsForMissingFiles();for(let o of i)this.intentLogs.delete(o.id),e++;let r=this.intentLogs.findRecentDecisionActivity(1e3).length;return Ue.info({deleted:e,converted:t},"Orphan pruning complete"),{deleted:e,converted:t,retained:r}}},Ri=class{lambda;constructor(e=.01){this.lambda=e}calculateScore(e,t){let i=(Math.floor(Date.now()/1e3)-t)/(3600*24),r=Math.exp(-this.lambda*i);return e*r}scoreResults(e){return e.map(t=>({...t,decayed_score:this.calculateScore(t.score,t.created_at)}))}},Ti=class{missions;constructor(e){let{missions:t}=k.getInstance(e);this.missions=t}findColdMissions(){let e=Math.floor(Date.now()/1e3)-604800,t=this.missions.findColdMissions(e,10);return Ue.info({count:t.length},"Found cold missions for compaction"),t}markDistilled(e){this.missions.update(e,{status:"distilled"})}},Ln=class{pruner;scorer;compactor;constructor(e){this.pruner=new xi(e),this.scorer=new Ri,this.compactor=new Ti(e)}runMaintenance(){Ue.info("Initiating Clean Sweep maintenance protocol...");let e=this.pruner.pruneOrphans(),t=this.compactor.findColdMissions();return Ue.info("Clean Sweep maintenance complete"),{pruning:e,compaction:{eligible:t.length}}}getScorer(){return this.scorer}getCompactor(){return this.compactor}};F();N();var Gr=_.child({module:"lineage-service"}),tt=class{repoPath;constructor(e){this.repoPath=e}getAncestorMissionIds(e=50){try{let t=Gs(this.repoPath,e);if(t.length===0)return[];let{missions:n}=k.getInstance(this.repoPath),r=n.findByCommitShas(t).map(o=>o.id);return r.length>0&&Gr.debug({count:r.length},"Identified ancestor missions for gravity bleed"),r}catch(t){return Gr.warn({err:t.message},"Failed to identify ancestor missions"),[]}}};var gc={Solid:1,Liquid:.8,Virtual:.4,Intel:.2,Phantom:.05},$e=class{static classify(e,t){let n=e.toLowerCase();if(t?.content){let i=t.content;if(i.includes("describe(")||i.includes("test(")||i.includes("it(")||i.includes("expect(")||i.includes('from "@jest/globals"')||i.includes('from "vitest"'))return"Virtual"}return t?.exports&&(t.exports.some(r=>r.kind==="ClassDeclaration"||r.kind==="Class")||t.exports.length>5),n.includes("/dist/")||n.includes("/build/")||n.includes("/.generated/")||n.includes("/node_modules/")||n.endsWith(".map")||n.endsWith(".log")?"Phantom":n.includes("/test/")||n.includes("/tests/")||n.includes("/__tests__/")||n.includes("/__mocks__/")||n.includes(".spec.")||n.includes(".test.")||n.includes("/e2e/")||n.includes("/test-utils/")?"Virtual":n.includes("/examples/")||n.includes("/fixtures/")||n.includes("/mocks/")||n.includes("/stories/")||n.includes("/samples/")||n.includes("/docs/")?"Intel":n.includes("/src/")||n.includes("/lib/")||n.includes("/app/")||n.includes("/core/")||n.includes("/logic/")||n.includes("/domain/")||n.includes("/services/")||n.includes("/controllers/")||n.includes("/handlers/")||n.includes("/repositories/")||n.includes("/models/")||n.includes("/packages/")&&!n.includes("/packages/config/")||n.includes("/backends/")||t?.exports&&(t.exports.some(i=>i.kind==="ClassDeclaration"||i.kind==="Class")||t.exports.length>5)?"Solid":"Liquid"}static mapClassificationToTier(e){let t=e.toLowerCase();return t==="service"||t==="repository"||t==="model"||t==="controller"||t==="handler"||t==="component"||t==="hook"||t==="titanium"||t==="solid"?"Solid":t==="test"||t==="iron"||t==="virtual"?"Virtual":t==="lead"||t==="intel"?"Intel":t==="ghost"||t==="error"||t==="phantom"?"Phantom":"Liquid"}static getMultiplier(e,t){let n=t?this.mapClassificationToTier(t):this.classify(e);return gc[n]}};N();function yc(s,e){let t=[];for(let n=0;n<=e.length;n++)t[n]=[n];for(let n=0;n<=s.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=s.length;i++)e.charAt(n-1)===s.charAt(i-1)?t[n][i]=t[n-1][i-1]:t[n][i]=Math.min(t[n-1][i-1]+1,t[n][i-1]+1,t[n-1][i]+1);return t[e.length][s.length]}function bc(s,e){let t=yc(s.toLowerCase(),e.toLowerCase()),n=Math.max(s.length,e.length);return Math.round((n-t)/n*100)}function qr(s){let e=[],t="";for(let n=0;n<s.length;n++){let i=s[n],r=i>="A"&&i<="Z",o=i>="a"&&i<="z";r&&t.length>0?(e.push(t),t=i):o||r?t+=i:t.length>0&&(e.push(t),t="")}return t.length>0&&e.push(t),e}function Ec(s,e){let t=qr(e),n=s.toLowerCase();if(t.map(o=>o[0].toLowerCase()).join("")===n)return!0;let r=0;for(let o of t){if(r>=s.length)break;let l=o.toLowerCase();if(l.startsWith(n.slice(r))){r=s.length;break}l[0]===n[r]&&r++}return r===s.length}function Sc(s,e){return qr(e).map(i=>i[0].toLowerCase()).join("")===s.toLowerCase()}function _c(s,e){let t=s.toLowerCase(),n=e.toLowerCase();if(s===e)return{matchType:"exact",score:100};if(t===n)return{matchType:"exact-case-insensitive",score:98};if(n.startsWith(t))return{matchType:"prefix",score:90+s.length/e.length*8};if(n.endsWith(t))return{matchType:"suffix",score:80+s.length/e.length*8};if(n.includes(t)){let r=s.length/e.length,o=n.indexOf(t)/e.length;return{matchType:"substring",score:70+r*10-o*5}}return Sc(s,e)?{matchType:"acronym",score:75}:Ec(s,e)?{matchType:"camel-case",score:65}:{matchType:"levenshtein",score:bc(s,e)*.6}}function $n(s,e,t=50,n=5){let i=[];for(let r of e){let{matchType:o,score:l}=_c(s,r);if(l>=t){let a={exact:1e3,"exact-case-insensitive":900,prefix:800,suffix:700,substring:600,acronym:550,"camel-case":500,levenshtein:100}[o]+l;i.push({match:r,score:l,matchType:o,rank:a})}}return i.sort((r,o)=>o.rank!==r.rank?o.rank-r.rank:o.score!==r.score?o.score-r.score:r.match.length-o.match.length),i.slice(0,n)}dt();var je=class s{constructor(e){this.repoPath=e}get filesRepo(){return k.getInstance(this.repoPath).files}get exportsRepo(){return k.getInstance(this.repoPath).exports}static normalizeFileType(e){if(e==null)return;let t=Array.isArray(e)?e:e.split(",").map(n=>n.trim().replace(/^\./,""));return t.filter(Boolean).length?t:void 0}static matchesFilters(e,t,n,i){if(t.fileType?.length){let r=e.replace(/^.*\./,"").toLowerCase();if(!t.fileType.some(o=>o.toLowerCase()===r))return!1}if(t.layer!=null||t.excludeLayers&&t.excludeLayers.length>0){let r=i!=null?$e.mapClassificationToTier(i):$e.classify(e);if(t.layer!=null&&r!==t.layer||t.excludeLayers?.includes(r))return!1}if(t.dateModifiedAfter!=null||t.dateModifiedBefore!=null){if(n==null)return!1;let r=n>1e10?n/1e3:n;if(t.dateModifiedAfter!=null&&r<t.dateModifiedAfter||t.dateModifiedBefore!=null&&r>t.dateModifiedBefore)return!1}return!0}async searchByPath(e,t,n,i,r){let o=e.toLowerCase().split(/\s+/).filter(Boolean),l=this.filesRepo.findByPathKeywords(o,Math.min((t??50)*(r?oe.FILTERED_QUERY_LIMIT_MULTIPLIER:1),ot.MAX_LIMIT));r&&(l=l.filter(p=>s.matchesFilters(p.path,i,p.mtime,p.classification)),l=l.slice(0,t??50));let c=p=>p.replace(this.repoPath,"").replace(/^\//,"");return{content:[{type:"text",text:l.length===0?`No indexed files match path/filename: "${e}".
|
|
549
|
+
|
|
550
|
+
If the repo is not indexed, run shadow_recon_onboard then shadow_sync_trace. Otherwise try broader keywords.`:`# Resolved paths: "${e}"
|
|
551
|
+
|
|
552
|
+
${l.length} file(s):
|
|
553
|
+
|
|
554
|
+
`+l.map((p,d)=>`${d+1}. \`${c(p.path)}\`${p.classification?` (${p.classification})`:""}`).join(`
|
|
555
|
+
`)}]}}async searchByConcept(e,t,n,i,r,o=!1){_.info({repoPath:this.repoPath,query:e},"Searching by concept (Semantic Analysis)...");let l=await ii(e),c=y=>y.replace(this.repoPath,"").replace(/^\//,"");if(l){let y=await this.findConceptMatches(e,l,i,r,t*2);if(y.length>0){let S=y.length,w=y.slice(n,n+t),T=n+t<S?`
|
|
556
|
+
> **Note**: More results available. Use \`offset: ${n+t}\` to see the next page.`:"",I=o?`
|
|
557
|
+
> _Compact mode: snippets omitted_`:S>20&&!o?"\n> \u{1F4A1} **Tip**: Use `compact: true` to reduce output size (omits snippets).":"",x=`# Semantic Concept Search: "${e}"
|
|
558
|
+
|
|
559
|
+
Showing ${w.length} of ${S} relevant file(s) (offset: ${n}, limit: ${t})${T}${I}
|
|
560
|
+
|
|
561
|
+
`,R=new de(this.repoPath).getSection("gravity"),v=new Map;if(R?.hotspots)for(let L of R.hotspots)v.set(L.filePath,L.gravity);return{content:[{type:"text",text:o?x+w.map((L,H)=>{let B=c(L.path),ne=Math.round((L.decayedScore||0)*100),D=v.get(L.path)?" \u269B\uFE0F":"";return`${n+H+1}. \`${B}\`${D} (${ne}%) - ${L.summary||"No summary"}`}).join(`
|
|
562
|
+
`):x+w.map((L,H)=>{let B=c(L.path),ne=Math.round((L.decayedScore||0)*100),W=v.get(L.path),D=W?" \u269B\uFE0F **CORE**":"",M=W&&W>50?`
|
|
563
|
+
> \u26A0\uFE0F **STRATEGIC RISK**: High-gravity hotspot (${W.toFixed(0)}). Modifications may have significant architectural impact.`:"";return`## ${n+H+1}. ${B}${D} (${ne}% Match)
|
|
564
|
+
> **Rationale**: ${L.rationale}${M}
|
|
565
|
+
|
|
566
|
+
`+(L.snippet?`**Matched Snippet**:
|
|
567
|
+
\`\`\`typescript
|
|
568
|
+
${L.snippet}
|
|
569
|
+
\`\`\`
|
|
570
|
+
|
|
571
|
+
`:"")+`**Summary**: ${L.summary||"No summary available"}
|
|
572
|
+
`}).join(`
|
|
573
|
+
`)}]}}}let a=e.replace(/[^\w\s]/g," ").trim(),p=this.filesRepo.findFts(a,(t+n)*(r?oe.FILTERED_QUERY_LIMIT_MULTIPLIER:1));r&&(p=p.filter(y=>s.matchesFilters(y.path,i,y.mtime,y.classification)));let d=p.slice(n,n+t);if(d.length===0&&n===0){let y=this.filesRepo.getStats(),S=e.toLowerCase().split(/\s+/),w=this.filesRepo.findByPathKeywords(S,t);return r&&(w=w.filter(C=>s.matchesFilters(C.path,i,C.mtime,C.classification))),w.length>0?{content:[{type:"text",text:`# Concept Search: "${e}"
|
|
574
|
+
|
|
575
|
+
\u26A0\uFE0F No semantic matches in file summaries (${y.withSummary}/${y.total} indexed).
|
|
576
|
+
|
|
577
|
+
Found ${w.length} file(s) with matching paths:
|
|
578
|
+
|
|
579
|
+
`+w.map((T,I)=>`${I+1}. \`${c(T.path)}\` (${T.classification||"Unknown"})`).join(`
|
|
580
|
+
`)}]}:{content:[{type:"text",text:`No files found matching concept: "${e}"
|
|
581
|
+
|
|
582
|
+
Summary Stats: ${y.withSummary}/${y.total} summaries.
|
|
583
|
+
|
|
584
|
+
Try a symbol search: shadow_search_symbol({ query: "${e}", repoPath })`}]}}let u=p.length,h=n+t<u?`
|
|
585
|
+
> Use \`offset: ${n+t}\` for more results.`:"",b=o?`
|
|
586
|
+
> _Compact mode_`:u>20&&!o?"\n> \u{1F4A1} Use `compact: true` to reduce output size.":"",E=`# Concept Search (FTS Fallback): "${e}"
|
|
587
|
+
|
|
588
|
+
Showing ${d.length} of ${u} relevant file(s)${h}${b}
|
|
589
|
+
|
|
590
|
+
`;return{content:[{type:"text",text:o?E+d.map((y,S)=>`${n+S+1}. \`${c(y.path)}\``).join(`
|
|
591
|
+
`):E+d.map((y,S)=>`## ${n+S+1}. ${c(y.path)}
|
|
592
|
+
|
|
593
|
+
**Summary**: ${y.summary||"No summary available"}
|
|
594
|
+
`).join(`
|
|
595
|
+
`)}]}}async searchBySymbol(e,t,n,i,r){let o=e.toLowerCase(),l=x=>x.replace(this.repoPath,"").replace(/^\//,""),c;try{c=this.exportsRepo.findFts(`"${e}" OR ${e}*`,t+50)}catch{c=this.exportsRepo.findByPartialName(e,t+50)}if(c.length===0){let x=this.exportsRepo.getAllNames(5e3),$=$n(e,x,50,5);if($.length>0){let R=$.map(v=>` \u2022 \`${v.match}\` (${Math.round(v.score)}% ${v.matchType} match)`).join(`
|
|
596
|
+
`);return{content:[{type:"text",text:`No symbols found matching: "${e}"
|
|
597
|
+
|
|
598
|
+
**Did you mean?**
|
|
599
|
+
${R}
|
|
600
|
+
|
|
601
|
+
\u{1F4A1} Try shadow_search_symbol with fuzzy, or shadow_search_concept for semantic search.`}]}}return{content:[{type:"text",text:`No symbols found matching: "${e}"
|
|
602
|
+
|
|
603
|
+
\u{1F4A1} Try shadow_search_symbol (fuzzy) or shadow_search_concept for semantic search.`}]}}r&&(c=c.filter(x=>{let $=this.filesRepo.findByPath(x.file_path);return s.matchesFilters(x.file_path,i,$?.mtime,$?.classification)}));let a=new tt(this.repoPath),p=new de(this.repoPath),d=a.getAncestorMissionIds(),u=se(this.repoPath)||void 0,m=this.exportsRepo.getGravityMap(d,u),h=p.getSection("gravity"),b=new Map;if(h?.hotspots)for(let x of h.hotspots)b.set(`${x.filePath}::${x.symbol}`,x.gravity);let E="\u{1F525}",g="\u26A1",y="\u269B\uFE0F",S=c.map((x,$)=>{let R=m[x.id],v=b.get(`${x.file_path}::${x.name}`),P=this.filesRepo.findByPath(x.file_path),L=$e.getMultiplier(x.file_path,P?.classification),H=(oe.SCORE_BASE-$)*L;R&&(H+=R.score*oe.SCORE_BASE),v&&(H+=v*oe.SCORE_BASE*oe.GRAVITY_STRUCTURAL_WEIGHT),x.name.toLowerCase()===o&&(H+=oe.EXACT_MATCH_BONUS*L);let B=P?.mtime;if(B!=null){let W=B>1e10?B/1e3:B,D=(Date.now()/1e3-W)/ci.SECONDS_PER_DAY;D<oe.RECENT_FILE_THRESHOLD_DAYS?H+=oe.RECENT_FILE_BOOST:D<oe.OLDER_FILE_THRESHOLD_DAYS&&(H+=oe.OLDER_FILE_BOOST)}let ne=[];return R&&ne.push(...R.reasons),v&&ne.push(`Structural Hotspot (Gravity: ${v.toFixed(1)})`),{...x,activeGravity:R,structuralGravity:v,sortScore:H,reasons:ne}}).sort((x,$)=>$.sortScore-x.sortScore).slice(n,n+t),w=c.length,C=n+t<w,T=S.map((x,$)=>{let R=l(x.file_path),v=this.filesRepo.getContent(x.file_path),P="";if(v){let B=v.split(`
|
|
604
|
+
`);P=B.slice(Math.max(0,x.start_line-2),Math.min(B.length,x.start_line+3)).join(`
|
|
605
|
+
`).trim()}let L=[];x.activeGravity&&(x.activeGravity.reasons.some(B=>B.includes("Working Set"))?L.push(E):x.activeGravity.reasons.some(B=>B.includes("Recent Intent"))&&L.push(g)),x.structuralGravity&&L.push(y);let H=L.length>0?` ${L.join("")}`:"";return{relPath:R,name:x.name,kind:x.kind,signature:x.signature,line:x.start_line,snippet:P,badgeStr:H,gravityReasons:x.reasons}});return{content:[{type:"text",text:`# Symbol Search Results: "${e}"
|
|
606
|
+
|
|
607
|
+
Showing ${T.length} matching symbol(s)${C?` (use offset=${n+t} for more)`:""}:
|
|
608
|
+
|
|
609
|
+
`+T.map((x,$)=>{let R=`## ${n+$+1}. \`${x.name}\` (${x.kind})${x.badgeStr}
|
|
610
|
+
**File**: \`${x.relPath}:${x.line}\`
|
|
611
|
+
`;return x.gravityReasons&&(R+=`> *${x.gravityReasons.join(", ")}*
|
|
612
|
+
`),x.signature&&(R+=`**Signature**: \`${x.signature}\`
|
|
613
|
+
`),x.snippet&&(R+=`
|
|
614
|
+
\`\`\`typescript
|
|
615
|
+
${x.snippet}
|
|
616
|
+
\`\`\`
|
|
617
|
+
`),R}).join(`
|
|
618
|
+
`)}]}}async findConceptMatches(e,t,n,i,r,o=0){let l=se(this.repoPath)||void 0;if(!t)return[];let c=this.filesRepo.findWithEmbeddings(),p=new Ln(this.repoPath).getScorer(),u=new tt(this.repoPath).getAncestorMissionIds(),m=[];for(let h of c)try{let b=JSON.parse(h.embedding),E=ri(t,b),g=this.filesRepo.getContent(h.path),y=oe.ENABLE_LEXICAL_SCORING&&g?Ft.calculateLexicalScore(g,e):0,S=y>0?.1:.18;if(E>S){if(i&&!s.matchesFilters(h.path,n,h.mtime,h.classification))continue;let w=h.mtime>2e9?Math.floor(h.mtime/1e3):h.mtime,C=Math.floor(Date.now()/1e3)-ci.SECONDS_PER_YEAR,T=$e.getMultiplier(h.path,h.classification),I=p.calculateScore(E,w||C);I*=T;let $=this.filesRepo.getGravityMap(u,l)[h.path],R=h.classification?$e.mapClassificationToTier(h.classification):$e.classify(h.path,{content:g??void 0}),v=`Similarity: ${(E*100).toFixed(0)}%, Tier: ${R}${T!==1?` (${T}x)`:""}`;y>0&&(I+=y*oe.LEXICAL_WEIGHT,v+=` | Lexical: +${y.toFixed(1)}`),$&&(I+=$.score,v+=` | \u{1F525} Gravity: +${$.score.toFixed(1)} (${$.reasons.join(", ")})`);let P=g?Ft.extractSnippet(g,e):void 0;m.push({path:h.path,summary:h.summary||"",score:E,decayedScore:I,rationale:v,snippet:P})}}catch{}return m.sort((h,b)=>(b.decayedScore||0)-(h.decayedScore||0)),m}};N();F();function Nn(s){let{fileType:e,layer:t,dateModifiedAfter:n,dateModifiedBefore:i,includeTests:r}=s,o={fileType:je.normalizeFileType(e),layer:t,excludeLayers:r===!1?["Virtual"]:void 0,dateModifiedAfter:n,dateModifiedBefore:i},l=!!(o.fileType?.length||o.layer!=null||o.excludeLayers&&o.excludeLayers.length>0||o.dateModifiedAfter!=null||o.dateModifiedBefore!=null);return{filters:o,hasFilters:l}}async function Jr(s){let e=vn(s.query??""),t={...s,query:e},n=mn();try{let{repoPath:i}=xe(t),{query:r,limit:o=ot.DEFAULT_LIMIT,offset:l=0,skipSync:c=!1,compact:a=!1}=t;c||await j(i);let{filters:p,hasFilters:d}=Nn(t),m=await new je(i).searchByConcept(r,o,l,p,d,a);return xc(i,r,"concept"),n(),m}catch(i){return _.error({error:i,args:s},"Concept Search failed"),n(),await rt(),{content:[{type:"text",text:`Concept Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function xc(s,e,t){try{let n=k.getInstance(s),i=se(s);n.searchHistory.record(e,t,i)}catch(n){let i=se(s);_.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),rt()}}N();F();async function vi(s){let e=vn(s.query??""),t={...s,query:e},n=mn();try{let{repoPath:i}=xe(t),{query:r,limit:o=ot.DEFAULT_LIMIT,offset:l=0,skipSync:c=!1}=t;c||await j(i);let{filters:a,hasFilters:p}=Nn(t),u=await new je(i).searchBySymbol(r,o,l,a,p);return Rc(i,r,"symbol"),n(),u}catch(i){return _.error({error:i,args:s},"Symbol Search failed"),n(),await rt(),{content:[{type:"text",text:`Symbol Search failed: ${i instanceof Error?i.message:String(i)}`}],isError:!0}}}function Rc(s,e,t){try{let n=k.getInstance(s),i=se(s);n.searchHistory.record(e,t,i)}catch(n){let i=se(s);_.error({module:"search",repoPath:s,query:e,mode:t,error:n instanceof Error?n.message:String(n),branch:i},"Failed to record search history"),rt()}}F();N();import Yr from"path";async function Vr(s){let{repoPath:e,query:t,key:n="",kind:i,limit:r=50}=s,o=n||t;if(!o&&!i)return{content:[{type:"text",text:'Error: Either "key" or "kind" parameter is required.'}]};await j(e);let{configs:l}=k.getInstance(e);if(o){_.info({repoPath:e,key:o},"Searching for config key in DB...");let d=l.findByKey(o,r);if(d.length===0)return{content:[{type:"text",text:`No configuration found for key: ${o}`}]};let u=d.map(h=>({file:Yr.relative(e,h.file_path),key:h.key,value:h.value,kind:h.kind}));return{content:[{type:"text",text:`# Configuration Search: "${o}"
|
|
619
|
+
|
|
620
|
+
Found ${d.length} match(es):
|
|
621
|
+
|
|
622
|
+
`+u.map(h=>`## ${h.file} (${h.kind})
|
|
623
|
+
**${h.key}**: \`${h.value}\``).join(`
|
|
624
|
+
|
|
625
|
+
`)}]}}let c=l.findByKind(i||null,r),a=c.map(d=>({...d,file:Yr.relative(e,d.file_path)})),p=JSON.stringify(a,null,2);return c.length===r&&(p=`Results limited to ${r} entries. Use the 'limit' parameter to see more.
|
|
626
|
+
|
|
627
|
+
`+p),{content:[{type:"text",text:p}]}}F();import Qr from"path";async function An(s){let{repoPath:e,filePath:t}=xe(s);if(!t)return{content:[{type:"text",text:"Error: filePath is required"}],isError:!0};let n=s.detailLevel||"signatures";await j(e);let{files:i,exports:r}=k.getInstance(e),o=i.findByPath(t),l=Qr.basename(t),c=/\.(ts|tsx|php|py|go)$/.test(l),a;c?a=await Ct(t):a={exports:r.findByFile(t),imports:[]},n==="structure"?(a.exports=a.exports.map(m=>({name:m.name,kind:m.kind,line:m.start_line,classification:m.classification})),delete a.imports):n==="signatures"&&(a.exports=a.exports.map(m=>({name:m.name,kind:m.kind,signature:m.signature,line:m.start_line,classification:m.classification,capabilities:JSON.parse(m.capabilities||"[]")})),delete a.imports);let p=Qr.relative(e,t),d=a.exports?.length||0,u="";return n==="structure"&&d>0?u=`
|
|
628
|
+
|
|
629
|
+
\u{1F4A1} Showing ${d} symbol names. For full signatures: shadow_inspect_file({ filePath: "${p}", detailLevel: "signatures" })`:n==="signatures"&&d>0&&(u=`
|
|
630
|
+
|
|
631
|
+
\u{1F4A1} Showing ${d} complete signatures. To inspect a specific symbol: shadow_inspect_symbol({ symbolName: "...", context: "full" })`),{content:[{type:"text",text:JSON.stringify({...a,fileDescription:o?.summary||"",classification:o?.classification||"Unknown"},null,2)+u}]}}F();import Kr from"path";import Tc from"fs";function vc(s,e,t){let n=s.split(`
|
|
632
|
+
`),i=[],r=0;for(let d=0;d<Math.min(n.length,50);d++){let u=n[d].trim();if(u.startsWith("import ")||u.startsWith("from ")||u.startsWith("export ")&&u.includes(" from "))r=d+1;else if(u&&!u.startsWith("//")&&!u.startsWith("/*")&&!u.startsWith("*")&&u!==""&&r>0)break}r>0&&(i.push(...n.slice(0,r)),i.push(""));let o=[...t].sort((d,u)=>d.startLine-u.startLine),l=0,c=0;for(let d of o)if(d.isTarget){i.push(`// \u2501\u2501\u2501 REQUESTED: ${d.name} \u2501\u2501\u2501`);let u=n.slice(d.startLine-1,d.endLine);i.push(...u),i.push("// \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),i.push(""),c++}else{let u=d.signature||wc(n,d.startLine-1,d.kind);u&&(i.push(`${u}`),i.push(` /* implementation: ${d.lineCount} lines */`),i.push(""),l++)}let a=o[o.length-1];if(a)for(let d=a.endLine;d<n.length;d++){let u=n[d].trim();if(u==="}"||u==="};"){i.push(n[d]);break}else if(u&&!u.startsWith("//"))break}return{foldedSource:i.join(`
|
|
633
|
+
`),totalOriginalLines:n.length,foldedToLines:i.length,siblingsShown:c,siblingsFolded:l}}function wc(s,e,t){let n=s[e];if(t.includes("Function")||t.includes("Method")||t.includes("Arrow")){let i="";for(let r=e;r<Math.min(e+5,s.length);r++)if(i+=s[r],i.includes("{")||i.includes("=>")){let o=i.indexOf("{");o>0&&(i=i.substring(0,o).trim());break}return i.trim()}return n}async function gt(s){let{repoPath:e,filePath:t,resolver:n}=xe(s),i=String(s.symbolName),r=s.context||"definition";if(t&&!n.isWithinRoot(t))return{content:[{type:"text",text:`Error: Access denied. Path ${t} is outside the repository root.`}],isError:!0};await j(e);let o=k.getInstance(e),l=[];if(i.includes(".")){let[T,I]=i.split(".");l=o.exports.findMemberCandidates(T,I,t)}else l=o.exports.findDefinitionCandidates(i,t);if(l.length===0){let T=o.exports.findPotentialParents(i);if(T.length>0){let R=T.map(v=>`\`${v.name}\` (in ${n.getRelative(v.file_path)})`).join(", ");return{content:[{type:"text",text:`Symbol "${i}" not found as a top-level export.
|
|
634
|
+
However, it likely exists inside: ${R}.
|
|
635
|
+
Try: shadow_inspect_symbol({ symbolName: "${T[0].name}", context: "full" }) to see the class body.`}]}}let x=o.exports.findFuzzyCandidates(i).map(R=>R.name),$=$n(i,x,50,3);if($.length>0){let R=$.map(v=>` \u2022 \`${v.match}\` (${v.score}% match)`).join(`
|
|
636
|
+
`);return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
|
|
637
|
+
|
|
638
|
+
Suggestions:
|
|
639
|
+
${R}
|
|
640
|
+
|
|
641
|
+
Next steps:
|
|
642
|
+
\u2022 Search semantically: shadow_search_concept({ query: "${i}" })
|
|
643
|
+
\u2022 Verify repository is indexed: shadow_sync_index({ repoPath: "${e}" })`}]}}return{content:[{type:"text",text:`Error: Symbol "${i}" not found in the index.
|
|
644
|
+
|
|
645
|
+
Next steps:
|
|
646
|
+
\u2022 Search for it: shadow_search_concept({ query: "${i}" })
|
|
647
|
+
\u2022 Try with file path: shadow_inspect_symbol({ symbolName: "${i}", filePath: "..." })
|
|
648
|
+
`}]}}let c=l[0];if(c.kind==="ExportSpecifier"||c.kind==="ExportAllDeclaration"){let T=o.imports.findImportSource(c.file_path,i);if(T&&T.resolved_path)return gt({...s,filePath:T.resolved_path})}let a=Tc.readFileSync(c.file_path,"utf8"),p=a.split(`
|
|
649
|
+
`),d=c.end_line-c.start_line+1,u=150,m,h=!1,b=null;if(r==="definition"&&d>u){let I=o.exports.findSiblings(c.file_path).map(x=>({name:x.name,kind:x.kind,signature:x.signature||"",startLine:x.start_line,endLine:x.end_line,lineCount:x.end_line-x.start_line+1,isTarget:x.name===c.name&&x.start_line===c.start_line,parentName:x.parent_name}));if(I.length>1){b=vc(a,{name:c.name,startLine:c.start_line,endLine:c.end_line},I);let x=n.getRelative(c.file_path);m=b.foldedSource+`
|
|
650
|
+
|
|
651
|
+
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
652
|
+
\u{1F4CA} Semantic Fold Applied (context: "definition")
|
|
653
|
+
|
|
654
|
+
Original file: ${b.totalOriginalLines} lines
|
|
655
|
+
Folded view: ${b.foldedToLines} lines
|
|
656
|
+
Target Symbol: ${c.name}
|
|
657
|
+
\u{1F4A1} Need more context?
|
|
658
|
+
\u2022 Full symbol + dependencies + usage: shadow_inspect_symbol({ symbolName: "${c.name}", context: "full" })
|
|
659
|
+
\u2022 ALL symbols in this file: shadow_inspect_file({ filePath: "${x}", detailLevel: "signatures" })
|
|
660
|
+
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,h=!0}else m=p.slice(c.start_line-1,c.start_line-1+u).join(`
|
|
661
|
+
`)+`
|
|
662
|
+
|
|
663
|
+
... (truncated ${d-u} lines)`,h=!0}else m=p.slice(c.start_line-1,c.end_line).join(`
|
|
664
|
+
`);let E=c.parent_name?`${c.parent_name}.${c.name}`:c.name,g=o.exports.findHydratedById(c.id),y={name:E,kind:c.kind,file:n.getRelative(c.file_path),startLine:c.start_line,endLine:c.end_line,totalLines:d,...h&&{truncated:!0,previewLines:u},classification:c.classification,intelligence:g?{working_set_of:g.active_missions.map(T=>`Mission #${T.id}: ${T.name}`),total_intents:g.intent_log_count,latest_intent:g.recent_intents[0]?`${g.recent_intents[0].type}: ${g.recent_intents[0].content}`:null}:void 0,source:m};if(r==="definition")return{content:[{type:"text",text:JSON.stringify(y,null,2)}]};let S={definition:y,dependencies:o.imports.getImportsForFile(c.file_path).map(T=>({module:T.module_specifier,symbols:T.imported_symbols,relativePath:T.resolved_path?Kr.relative(e,T.resolved_path):null}))},w=[c.file_path],C=o.imports.findVerifiedDependents(w,i);return S.verifiedUsages=C.slice(0,10).map(T=>({file:Kr.relative(e,T.file_path),classification:T.classification,importedSymbols:T.imported_symbols})),{content:[{type:"text",text:JSON.stringify(S,null,2)}]}}async function Xr(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Semantic Concept Search");let n=ue();n.start(`Analyzing intent: "${f.bold(s)}"...`);try{let i=await Jr({repoPath:t,query:s});n.stop("Analysis complete.");let r=i.content[0].text;if(r.includes("Found")){let l=r.split("## ").slice(1).map(c=>{let[a,...p]=c.split(`
|
|
665
|
+
|
|
666
|
+
`),[d,u]=a.split(" ( "),m=(d??"").replace(/^\d+\.\s*/,"").trim(),h=p.find(b=>b.startsWith("**Summary**: "))?.replace("**Summary**: ","")||"";return{name:m,matchPct:u??"",summaryLine:h}});if(l.forEach(({name:c,matchPct:a,summaryLine:p})=>{te(`${f.green(c)} ${f.dim("("+(a||""))}`,p,"blue"),console.log("")}),e.interactive&&l.length>1){let c=await on("Inspect a file",l.map(a=>({value:{name:a.name},label:a.name,hint:a.summaryLine.slice(0,50)})),{limit:15});if(c){let a=c.name.startsWith(t)?c.name:Ht.join(t,c.name),p=await An({repoPath:t,filePath:a});p.content?.[0]&&(console.log(""),te(f.bold("File summary"),p.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await G(t)}})}async function Zr(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Symbol Search");let n=ue();n.start(`Searching symbols: "${f.bold(s)}"...`);try{let i=await vi({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;try{let o=JSON.parse(r);if(Array.isArray(o)){if(console.log(""),rn(["Symbol","Kind","File","Line"],o.map(l=>[f.bold(f.green(l.name)),f.dim(l.kind??""),f.cyan(l.file??""),f.yellow(String(l.line??""))])),e.interactive&&o.length>1){let l=o.map(a=>({value:a,label:a.name,hint:`${a.file??""}:${a.line??""}`})),c=await on("Inspect symbol",l,{limit:15});if(c){let a=await gt({repoPath:t,symbolName:c.name});a.content?.[0]&&(console.log(""),te(f.bold(c.name),a.content[0].text,"cyan"))}}}else console.log(r)}catch{console.log(r)}}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await G(t)}})}async function eo(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Fuzzy Symbol Search");let n=ue();n.start(`Fuzzy matching: "${f.bold(s)}"...`);try{let i=await vi({repoPath:t,query:s});n.stop("Search complete.");let r=i.content[0].text;if(r.includes("## ")){let l=r.split("## ").slice(1).map(c=>{let a=c.split(`
|
|
667
|
+
`),p=a[0],d=a.find(g=>g.startsWith("**Match**:"))||"",u=a.find(g=>g.startsWith("**File**:"))||"",m=p.match(/`([^`]+)`/),h=m?m[1]:"",b=d.match(/\*\*Match\*\*: (.+) \((\d+)% confidence\)/),E=u.match(/`([^:]+):(\d+)`/);return{symbolName:h,file:E?E[1]:"",line:E?E[2]:"",matchType:b?b[1]:"",confidence:b?b[2]:""}});if(console.log(""),console.log(f.dim(`Found ${l.length} fuzzy match(es):`)),console.log(""),l.forEach((c,a)=>{console.log(`${f.dim(`${a+1}.`)} ${f.bold(f.green(c.symbolName))} ${f.dim(`(${c.matchType}, ${c.confidence}% match)`)}`),console.log(` ${f.cyan(c.file)}:${f.yellow(c.line)}`),console.log("")}),e.interactive&&l.length>1){let c=await on("Inspect symbol",l.map(a=>({value:a,label:a.symbolName,hint:`${a.file}:${a.line}`})),{limit:15});if(c){let a=await gt({repoPath:t,symbolName:c.symbolName});a.content?.[0]&&(console.log(""),te(f.bold(c.symbolName),a.content[0].text,"cyan"))}}}else console.log(r)}catch(i){throw n.stop(`Search failed: ${i.message}`),i}finally{await G(t)}})}async function to(s,e){let t=Ht.resolve(e.dir);await U(async()=>{le("Config Search");let n=ue();n.start(`Searching config: ${f.bold(s||"all")}...`);try{let i=await Vr({repoPath:t,key:s,kind:e.kind});n.stop("Search complete."),te("\u2699\uFE0F Results",i.content[0].text,"yellow")}finally{await G(t)}})}N();var wi=_.child({module:"mcp:tools:env:hooks"});async function Mn(s){let{repoPath:e,action:t,enableAutoRefresh:n,enableSymbolHealing:i}=s;if(t==="install"){wi.info({repoPath:e,enableAutoRefresh:n,enableSymbolHealing:i},"Installing git hooks");let r=gs({repoPath:e,enableAutoRefresh:n??!0,enableSymbolHealing:i??!0}),o=["# Git Hooks Installation","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(l=>`- \`${l}\``).join(`
|
|
668
|
+
`):"- None","",`## \u23ED\uFE0F Skipped (${r.skipped.length})`,r.skipped.length>0?r.skipped.map(l=>`- \`${l}\` (already installed)`).join(`
|
|
669
|
+
`):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(l=>`- ${l}`).join(`
|
|
670
|
+
`)),o.push("")),o.push("---"),o.push("**What happens now?**"),(n??!0)&&o.push("- After `git pull` or `git checkout`: Index auto-refreshes in background"),(i??!0)&&o.push("- After `git commit`: Symbol shift detection runs automatically"),{content:[{type:"text",text:o.join(`
|
|
671
|
+
`)}]}}if(t==="remove"){wi.info({repoPath:e},"Uninstalling git hooks");let r=ys(e),o=["# Git Hooks Uninstallation","",`## Removed (${r.removed.length})`,r.removed.length>0?r.removed.map(l=>`- \`${l}\``).join(`
|
|
672
|
+
`):"- None",""];return r.errors.length>0&&(o.push(`## Errors (${r.errors.length})`),o.push(r.errors.map(l=>`- ${l}`).join(`
|
|
673
|
+
`))),{content:[{type:"text",text:o.join(`
|
|
674
|
+
`)}]}}if(t==="status"){wi.info({repoPath:e},"Checking git hooks status");let r=un(e);return{content:[{type:"text",text:["# Git Hooks Status","",`## Installed (${r.installed.length})`,r.installed.length>0?r.installed.map(l=>`- \`${l}\``).join(`
|
|
675
|
+
`):"- None","",`## Not Installed (${r.notInstalled.length})`,r.notInstalled.length>0?r.notInstalled.map(l=>`- \`${l}\``).join(`
|
|
676
|
+
`):"- None","","---",'**To install hooks**: Use `shadow_env_hooks({ action: "install" })`'].join(`
|
|
677
|
+
`)}]}}return{content:[{type:"text",text:`Unknown action: ${t}`}],isError:!0}}async function no(s){let[e,t="."]=s;if(!e||!["install","uninstall","status"].includes(e)){console.log(""),console.log(` ${f.bold("Usage: ")} liquid-shadow hooks <install|uninstall|status> [path]`),console.log(""),console.log(` ${f.bold("Commands: ")}`),console.log(` ${f.cyan("install")} Install git hooks for automatic index refresh and symbol healing`),console.log(` ${f.cyan("uninstall")} Remove installed git hooks`),console.log(` ${f.cyan("status")} Check git hooks installation status`),console.log(""),console.log(` ${f.bold("Examples: ")}`),console.log(" liquid-shadow hooks install ."),console.log(" liquid-shadow hooks status /path/to/repo"),console.log("");return}await U(async()=>{let n=Wo("path").resolve(t);switch(e){case"install":{let i=await Mn({repoPath:n,action:"install",enableAutoRefresh:!0,enableSymbolHealing:!0});if(console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Git hooks installed successfully")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);console.log(` ${f.bold("Installed hooks: ")}`),r.hooks.forEach(o=>{console.log(` ${f.cyan("\u2022")} ${o}`)}),console.log("")}catch{console.log(i.content[0].text)}break}case"uninstall":{await Mn({repoPath:n,action:"remove"}),console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Git hooks uninstalled successfully")}`),console.log("");break}case"status":{let i=await Mn({repoPath:n,action:"status"});if(console.log(""),console.log(` ${f.bold("Git Hooks Status")}`),console.log(""),i.content&&i.content[0])try{let r=JSON.parse(i.content[0].text);r.installed&&r.installed.length>0?(console.log(` ${f.green("\u2714")} Installed hooks:`),r.installed.forEach(o=>{console.log(` ${f.cyan("\u2022")} ${o}`)})):console.log(` ${f.yellow("\u26A0")} No hooks installed`),r.missing&&r.missing.length>0&&(console.log(""),console.log(` ${f.dim("Missing hooks: ")}`),r.missing.forEach(o=>{console.log(` ${f.dim("\u2022")} ${o}`)}))}catch{console.log(i.content[0].text)}console.log("");break}}})}F();N();import Ic from"path";import kc from"fs";var io=_.child({module:"mcp:tools:workspace:list"});async function so(s){let{repoPaths:e,status:t}=s;io.info({repoCount:e.length,status:t},"Getting workspace missions");let n=[];for(let i of e)if(kc.existsSync(i))try{let{missions:r}=k.getInstance(i),o=r.findAll(t);for(let l of o){let c=r.getLinks(l.id);n.push({...l,repo_path:i,repo_name:Ic.basename(i),cross_repo_links:c})}}catch(r){io.error({error:r,repoPath:i},"Failed to query repo missions")}return n.sort((i,r)=>{let o=a=>a==="in-progress"?0:a==="verifying"?1:2,l=o(i.status),c=o(r.status);return l!==c?l-c:(i.created_at||0)-(r.created_at||0)}),{content:[{type:"text",text:JSON.stringify({total_missions:n.length,missions:n},null,2)}]}}F();N();var Cc=_.child({module:"mcp:tools:workspace:link"});async function ro(s){let{parentRepoPath:e,parentMissionId:t,childRepoPath:n,childMissionId:i,relationship:r="related"}=s;Cc.info({parentRepoPath:e,childRepoPath:n},"Linking cross-repo missions");let{missions:o}=k.getInstance(e),{missions:l}=k.getInstance(n);try{let c=o.findById(t),a=l.findById(i);if(!c)throw new Error(`Parent mission ${t} not found`);if(!a)throw new Error(`Child mission ${i} not found`);return o.createLink(t,n,i,r,"parent"),l.createLink(i,e,t,r,"child"),{content:[{type:"text",text:JSON.stringify({status:"linked",relationship:r},null,2)}]}}catch(c){throw new Error(`Failed to link: ${c.message}`)}}N();import Hc from"path";N();Ve();import Lc from"better-sqlite3";import yt from"path";import oo from"fs";import $c from"os";import Nc from"crypto";var Ac=_.child({module:"fusion-connection"}),Pn=5,Mc=1,ao=["files","exports","imports","configs","schema_migrations"],Dn=class{fusionDb;attachedRepos=new Map;fusionDbPath;name;constructor(e){this.name=e.name,this.fusionDbPath=this.getFusionDbPath(e.name),Ac.info({name:e.name,path:this.fusionDbPath},"Initializing fused index connection");let t=yt.dirname(this.fusionDbPath);oo.existsSync(t)||oo.mkdirSync(t,{recursive:!0}),this.fusionDb=new Lc(this.fusionDbPath),this.fusionDb.pragma("journal_mode = WAL"),this.fusionDb.pragma("busy_timeout = 5000"),this.initFusionSchema();for(let n of e.repoPaths)this.attachRepo(n)}getFusionDbPath(e){let t=$c.homedir(),n=yt.join(t,".mcp-liquid-shadow","fused"),i=e.replace(/[^a-zA-Z0-9-_]/g,"_");return yt.join(n,`${i}.db`)}initFusionSchema(){this.fusionDb.exec(`
|
|
678
|
+
CREATE TABLE IF NOT EXISTS fused_repos (
|
|
679
|
+
alias TEXT PRIMARY KEY,
|
|
680
|
+
repo_path TEXT NOT NULL UNIQUE,
|
|
681
|
+
db_path TEXT NOT NULL,
|
|
682
|
+
schema_version INTEGER NOT NULL,
|
|
683
|
+
attached_at REAL DEFAULT (unixepoch()),
|
|
684
|
+
last_validated_at REAL
|
|
685
|
+
);
|
|
686
|
+
|
|
687
|
+
CREATE TABLE IF NOT EXISTS fused_metadata (
|
|
688
|
+
key TEXT PRIMARY KEY,
|
|
689
|
+
value TEXT NOT NULL,
|
|
690
|
+
updated_at REAL DEFAULT (unixepoch())
|
|
691
|
+
);
|
|
692
|
+
|
|
693
|
+
CREATE TABLE IF NOT EXISTS virtual_edges (
|
|
694
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
695
|
+
source_repo TEXT NOT NULL,
|
|
696
|
+
source_file_path TEXT NOT NULL,
|
|
697
|
+
source_symbol_id INTEGER,
|
|
698
|
+
target_repo TEXT NOT NULL,
|
|
699
|
+
target_file_path TEXT NOT NULL,
|
|
700
|
+
target_symbol_id INTEGER,
|
|
701
|
+
relationship TEXT NOT NULL,
|
|
702
|
+
metadata TEXT,
|
|
703
|
+
confidence REAL DEFAULT 1.0,
|
|
704
|
+
created_at REAL DEFAULT (unixepoch()),
|
|
705
|
+
updated_at REAL DEFAULT (unixepoch()),
|
|
706
|
+
UNIQUE(source_repo, source_file_path, target_repo, target_file_path, relationship)
|
|
707
|
+
);
|
|
708
|
+
|
|
709
|
+
CREATE INDEX IF NOT EXISTS idx_virtual_edges_source ON virtual_edges(source_repo, source_file_path);
|
|
710
|
+
CREATE INDEX IF NOT EXISTS idx_virtual_edges_target ON virtual_edges(target_repo, target_file_path);
|
|
711
|
+
`),this.fusionDb.prepare("INSERT OR REPLACE INTO fused_metadata (key, value, updated_at) VALUES ('schema_version', ?, unixepoch())").run(Mc.toString())}attachRepo(e){let t=yt.resolve(e);if(this.attachedRepos.has(t))return;if(!Ye(t))throw new Error(`Repository "${t}" is not indexed. Run shadow_recon_onboard({ repoPath: "${t}" }) then shadow_sync_trace({ repoPath: "${t}" }).`);let n=ke(t),i=n.name;this.validateSchemaCompatibility(n,t);let r=this.getSchemaVersion(n),o=this.generateAlias(t),l=3,c=100;for(let a=1;a<=l;a++)try{this.fusionDb.exec(`ATTACH DATABASE '${i}' AS ${o}`);let p={alias:o,repoPath:t,dbPath:i,schemaVersion:r,attached:!0};this.attachedRepos.set(t,p),this.fusionDb.prepare(`INSERT OR REPLACE INTO fused_repos (alias, repo_path, db_path, schema_version, attached_at, last_validated_at)
|
|
712
|
+
VALUES (?, ?, ?, ?, unixepoch(), unixepoch())`).run(o,t,i,r);return}catch(p){let d=p instanceof Error?p.message.toLowerCase():String(p).toLowerCase();if((d.includes("locked")||d.includes("busy"))&&a<l){this.sleep(c*a);continue}throw p}}checkHealth(){let e=[];for(let t of this.attachedRepos.values())try{this.fusionDb.prepare(`SELECT 1 FROM ${t.alias}.files LIMIT 1`).get(),e.push({alias:t.alias,repoPath:t.repoPath,accessible:!0})}catch(n){e.push({alias:t.alias,repoPath:t.repoPath,accessible:!1,error:n instanceof Error?n.message:String(n)})}return{healthy:e.every(t=>t.accessible),repos:e}}detachRepo(e){let t=yt.resolve(e),n=this.attachedRepos.get(t);n&&(this.fusionDb.exec(`DETACH DATABASE ${n.alias}`),this.attachedRepos.delete(t),this.fusionDb.prepare("DELETE FROM fused_repos WHERE repo_path = ?").run(t))}refreshRepo(e){this.detachRepo(e),this.attachRepo(e)}refreshAll(){let e=Array.from(this.attachedRepos.keys());for(let t of e)this.refreshRepo(t)}validateSchemas(){let e=Array.from(this.attachedRepos.values()).map(t=>{let n=ke(t.repoPath),i=ao.filter(o=>!this.checkTableExists(n,o)),r=this.getSchemaVersion(n);return{alias:t.alias,repoPath:t.repoPath,schemaVersion:r,compatible:r>=Pn&&i.length===0,missingTables:i}});return{valid:e.every(t=>t.compatible),minVersion:Pn,repos:e}}getAttachedRepos(){return Array.from(this.attachedRepos.values())}prepare(e){return this.fusionDb.prepare(e)}exec(e){this.fusionDb.exec(e)}close(){for(let e of this.attachedRepos.values())try{this.fusionDb.exec(`DETACH DATABASE ${e.alias}`)}catch{}this.attachedRepos.clear(),this.fusionDb.open&&this.fusionDb.close()}generateAlias(e){let t=yt.basename(e).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),n=Nc.createHash("sha256").update(e).digest("hex").substring(0,6);return`repo_${t}_${n}`}getSchemaVersion(e){try{return e.prepare("SELECT MAX(version) as version FROM schema_migrations").get()?.version||0}catch{return 0}}validateSchemaCompatibility(e,t){let n=this.getSchemaVersion(e);if(n<Pn)throw new Error(`Schema version mismatch for ${t}. Expected >= ${Pn}, got ${n}.`);let i=ao.filter(r=>!this.checkTableExists(e,r));if(i.length>0)throw new Error(`Missing tables in ${t}: ${i.join(", ")}`)}checkTableExists(e,t){try{return!!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)}catch{return!1}}sleep(e){let t=Date.now()+e;for(;Date.now()<t;);}get nameValue(){return this.name}get dbPath(){return this.fusionDbPath}};N();var Be=_.child({module:"edge-scanner"});function Ii(s){let e=s.split("?")[0].split("#")[0];return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Pc(s){if(!s)return null;try{let e=JSON.parse(s);return e.path||e.name||null}catch{return null}}function Dc(s,e){let t=Ii(s),n=Ii(e);if(t===n)return!0;let i=n.replace(/:[^/]+/g,"[^/]+").replace(/\{[^}]+\}/g,"[^/]+").replace(/\$[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function Oc(s){Be.info("Starting HTTP gap detection scan");let e=s.getAttachedRepos();if(e.length<2)return Be.warn("Need at least 2 repos for cross-repo dependency detection"),0;let t=[];for(let r of e)try{let o=`
|
|
713
|
+
SELECT id, name, file_path, capabilities
|
|
714
|
+
FROM ${r.alias}.exports
|
|
715
|
+
WHERE kind = 'HTTP Route'
|
|
716
|
+
`,l=s.executeRawQuery(o);for(let c of l){let a=Pc(c.capabilities)||c.name;a&&a.startsWith("/")&&t.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,symbolId:c.id,routePath:a})}}catch(o){Be.warn({repo:r.alias,error:o},"Failed to query backend routes")}Be.debug({count:t.length},"Found backend routes");let n=[];for(let r of e)try{let o=`
|
|
717
|
+
SELECT file_path, name
|
|
718
|
+
FROM ${r.alias}.event_synapses
|
|
719
|
+
WHERE type = 'api_route' AND direction = 'produce'
|
|
720
|
+
`,l=s.executeRawQuery(o);for(let c of l){let a=Ii(c.name);a&&a.startsWith("/")&&n.push({repo:r.alias,repoPath:r.repoPath,filePath:c.file_path,routePath:a})}}catch(o){Be.warn({repo:r.alias,error:o},"Failed to query frontend API calls")}Be.debug({count:n.length},"Found frontend API calls");let i=0;for(let r of n)for(let o of t)if(r.repoPath!==o.repoPath&&Dc(r.routePath,o.routePath))try{s.addVirtualEdge({sourceRepo:r.repoPath,sourceFilePath:r.filePath,targetRepo:o.repoPath,targetFilePath:o.filePath,targetSymbolId:o.symbolId,relationship:"api_call",metadata:{frontendPath:r.routePath,backendPath:o.routePath,method:o.method},confidence:1}),i++}catch(l){Be.debug({source:r.filePath,target:o.filePath,error:l},"Skipped duplicate edge")}return Be.info({edgesCreated:i,backendRoutes:t.length,frontendCalls:n.length},"HTTP gap detection scan completed"),i}function co(s){let e=Oc(s);return{httpGaps:e,totalEdges:e}}N();var Fc=_.child({module:"fusion-index-service"}),On=class{constructor(e){this.connection=e}executeFederatedQuery(e,...t){return this.connection.prepare(e).all(...t).map(r=>{let{_repo_alias:o,_repo_path:l,...c}=r;return{repo:o,repoPath:l,data:c}})}executeRawQuery(e,...t){return this.connection.prepare(e).all(...t)}buildAdvancedQuery(e){let t=this.connection.getAttachedRepos();if(t.length===0)throw new Error("No repositories attached");let{table:n,tableAlias:i,columns:r,joins:o,where:l,groupBy:c,having:a,orderBy:p,limit:d,offset:u}=e,m=i||n.charAt(0),h=r.join(", "),E=t.map(g=>{let y=`${g.alias}.${n} ${m}`,S="";o&&o.length>0&&(S=o.map(I=>{let x=I.alias||I.table.charAt(0);return`${I.type} JOIN ${g.alias}.${I.table} ${x} ON ${I.on}`}).join(`
|
|
721
|
+
`));let w=l?`WHERE ${l}`:"",C=c&&c.length>0?`GROUP BY ${c.join(", ")}`:"",T=a?`HAVING ${a}`:"";return`SELECT '${g.alias}' as _repo_alias, '${g.repoPath}' as _repo_path, ${h} FROM ${y} ${S} ${w} ${C} ${T}`.trim()}).join(`
|
|
722
|
+
UNION ALL
|
|
723
|
+
`);return p&&(E=`SELECT * FROM (${E}) AS federated_results ORDER BY ${p}`),d!==void 0&&(E+=` LIMIT ${d}`),u!==void 0&&(E+=` OFFSET ${u}`),E}buildFtsQuery(e,t,n,i,r=50){let o=this.connection.getAttachedRepos();if(o.length===0)throw new Error("No repositories attached");let l=n.replace(/"/g,'""'),c=i.map(p=>`c.${p}`).join(", ");return`${o.map(p=>`
|
|
724
|
+
SELECT '${p.alias}' as _repo_alias, '${p.repoPath}' as _repo_path, ${c}, bm25(${p.alias}.${e}) as _fts_rank
|
|
725
|
+
FROM ${p.alias}.${e} fts
|
|
726
|
+
JOIN ${p.alias}.${t} c ON fts.rowid = c.id
|
|
727
|
+
WHERE ${p.alias}.${e} MATCH '"${l}"'`).join(`
|
|
728
|
+
UNION ALL
|
|
729
|
+
`)} ORDER BY _fts_rank LIMIT ${r}`}buildCrossRepoImportsQuery(){let e=this.connection.getAttachedRepos();if(e.length<2)throw new Error("Cross-repo analysis requires at least 2 attached repositories");let t=[];for(let n of e)for(let i of e)n.alias!==i.alias&&t.push(`
|
|
730
|
+
SELECT
|
|
731
|
+
'${n.alias}' as source_repo, '${n.repoPath}' as source_repo_path,
|
|
732
|
+
i.file_path as source_file, i.module_specifier, i.imported_symbols,
|
|
733
|
+
'${i.alias}' as target_repo, '${i.repoPath}' as target_repo_path,
|
|
734
|
+
f.path as target_file
|
|
735
|
+
FROM ${n.alias}.imports i
|
|
736
|
+
JOIN ${i.alias}.files f ON i.resolved_path = f.path
|
|
737
|
+
WHERE i.resolved_path IS NOT NULL`);return t.join(`
|
|
738
|
+
UNION ALL
|
|
739
|
+
`)}buildUnionQuery(e,t,n){let i=this.connection.getAttachedRepos();if(i.length===0)throw new Error("No repositories attached");let r=t.join(", "),o=n?` WHERE ${n}`:"";return i.map(l=>`SELECT '${l.alias}' as _repo_alias, '${l.repoPath}' as _repo_path, ${r} FROM ${l.alias}.${e}${o}`).join(`
|
|
740
|
+
UNION ALL
|
|
741
|
+
`)}searchExports(e,t=50){let n=this.buildUnionQuery("exports",["id","name","kind","file_path","signature"],"name LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}searchFiles(e,t=50){let n=this.buildUnionQuery("files",["path","classification","content_hash"],"path LIKE ?")+` LIMIT ${t*this.connection.getAttachedRepos().length}`,i=Array(this.connection.getAttachedRepos().length).fill(`%${e}%`);return this.executeFederatedQuery(n,...i)}getVirtualEdges(e,t){let n="SELECT * FROM virtual_edges WHERE 1=1",i=[];return e&&(n+=" AND source_repo = ?",i.push(e)),t&&(n+=" AND target_repo = ?",i.push(t)),this.connection.prepare(n).all(...i)}addVirtualEdge(e){return this.connection.prepare(`
|
|
742
|
+
INSERT INTO virtual_edges
|
|
743
|
+
(source_repo, source_file_path, source_symbol_id, target_repo, target_file_path, target_symbol_id, relationship, metadata, confidence, updated_at)
|
|
744
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
|
|
745
|
+
`).run(e.sourceRepo,e.sourceFilePath,e.sourceSymbolId||null,e.targetRepo,e.targetFilePath,e.targetSymbolId||null,e.relationship,e.metadata?JSON.stringify(e.metadata):null,e.confidence??1).lastInsertRowid}scanEdges(){return Fc.info({name:this.connection.nameValue},"Starting edge scan"),co(this)}getAttachedRepos(){return this.connection.getAttachedRepos()}get name(){return this.connection.nameValue}};var lo=_.child({module:"fused-index"}),Ci=class{connection;service;configName;constructor(e){this.configName=e.name,this.connection=new Dn(e),this.service=new On(this.connection)}attachRepo(e){this.connection.attachRepo(e)}detachRepo(e){this.connection.detachRepo(e)}refreshRepo(e){this.connection.refreshRepo(e)}getAttachedRepos(){return this.connection.getAttachedRepos()}checkHealth(){return this.connection.checkHealth()}close(){this.connection.close(),lo.info({name:this.configName},"Fused index closed")}getStatus(){let e=this.service.executeRawQuery("SELECT COUNT(*) as count FROM virtual_edges");return{name:this.connection.nameValue,path:this.connection.dbPath,attachedRepos:this.connection.getAttachedRepos().length,repos:this.connection.getAttachedRepos(),virtualEdgesCount:e[0]?.count||0}}searchExports(e,t=50){return this.service.searchExports(e,t)}searchFiles(e,t=50){return this.service.searchFiles(e,t)}getVirtualEdges(e,t){return this.service.getVirtualEdges(e,t)}addVirtualEdge(e){return this.service.addVirtualEdge(e)}scanEdges(){return this.service.scanEdges()}buildUnionQuery(e,t,n){return this.service.buildUnionQuery(e,t,n)}executeFederatedQuery(e,...t){return this.service.executeFederatedQuery(e,...t)}executeRawQuery(e,...t){return this.service.executeRawQuery(e,...t)}buildAdvancedQuery(e){return this.service.buildAdvancedQuery(e)}buildFtsQuery(e,t,n,i,r){return this.service.buildFtsQuery(e,t,n,i,r)}buildCrossRepoImportsQuery(){return this.service.buildCrossRepoImportsQuery()}refreshAll(){this.connection.refreshAll()}validateSchemas(){return lo.debug({name:this.configName},"Delegating validateSchemas"),this.connection.validateSchemas()}},ki=new Map;function po(s){let e=ki.get(s.name);if(e){let n=new Set(e.getAttachedRepos().map(o=>o.repoPath)),i=new Set(s.repoPaths.map(o=>Hc.resolve(o)));if(n.size===i.size&&[...n].every(o=>i.has(o)))return e;e.close(),ki.delete(s.name)}let t=new Ci(s);return ki.set(s.name,t),t}N();var Wc=_.child({module:"mcp:tools:workspace:fuse"});async function uo(s){let{repoPaths:e,name:t}=s;Wc.info({repoCount:e.length,name:t},"Creating fused workspace index");try{let n=po({repoPaths:e,name:t||`workspace-${Date.now()}`});return{content:[{type:"text",text:JSON.stringify({message:"Fused index created",status:n.getStatus()},null,2)}]}}catch(n){throw new Error(`Failed to fuse: ${n.message}`)}}import Fn from"path";async function mo(s){let[e,...t]=s;if(!e||!["missions","link","fuse"].includes(e)){console.log(""),console.log(` ${f.bold("Usage: ")} liquid-shadow workspace <missions|link> [options]`),console.log(""),console.log(` ${f.bold("Commands: ")}`),console.log(` ${f.cyan("missions")} <paths...> Get unified view of missions across repositories`),console.log(` ${f.cyan("link")} <args...> Link missions across repositories`),console.log(` ${f.cyan("fuse")} <paths...> Create fused index for cross-repo search (use --name for custom name)`),console.log(""),console.log(` ${f.bold("Examples: ")}`),console.log(" liquid-shadow workspace missions /frontend /backend"),console.log(" liquid-shadow workspace link /frontend 5 /backend 12"),console.log(" liquid-shadow workspace fuse /frontend /backend --name my-app"),console.log("");return}await U(async()=>{switch(e){case"missions":{if(t.length===0){console.error(` ${f.red("\u2716")} Please provide at least one repository path`);return}let n=t.map(r=>Fn.resolve(r)),i=await so({repoPaths:n});if(console.log(""),console.log(` ${f.bold("Workspace Missions")}`),console.log(""),i.content&&i.content[0]){let r=JSON.parse(i.content[0].text);r.missions&&r.missions.length>0?r.missions.forEach(o=>{console.log(` ${f.cyan("\u2022")} ${f.bold(o.name)} (ID: ${o.id})`),console.log(` ${f.dim("Repo: ")} ${o.repo_path}`),console.log(` ${f.dim("Status: ")} ${o.status}`),console.log(` ${f.dim("Branch: ")} ${o.git_branch||"N/A"}`),o.cross_repo_links&&o.cross_repo_links.length>0&&console.log(` ${f.dim("Links: ")} ${o.cross_repo_links.length} cross-repo link(s)`),console.log("")}):(console.log(` ${f.yellow("\u26A0")} No missions found`),console.log(""))}break}case"link":{if(t.length<4){console.error(""),console.error(` ${f.red("\u2716")} Usage: workspace link <parent-repo> <parent-id> <child-repo> <child-id> [relationship]`),console.error("");return}let[n,i,r,o,l]=t;await ro({parentRepoPath:Fn.resolve(n),parentMissionId:parseInt(i,10),childRepoPath:Fn.resolve(r),childMissionId:parseInt(o,10),relationship:l}),console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Missions linked successfully")}`),console.log(` ${f.dim("Parent: ")} ${n} (Mission ${i})`),console.log(` ${f.dim("Child: ")} ${r} (Mission ${o})`),l&&console.log(` ${f.dim("Relationship: ")} ${l}`),console.log("");break}case"fuse":{if(t.length===0){console.error(` ${f.red("\u2716")} Please provide at least one repository path`);return}let n,i=[];for(let o=0;o<t.length;o++)t[o]==="--name"&&o+1<t.length?(n=t[o+1],o++):i.push(Fn.resolve(t[o]));let r=await uo({repoPaths:i,name:n});if(console.log(""),console.log(` ${f.green("\u2714")} ${f.bold("Fused Index Created")}`),r.content&&r.content[0]){let o=JSON.parse(r.content[0].text);console.log(` ${f.dim("Name: ")} ${o.fused_index.name}`),console.log(` ${f.dim("Path: ")} ${o.fused_index.path}`),console.log(` ${f.dim("Repos: ")} ${o.fused_index.attachedRepos}`),console.log(""),console.log(` ${f.bold("Instructions:")}`),console.log(` ${o.instructions}`)}console.log("");break}}})}N();N();var Uc=_.child({module:"strategy-normalizer"}),Ne=class{static normalize(e){if(!e)return{steps:[]};let t;if(typeof e=="string")try{t=JSON.parse(e)}catch(i){return Uc.warn({strategyInput:e,err:i},"Failed to parse strategy JSON"),{steps:[]}}else t=e;return{steps:this.normalizeSteps(t)}}static normalizeSteps(e){return Array.isArray(e)?e.map((t,n)=>typeof t=="string"?{id:`step-${n}`,description:t,status:"pending"}:typeof t=="object"&&t!==null?{id:t.id||`step-${n}`,description:t.description||t.content||t.name||`Step ${n+1}`,status:t.status||"pending",dependencies:t.dependencies||t.deps,verification:t.verification,...t}:{id:`step-${n}`,description:String(t),status:"pending"}):e.steps&&Array.isArray(e.steps)?this.normalizeSteps(e.steps):typeof e=="object"?Object.entries(e).map(([t,n],i)=>typeof n=="string"?{id:t,description:n,status:"pending"}:typeof n=="object"&&n!==null?{id:t,description:n.description||n.content||n.name||t,status:n.status||"pending",dependencies:n.dependencies||n.deps,verification:n.verification,...n}:{id:t||`step-${i}`,description:String(n),status:"pending"}):[]}static stringify(e){return JSON.stringify(e,null,2)}static validate(e){let t=[];if(!e)return{valid:!0,errors:[]};try{let n=this.normalize(e),i=new Set;for(let r of n.steps)if(i.has(r.id)&&t.push(`Duplicate step ID: ${r.id}`),i.add(r.id),r.dependencies)for(let o of r.dependencies)i.has(o)||t.push(`Step "${r.id}" depends on non-existent step "${o}"`);return{valid:t.length===0,errors:t}}catch(n){return t.push(`Strategy validation failed: ${n instanceof Error?n.message:String(n)}`),{valid:!1,errors:t}}}};var jc=[{id:"step-0",description:"Analyze impact: identify dependents and call sites",status:"pending"},{id:"step-1",description:"Implement refactor and update call sites",status:"pending"},{id:"step-2",description:"Run tests and verify behavior; update docs if needed",status:"pending"}],Bc=[{id:"step-0",description:"Capture requirements and acceptance criteria",status:"pending"},{id:"step-1",description:"Implement feature with tests",status:"pending"},{id:"step-2",description:"Integrate and verify end-to-end",status:"pending"}],zc=[{id:"step-0",description:"Reproduce the bug and document steps",status:"pending"},{id:"step-1",description:"Diagnose root cause and plan fix",status:"pending"},{id:"step-2",description:"Apply fix and add/update regression test",status:"pending"},{id:"step-3",description:"Verify fix and run full test suite",status:"pending"}],Gc=[{id:"refactoring",name:"Refactoring",description:"Impact analysis \u2192 implementation \u2192 verification",defaultGoal:"Refactor {{target}} safely with full impact analysis and verification.",steps:jc},{id:"feature",name:"Feature",description:"Requirements \u2192 implementation \u2192 testing",defaultGoal:"Implement {{target}} with clear requirements and end-to-end verification.",steps:Bc},{id:"bug-fix",name:"Bug fix",description:"Reproduction \u2192 diagnosis \u2192 fix \u2192 regression test",defaultGoal:"Fix {{target}}: reproduce, diagnose, fix, and add regression test.",steps:zc}],ho=new Map(Gc.map(s=>[s.id,s]));function qc(s){return ho.get(s)}function Jc(s,e){let t=s;for(let[n,i]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${n}\\}\\}`,"g"),i);return t}function fo(s,e,t={}){let n=qc(s);if(!n)throw new Error(`Unknown template: ${s}. Use one of: ${Array.from(ho.keys()).join(", ")}`);let i=t.target||"scope",r=e||(s==="refactoring"?`Refactor ${i}`:s==="feature"?`Feature: ${i}`:`Fix: ${i}`),o=Jc(n.defaultGoal,{...t,target:i}),l=Ne.normalize({steps:n.steps}),c=Ne.stringify(l);return{name:r,goal:o,strategy:c}}F();var Hn=_.child({module:"mcp:tools:ops:plan"});async function go(s){let{repoPath:e,name:t,goal:n,strategy:i,missionId:r,parentId:o,outcomeContract:l,templateId:c,templateVars:a}=s,{missions:p}=k.getInstance(e),d=se(e),u=fe(e);Hn.info({repoPath:e,name:t,missionId:r,templateId:c},"Planning mission");try{let m=t,h=n,b=i;if(c){let S=fo(c,t,a||{});m=m??S.name,h=h??S.goal,b=b??S.strategy}if(!m||!h)throw new Error("Mission requires name and goal (or templateId with optional templateVars).");let E=null;if(b){let S=Ne.normalize(b);E=Ne.stringify(S);let w=Ne.validate(E);w.valid||Hn.warn({errors:w.errors,strategy:b},"Strategy validation warnings detected")}let g,y;r?(p.update(r,{name:m,goal:h,strategy_graph:E,commit_sha:u,parent_id:o!==void 0?o:void 0,outcome_contract:l}),g=r,y=`Mission "${m}" updated.`):(g=p.create({name:m,goal:h,strategy_graph:E,status:"planned",git_branch:d,commit_sha:u,parent_id:o||null,verification_context:null,outcome_contract:l||null}),y=`Mission "${m}" planned.`);try{await new Re(e).syncMissionToGitNotes(Number(g))}catch(S){Hn.warn({syncError:S,missionId:g},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:g,status:"planned",message:y,strategy_saved:!!b,contract_saved:!!l,from_template:c??void 0,commit:u},null,2)}]}}catch(m){throw Hn.error({error:m,repoPath:e},"Failed to plan mission"),new Error(`Failed to plan mission: ${m instanceof Error?m.message:String(m)}`)}}N();F();F();N();var Yc=_.child({module:"collision-service"}),Wn=class{repoPath;constructor(e){this.repoPath=e}async analyzePotentialCollisions(){let e=se(this.repoPath);if(!e)return[];let{missions:t,intentLogs:n}=k.getInstance(this.repoPath),i=t.findActive().filter(l=>l.git_branch&&l.git_branch!==e),r=[],o=new Set;for(let l of i){let c=l.git_branch;if(o.has(c))continue;o.add(c),Yc.info({branch:c,currentBranch:e},"Checking predictive collisions"),qs(this.repoPath,e,c)&&r.push({branch:c,type:"file",description:`Background merge-tree detected a file-level conflict between '${e}' and '${c}'.`});let p=t.findActive(e),d=new Set;for(let h of p)t.getWorkingSet(h.id).forEach(b=>d.add(b.file_path));let m=t.getWorkingSet(l.id).filter(h=>d.has(h.file_path));m.length>0&&r.push({branch:c,type:"intent",description:`Logical conflict: Mission '${l.name}' on '${c}' is modifying files you are currently working on.`,conflictingFiles:m.map(h=>h.file_path)})}return r}};var Wt=_.child({module:"mcp:tools:ops:briefing"});async function yo(s){let{repoPath:e,missionId:t,branch:n,scope:i="mission"}=s,{missions:r,intentLogs:o}=k.getInstance(e),l=fe(e),c=se(e);Wt.info({repoPath:e,missionId:t,branch:n,scope:i},"Generating briefing");try{if(i==="project"){let m=r.findActive(n),h=r.findParentOnlyIds(m),b=new Set(h),E=m.filter(R=>!b.has(R.id)),g={};for(let R of m)R.parent_id!=null&&(g[R.parent_id]||(g[R.parent_id]=[]),g[R.parent_id].push(R));let y={},S=new Map(m.map(R=>[R.id,R])),w=Object.keys(g).map(Number),C=w.filter(R=>!S.has(R)),T=C.length>0?r.findByIds(C):[],I=new Map(S);for(let R of T)I.set(R.id,R);for(let R of w){let v=I.get(R);v&&(y[R]={id:v.id,name:v.name??"",goal:v.goal??"",status:v.status??"unknown"})}let x={scope:"project",counts:r.getStats(),analytics:r.getAnalytics(),active_missions:m,parent_only_ids:h,missions_by_parent:g,parents_summary:Object.keys(y).length?y:void 0,close_parent_when_all_children_done:'When all children of a parent are completed, call shadow_ops_track({ missionId: <parent_id>, status: "completed" }) with no stepId.',next_work_candidates:E,recent_completed:r.findRecentCompleted(),recent_activity:o.findRecentDecisionActivity(),meta:{current_branch:c,current_commit:l}};if(s.includeGroupedByParent){let R=h.map(v=>{let P=m.find(H=>H.id===v),L=g[v]??[];return{parent:P,children:L}});x.missions_grouped_by_parent=R}let $=E.length===0?{tool:"shadow_ops_plan",reason:"No open work; create a mission"}:{tool:"shadow_ops_track",reason:"Pick one from next_work_candidates and run /continue"};return{content:[{type:"text",text:JSON.stringify(x,null,2)}],suggestedNext:$}}let a;if(t?a=r.findById(t):a=r.findActive(n||c||void 0)[0],!a)return{content:[{type:"text",text:"No active missions found. Ready for new assignment."}]};let p="No external shadow changes detected.";try{new mt(e).analyzeGhostChanges(a.commit_sha||void 0),p="Shadow Trace completed: Checked for external modifications."}catch(m){Wt.warn({error:m},"Ghost analysis failed")}let d={repaired:0,failed:0};try{d=new _e(e).detectAndRepairShifts()}catch(m){Wt.warn({error:m},"Symbol shift repair failed")}let u={mission:{id:a.id,name:a.name,goal:a.goal,status:a.status,last_updated:new Date(a.updated_at*1e3).toISOString(),git_branch:a.git_branch,commit_sha:a.commit_sha,outcome_contract:a.outcome_contract},artifacts:r.getArtifacts(a.id),shadow_trace:{ghost_analysis:p,symbols_repaired:d.repaired,symbols_missing:d.failed},context:{current_commit:l,working_set:r.getWorkingSet(a.id).map(m=>m.file_path)},strategy_snapshot:a.strategy_graph?JSON.parse(a.strategy_graph):null,recent_activity:o.findByMission(a.id,15),ancestor_activity:[],predictive_collisions:[]};try{let m=new Wn(e);u.predictive_collisions=await m.analyzePotentialCollisions()}catch(m){Wt.warn({error:m},"Predictive collision analysis failed")}if(s.includeLineage){let b=new tt(e).getAncestorMissionIds().filter(E=>E!==a?.id);if(b.length>0)for(let E of b){let g=o.findByMission(E,5);u.ancestor_activity.push(...g)}}return{content:[{type:"text",text:JSON.stringify(u,null,2)}]}}catch(a){throw Wt.error({error:a,repoPath:e},"Failed to generate briefing"),new Error(`Failed to generate briefing: ${a instanceof Error?a.message:String(a)}`)}}N();F();F();N();N();var Vc=_.child({module:"reasoning-engine"}),Un=class{analyze(e){Vc.debug({logCount:e.length},"Performing reasoning pass over intent logs");let t={context:[],decisions:[],consequences:[],recommendations:[],unclassified:[]};for(let n of e){let i=n.content.toLowerCase(),r=this.matchesContext(i,n.type),o=this.matchesDecision(i,n.type),l=this.matchesConsequence(i,n.type),c=this.matchesRecommendation(i,n.type);r?t.context.push(n.content):o?t.decisions.push(n.content):c?t.recommendations.push(n.content):l?t.consequences.push(n.content):n.type==="decision"?t.decisions.push(n.content):n.type==="discovery"||n.type==="fix"?t.consequences.push(n.content):t.unclassified.push(n.content)}return t}matchesContext(e,t){return["because","since","given","due to","context: ","problem: ","situation:"].some(i=>e.includes(i))||t==="blocker"}matchesDecision(e,t){return["decided","chose","implemented","integrated","using","selected","strategy:"].some(i=>e.includes(i))||t==="decision"}matchesConsequence(e,t){return["results in","enables","allows","impact: ","consequence: ","next steps: ","meaning"].some(i=>e.includes(i))||t==="fix"}matchesRecommendation(e,t){return["should","recommend","suggest","next work","future","consider","strategy advice"].some(i=>e.includes(i))}};var jn=_.child({module:"briefing-engine"}),ze=class{intentLogs;missions;reasoningEngine;persistencePivot;constructor(e){let{intentLogs:t,missions:n}=k.getInstance(e);this.intentLogs=t,this.missions=n,this.reasoningEngine=new Un,this.persistencePivot=new Re(e)}async distillMission(e,t=!0){jn.info({missionId:e},"Synthesizing mission intelligence into Tactical Briefing...");let n=this.gatherConsolidatedLogs(e);if(n.length===0)return{missionId:e,adr:"No intent logs found for this mission.",metrics:{totalLogs:0,symbolCount:0}};let i=this.reasoningEngine.analyze(n),r=new Set(n.map(l=>l.symbol_name).filter(Boolean)),o=`# Architectural Decision Record: Mission #${e}
|
|
746
|
+
|
|
747
|
+
`;if(o+=`## Summary of Intent
|
|
748
|
+
`,o+=`Collected ${n.length} intent events across ${r.size} symbols.
|
|
749
|
+
|
|
750
|
+
`,i.context.length>0&&(o+=`### Context
|
|
751
|
+
`,i.context.forEach(l=>{o+=`- ${l}
|
|
752
|
+
`}),o+=`
|
|
753
|
+
`),i.decisions.length>0&&(o+=`### Key Decisions
|
|
754
|
+
`,i.decisions.forEach(l=>{o+=`- ${l}
|
|
755
|
+
`}),o+=`
|
|
756
|
+
`),i.consequences.length>0&&(o+=`### Consequences & Evolutions
|
|
757
|
+
`,i.consequences.forEach(l=>{o+=`- ${l}
|
|
758
|
+
`}),o+=`
|
|
759
|
+
`),i.recommendations.length>0&&(o+=`### Strategic Recommendations
|
|
760
|
+
`,i.recommendations.forEach(l=>{o+=`- ${l}
|
|
761
|
+
`}),o+=`
|
|
762
|
+
`),i.unclassified.length>0&&(o+=`### Additional Notes
|
|
763
|
+
`,i.unclassified.forEach(l=>{o+=`- ${l}
|
|
764
|
+
`}),o+=`
|
|
765
|
+
`),o+=`
|
|
766
|
+
---
|
|
767
|
+
*Generated by Liquid Shadow Reasoning Engine v1*`,t){this.intentLogs.create({mission_id:e,type:"adr",content:o,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:null});try{await this.persistencePivot.syncMissionToGitNotes(e),jn.info({missionId:e},"Tactical Briefing synthesized, archived, and synced to Git Notes.")}catch(l){jn.error({missionId:e,error:l},"Failed to sync ADR to Git Notes")}}else jn.info({missionId:e},"Tactical Briefing synthesized (dry-run).");return{missionId:e,adr:o,metrics:{totalLogs:n.length,symbolCount:r.size}}}gatherConsolidatedLogs(e,t=0){let n=this.intentLogs.findByMission(e,500);if(t>2)return n;let i=this.missions.findByParentId(e);for(let r of i)n.push(...this.gatherConsolidatedLogs(r.id,t+1));return n.filter(r=>r.type!=="adr"&&r.type!=="system")}};N();import{Visitor as Qc}from"@swc/core/Visitor.js";import*as bo from"@swc/core";var Kc=_.child({module:"verification-engine"}),Li=class extends Qc{foundUsage=!1;foundImport=!1;rule;currentFunctionName=null;constructor(e){super(),this.rule=e}visitImportDeclaration(e){return this.rule.type==="import"&&e.source.value===this.rule.target&&(this.foundImport=!0),super.visitImportDeclaration(e)}visitFunctionDeclaration(e){let t=this.currentFunctionName;this.currentFunctionName=e.identifier.value;let n=super.visitFunctionDeclaration(e);return this.currentFunctionName=t,n}visitCallExpression(e){return this.rule.type==="usage"&&e.callee.type==="Identifier"&&e.callee.value===this.rule.target&&(!this.rule.context||this.currentFunctionName===this.rule.context)&&(this.foundUsage=!0),super.visitCallExpression(e)}},Bn=class{async verify(e,t){try{let n=await bo.parse(e,{syntax:"typescript",tsx:!0,comments:!1}),i=new Li(t);i.visitProgram(n);let r=!1,o=[];if(t.type==="import")r=i.foundImport,r||o.push(`Required import "${t.target}" not found.`);else if(t.type==="usage"){if(r=i.foundUsage,!r){let l=t.context?` in function "${t.context}"`:"";o.push(`Required usage of "${t.target}"${l} not found.`)}}else t.type==="pattern"&&(r=new RegExp(t.target).test(e),r||o.push(`Required pattern "${t.target}" not found.`));return{passed:r,errors:o}}catch(n){return Kc.error({error:n},"Verification failed due to parse error"),{passed:!1,errors:[`Parse error: ${n.message}`]}}}};import Eo from"path";import zn from"fs";var bt=_.child({module:"mcp:tools:ops:track"});async function So(s){let{repoPath:e,missionId:t,stepId:n,status:i,contextPivot:r,updates:o,artifacts:l}=s,{missions:c,intentLogs:a}=k.getInstance(e),p=fe(e);bt.info({repoPath:e,missionId:t,singleStep:n,batchCount:o?.length,artifactCount:l?.length},"Updating mission status");try{if(l&&Array.isArray(l))for(let m of l)c.addArtifact(t,m.type,m.identifier,m.metadata);let d=[];if(o&&Array.isArray(o)&&d.push(...o),n&&i&&d.push({stepId:n,status:i,contextPivot:r}),i&&!n){if(c.updateStatus(t,i,p||void 0),a.create({mission_id:t,type:"system",content:`Mission status changed to "${i}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),i==="completed")try{await new ze(e).distillMission(t),bt.info({missionId:t},"Auto-Synthesis completed successfully")}catch(m){bt.warn({synthesisError:m,missionId:t},"Auto-Synthesis deferred or failed")}if(!d.length)return{content:[{type:"text",text:JSON.stringify({missionId:t,status:i,message:"Mission status updated successfully.",artifacts_added:l?.length||0,commit:p},null,2)}]}}if(d.length===0&&(!l||l.length===0))throw new Error("No updates provided. Must specify either 'updates', 'stepId'/'status', 'status' (top-level), or 'artifacts'.");let u=[];for(let m of d){let{stepId:h,status:b,contextPivot:E}=m,g=c.findById(t);if(!g)throw new Error(`Mission ID ${t} not found`);let y=JSON.parse(g.strategy_graph||"{}"),S=null;if(Array.isArray(y)?S=y.find(w=>w.id===h):y.nodes&&Array.isArray(y.nodes)?S=y.nodes.find(w=>w.id===h):y.steps?Array.isArray(y.steps)?S=y.steps.find(w=>w.id===h):S=y.steps[h]:y[h]&&(S=y[h]),!S)throw new Error(`Step ID "${h}" not found`);if(b==="completed"&&S.verification){let w=new Bn,C=Array.isArray(S.verification)?S.verification:[S.verification];for(let T of C){let I=T.filePath;if(I&&!Eo.isAbsolute(I)&&(I=Eo.join(e,I)),I){if(!zn.existsSync(I))throw new Error(`Verification failed: File not found at ${I}`);let x=await w.verify(zn.readFileSync(I,"utf8"),T);if(!x.passed)throw new Error(`Verification failed: ${x.errors.join("")}`)}else{let x=c.getWorkingSet(t),$=!1;for(let R of x){if(!zn.existsSync(R.file_path))continue;if((await w.verify(zn.readFileSync(R.file_path,"utf8"),T)).passed){$=!0;break}}if(!$)throw new Error(`Verification failed for rule "${T.target}" in working set.`)}}}if(S.status=b,c.update(t,{strategy_graph:JSON.stringify(y),commit_sha:p}),a.create({mission_id:t,type:"system",content:`Step "${h}" updated to "${b}"`,confidence:1,symbol_id:null,file_path:null,symbol_name:null,signature:null,commit_sha:p}),E)try{let w=JSON.parse(E);if(c.clearWorkingSet(t),w.files&&Array.isArray(w.files))for(let C of w.files)c.addToWorkingSet(t,C)}catch(w){bt.warn({error:w},"Failed to apply context pivot")}u.push({stepId:h,status:b})}try{await new Re(e).syncMissionToGitNotes(t)}catch(m){bt.warn({syncError:m,missionId:t},"Git Notes sync deferred")}return{content:[{type:"text",text:JSON.stringify({missionId:t,updates:u,artifacts_added:l?.length||0,message:"Status updated",commit:p},null,2)}]}}catch(d){throw bt.error({error:d,repoPath:e},"Failed to update status"),new Error(`Failed to update status: ${d instanceof Error?d.message:String(d)}`)}}N();var To=_.child({module:"mcp:tools:ops:graph"});async function vo(s){let{repoPath:e,missionId:t,depth:n,limit:i,format:r="mermaid"}=s;To.info({repoPath:e,missionId:t,format:r},"Generating mission graph");try{let{GraphExporterService:o}=await Promise.resolve().then(()=>(Ro(),xo));return{content:[{type:"text",text:await new o(e).generateGraph({includeCompleted:!0,format:r,focusMissionId:t,depth:n,limit:i})}]}}catch(o){throw To.error({error:o,repoPath:e},"Failed to generate mission graph"),new Error(`Failed to generate mission graph: ${o.message}`)}}F();N();var Ut=_.child({module:"mcp:tools:ops:log"});async function wo(s){let{repoPath:e,missionId:t,type:n,content:i,filePath:r,symbolName:o}=s;Ut.info({repoPath:e,type:n,symbolName:o},"Logging intent");let{missions:l,exports:c,intentLogs:a}=k.getInstance(e);try{let p=t??null;if(p){if(!l.findById(p))throw new Error(`Mission ${p} not found. Use shadow_ops_briefing to see available missions.`)}else{let b=l.findActive();b.length>0?(p=b[0].id,Ut.debug({missionId:p},"Auto-resolved to active mission")):(p=null,Ut.debug("No active mission found, logging as system/unlinked intent"))}let d=null,u=null,m=o||null;if(o){let E=(r?c.findByNameAndFile(o,r):c.findByName(o))[0];E?(d=E.id,u=E.signature,m=E.name):Ut.warn({symbolName:o,filePath:r},"Symbol not found for intent linking")}let h=a.create({mission_id:p,symbol_id:d,file_path:r||null,type:n,content:i,confidence:1,symbol_name:m,signature:u,commit_sha:null});return{content:[{type:"text",text:JSON.stringify({logId:h,missionId:p,symbolId:d,status:"logged",message:d?`Intent linked to symbol "${o}"`:"Intent logged (unlinked)"},null,2)}]}}catch(p){throw Ut.error({error:p,repoPath:e},"Failed to log intent"),new Error(`Failed to log intent: ${p instanceof Error?p.message:String(p)}`)}}F();N();var Io=_.child({module:"mcp:tools:ops:synthesize"});async function ko(s){let{repoPath:e,missionId:t}=s;Io.info({repoPath:e,missionId:t},"Synthesizing mission");let{missions:n}=k.getInstance(e);try{if(!n.findById(t))throw new Error(`Mission ${t} not found`);let o=await new ze(e).distillMission(t);return{content:[{type:"text",text:JSON.stringify({missionId:t,adr:o.adr,metrics:o.metrics},null,2)}]}}catch(i){throw Io.error({error:i,repoPath:e},"Failed to synthesize ADR"),new Error(`Failed to synthesize ADR: ${i instanceof Error?i.message:String(i)}`)}}import Xc from"path";var q={...f,box:te,table:rn,list:rs};async function Co(s){let[e,...t]=s;if(!e||!["plan","briefing","update","log","synthesize","graph"].includes(e)){console.log(""),console.log(` ${q.bold("Usage: ")} liquid-shadow mission <action> [options]`),console.log(""),console.log(` ${q.bold("Actions: ")}`),console.log(` ${q.cyan("plan")} <repo> <name> <goal> Plan a new mission`),console.log(` ${q.cyan("update")} <repo> <id> <status> Update mission status`),console.log(` ${q.cyan("log")} <repo> <id> <type> <msg> Log a mission discovery/intent`),console.log(` ${q.cyan("briefing")} <repo> [--branch] Get mission briefing`),console.log(` ${q.cyan("synthesize")} <repo> <id> Distill mission into ADR`),console.log(` ${q.cyan("graph")} <repo> [id] Generate mission lineage graph`),console.log("");return}await U(async()=>{let n=t[0]?Xc.resolve(t[0]):process.cwd();switch(e){case"plan":{let[i,r,o]=t;if(!r||!o){console.error(` ${q.red("\u2716")} Usage: mission plan <repo> <name> <goal>`);return}let l=await go({repoPath:n,name:r,goal:o}),c=JSON.parse(l.content[0].text);console.log(` ${q.green("\u2714")} Mission planned (ID: ${c.missionId})`);break}case"update":{let[i,r,o]=t;if(!r||!o){console.error(` ${q.red("\u2716")} Usage: mission update <repo> <id> <status>`);return}await So({repoPath:n,missionId:parseInt(r),status:o}),console.log(` ${q.green("\u2714")} Status updated to ${o}`);break}case"log":{let[i,r,o,...l]=t;if(!r||!o||l.length===0){console.error(` ${q.red("\u2716")} Usage: mission log <repo> <id> <type> <message>`);return}await wo({repoPath:n,missionId:parseInt(r),type:o,content:l.join(" ")}),console.log(` ${q.green("\u2714")} Intent logged`);break}case"synthesize":{let[i,r]=t;if(!r){console.error(` ${q.red("\u2716")} Usage: mission synthesize <repo> <id>`);return}let o=await ko({repoPath:n,missionId:parseInt(r)});console.log(""),q.box("Mission Synthesis (ADR)",o.content[0].text,"magenta");break}case"graph":{let[i,r]=t,o=await vo({repoPath:n,missionId:r?parseInt(r):void 0,format:"mermaid"});console.log(""),console.log(o.content[0].text);break}case"briefing":{let i,r=t.indexOf("--branch");r!==-1&&t[r+1]&&(i=t[r+1]);let o=await yo({repoPath:n,branch:i});if(o.content&&o.content[0]){let l=o.content[0].text;try{let c=JSON.parse(l);if(c.mission){console.log(""),console.log(q.bold(q.cyan(` Mission Dashboard: ${c.mission.name} `))),q.box("Tactical Goal",c.mission.goal,"cyan");let a=c.mission.status==="completed"?"green":c.mission.status==="failed"?"red":"yellow",p=[["Status",q.bold(q[a](c.mission.status.toUpperCase()))],["ID",`#${c.mission.id}`],["Branch",c.mission.git_branch||"main"]];q.table(["Field","Value"],p),c.recent_activity&&c.recent_activity.length>0&&(console.log(` ${q.bold("Recent Activity:")}`),q.list(c.recent_activity.slice(0,5).map(d=>`${q.dim(`[${d.type.toUpperCase()}]`)} ${d.content}`)))}else console.log(l)}catch{console.log(l)}}break}}})}import Ni from"path";async function Lo(s){let[e,...t]=s;if(!e||!["symbol","file"].includes(e)){console.log(""),console.log(` ${f.bold("Usage: ")} liquid-shadow inspect <symbol|file> [options]`),console.log(""),console.log(` ${f.bold("Actions: ")}`),console.log(` ${f.cyan("symbol")} <repo> <name> Read source code for a symbol`),console.log(` ${f.cyan("file")} <repo> <path> Get a token-efficient file summary`),console.log("");return}await U(async()=>{let n=t[0]?Ni.resolve(t[0]):process.cwd();if(e==="symbol"){let i=t[1];if(!i){console.error(` ${f.red("\u2716")} Please provide a symbol name`);return}let r=await gt({repoPath:n,symbolName:i});console.log(""),r.content&&r.content[0]&&console.log(r.content[0].text)}else{let i=t[1];if(!i){console.error(` ${f.red("\u2716")} Please provide a file path`);return}let r=Ni.isAbsolute(i)?i:Ni.join(n,i),o=await An({repoPath:n,filePath:r});console.log(""),o.content&&o.content[0]&&console.log(o.content[0].text)}})}var $o=["index","status","metrics","benchmark","tree","trace","watch","search-config","search-concept","search-symbol","search-fuzzy","hooks","workspace","mission","inspect","completion"],Zc=["--help","-h","--version","-v","--dir","-d"],el={index:["--output","-o","--level","-l","--subPath","--force","--deep"],tree:["--subPath","--depth","-d"],trace:["--dir","-d"],"search-config":["--dir","-d","--kind"],"search-concept":["--dir","-d","--interactive","-i"],"search-symbol":["--dir","-d","--interactive","-i"],"search-fuzzy":["--dir","-d","--interactive","-i"]};function tl(){let s=Object.entries(el).map(([n,i])=>` ${n}) opts="${i.join(" ")}" ;;`).join(`
|
|
768
|
+
`),e=$o.join(" ");return`# Bash completion for liquid-shadow. Usage: source <(liquid-shadow completion bash)
|
|
769
|
+
_liquid_shadow() {
|
|
770
|
+
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
771
|
+
local words=("\${COMP_WORDS[@]}")
|
|
772
|
+
local cmd=""
|
|
773
|
+
local i=1
|
|
774
|
+
while [ $i -lt $COMP_CWORD ]; do
|
|
775
|
+
if [[ "\${words[$i]}" != -* ]]; then cmd="\${words[$i]}"; break; fi
|
|
776
|
+
((i++))
|
|
777
|
+
done
|
|
778
|
+
local opts="${Zc.join(" ")}"
|
|
779
|
+
if [ -n "$cmd" ]; then
|
|
780
|
+
case "$cmd" in
|
|
781
|
+
${s}
|
|
782
|
+
esac
|
|
783
|
+
else
|
|
784
|
+
COMPREPLY=($(compgen -W "${e}" -- "$cur"))
|
|
785
|
+
return
|
|
786
|
+
fi
|
|
787
|
+
COMPREPLY=($(compgen -W "$opts" -- "$cur"))
|
|
788
|
+
}
|
|
789
|
+
complete -F _liquid_shadow liquid-shadow
|
|
790
|
+
`}function nl(){return`# Zsh completion for liquid-shadow. Usage: source <(liquid-shadow completion zsh)
|
|
791
|
+
# Run after compinit (e.g. in .zshrc after compinit)
|
|
792
|
+
|
|
793
|
+
_liquid_shadow() {
|
|
794
|
+
local -a cmds; cmds=(${$o.map(e=>`'${e}'`).join(" ")})
|
|
795
|
+
if [ $CURRENT -eq 2 ]; then
|
|
796
|
+
_describe 'command' cmds
|
|
797
|
+
return
|
|
798
|
+
fi
|
|
799
|
+
local cmd="\${words[2]}"
|
|
800
|
+
local -a fl
|
|
801
|
+
case "$cmd" in
|
|
802
|
+
index) fl=(-o --output -l --level --subPath --force --deep) ;;
|
|
803
|
+
tree) fl=(--subPath -d --depth) ;;
|
|
804
|
+
trace) fl=(-d --dir) ;;
|
|
805
|
+
search-concept|search-symbol|search-fuzzy) fl=(-d --dir -i --interactive) ;;
|
|
806
|
+
*) fl=(-d --dir -h --help) ;;
|
|
807
|
+
esac
|
|
808
|
+
_describe 'flag' fl
|
|
809
|
+
}
|
|
810
|
+
compdef _liquid_shadow liquid-shadow
|
|
811
|
+
`}async function No(s){s==="bash"?console.log(tl()):s==="zsh"?console.log(nl()):(console.error("Usage: liquid-shadow completion <bash|zsh>"),console.error("Then: source <(liquid-shadow completion bash) # or zsh"),process.exit(1))}import il from"fs";import sl from"path";var rl=2e3;async function Ao(s){let e=sl.resolve(s);await U(async()=>{le("Watch mode");let t=we(e),n=null,i=()=>{n&&clearTimeout(n),n=setTimeout(async()=>{n=null;try{console.log(""),console.log(f.dim(" Changes detected, reindexing...")),await j(e,5,!1,!0),console.log(f.green(" Reindex complete."))}catch(r){console.error(f.red(" Reindex failed:"),r instanceof Error?r.message:r)}},rl)};try{il.watch(e,{recursive:!0},(r,o)=>{o&&!o.includes("node_modules")&&i()}),console.log(f.cyan(` Watching ${e}`)),console.log(f.dim(" Ignore: "+(t.ignore?.length?t.ignore.join(", "):"default"))),Rt("Ctrl+C to stop"),await new Promise((r,o)=>{process.on("SIGINT",()=>o(new Error("SIGINT"))),process.on("SIGTERM",()=>o(new Error("SIGTERM")))}).catch(()=>{})}finally{n&&clearTimeout(n),await G(e)}})}F();N();var ol=_.child({module:"narrative-service"}),Gn=class{missions;briefingEngine;repoPath;constructor(e){this.repoPath=e;let{missions:t}=k.getInstance(e);this.missions=t,this.briefingEngine=new ze(e)}async generateChronicle(e={}){ol.info(e,"Generating Repo Chronicle...");let n=this.missions.findAll().filter(a=>a.parent_id===null&&a.status!=="planned");e.since&&(n=n.filter(a=>a.updated_at>=e.since)),e.until&&(n=n.filter(a=>a.updated_at<=e.until)),n.sort((a,p)=>p.updated_at-a.updated_at);let i=e.offset||0,r=e.limit||10;n=n.slice(i,i+r);let o=[],l=[],c=[];for(let a of n){let p=this.missions.findByParentId(a.id),d=p.length>0,u=await this.briefingEngine.distillMission(a.id,!1);if(d){let m=[];for(let b of p)m.push(await this.mapMissionToEpisode(b));m.unshift(await this.mapMissionToEpisode(a));let h={kind:"initiative",root_mission_id:a.id,title:a.name,strategy_graph:a.strategy_graph?JSON.parse(a.strategy_graph):{},episodes:m,synthesized_narrative:u.adr};o.push(h),c.push(h)}else{let m=await this.mapMissionToEpisode(a,u.adr);l.push(m),c.push(m)}}return{repo_path:this.repoPath,generated_at:Date.now(),initiatives:o,unattached_episodes:l,timeline:c}}async mapMissionToEpisode(e,t){let n=t;return n||(n=(await this.briefingEngine.distillMission(e.id,!1)).adr),{kind:"episode",mission_id:e.id,title:e.name,goal:e.goal,outcome:e.outcome_contract,intents:[],adr_summary:n}}renderChronicleMarkdown(e){let t=`# Repository Chronicle
|
|
812
|
+
|
|
813
|
+
`;if(t+=`*Generated at ${new Date(e.generated_at).toISOString()}*
|
|
814
|
+
|
|
815
|
+
`,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})
|
|
816
|
+
`,t+=`${n.synthesized_narrative}
|
|
817
|
+
|
|
818
|
+
`):(t+=`### \u269B\uFE0F ${n.title} (Mission #${n.mission_id})
|
|
819
|
+
`,t+=`${n.adr_summary}
|
|
820
|
+
|
|
821
|
+
`),t+=`---
|
|
822
|
+
`;return t}};N();import al from"path";async function Mo(s,e){let t=al.resolve(s||process.cwd()),n=e.format==="json"?"json":"markdown",i=_.child({module:"cli:chronicle",repoPath:t});i.info("Generating repository chronicle...");try{let r=new Gn(t),o=await r.generateChronicle({limit:e.limit,offset:e.offset,since:e.since,until:e.until});console.log(n==="json"?JSON.stringify(o,null,2):r.renderChronicleMarkdown(o))}catch(r){i.error({error:r},"Failed to generate chronicle"),console.error(`Error: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}}function ae(s){let e=process.cwd();return Oi(e,s.flags)}process.on("unhandledRejection",s=>{console.error("\x1B[31mUnhandled Rejection:\x1B[0m",s),G().then(()=>process.exit(1))});process.on("uncaughtException",s=>{console.error("\x1B[31mUncaught Exception:\x1B[0m",s),G().then(()=>process.exit(1))});var Z=cl().name("liquid-shadow").version("1.0.2").description("Tactical Repository Intelligence Operative - Liquid Shadow Ecosystem").scriptName("liquid-shadow");Z.command("index","Index the repository for AI analysis",{parameters:["[dir]"],flags:{output:{type:String,alias:"o",description:"Export to JSON file instead of indexing"},level:{type:String,alias:"l",description:"Detail level",default:"detailed"},subPath:{type:String,description:"Only process files within this subpath"},force:{type:Boolean,description:"Force re-indexing of all files",default:!1},deep:{type:Boolean,description:"Perform deep semantic indexing (headings + symbol embeddings)",default:!0}}}).on("index",async s=>{let e=ae(s),t={...s.flags,dir:s.flags.dir??e.dir,level:s.flags.level??e.level,deep:s.flags.deep??e.deep};t.deep==="false"||t.deep===!1?t.deep=!1:t.deep=!0,await nr(s.parameters.dir||e.dir,t)});Z.command("status","Show current repository intelligence status",{parameters:["[dir]"]}).on("status",async s=>{let e=ae(s);await fs(s.parameters.dir||e.dir)});Z.command("metrics","Show performance metrics and observability data",{parameters:["[dir]"]}).on("metrics",async s=>{let e=ae(s);await xs(s.parameters.dir||e.dir)});Z.command("benchmark","Run performance benchmark on repository indexing",{parameters:["[dir]"]}).on("benchmark",async s=>{let e=ae(s);await sr(s.parameters.dir||e.dir)});Z.command("tree","Visualize repository structure as a tree",{parameters:["[dir]"],flags:{subPath:{type:String,description:"Subpath to visualize"},depth:{type:String,alias:"d",description:"Max depth",default:"3"}}}).on("tree",async s=>{let e=ae(s);await Zs(s.parameters.dir||e.dir,{...s.flags,dir:s.flags.dir??e.dir})});Z.command("recon","Repository reconnaissance and architecture analysis",{parameters:["<mode>","[dir]"],flags:{subPath:{type:String,description:"Subpath to focus on"}}}).on("recon",async s=>{let e=ae(s);await zr(s.parameters.mode,s.parameters.dir||e.dir,{...s.flags})});Z.command("trace","Trace execution flow for a given file/symbol",{parameters:["<file>","[symbolName]"],flags:{dir:{type:String,alias:"d",default:"."}}}).on("trace",async s=>{let e=ae(s);await cr(s.parameters.file,{...s.flags,dir:s.flags.dir??e.dir,symbolName:s.parameters.symbolName})});Z.command("sync","Deep synchronize intelligence lifecycle (Trace + Repair + Re-hydrate)",{parameters:["[dir]"],flags:{since:{type:String,description:"Analyze since specific commit hash"}}}).on("sync",async s=>{let e=ae(s);await Ur(s.parameters.dir||e.dir,{sinceCommit:s.flags.since||void 0})});Z.command("search-config","Search for configuration values",{parameters:["[key]"],flags:{dir:{type:String,alias:"d",default:"."},kind:{type:String,description:"Filter by config kind"}}}).on("search-config",async s=>{let e=ae(s);await to(s.parameters.key,{...s.flags,dir:s.flags.dir??e.dir})});Z.command("search-concept","Search for files by concept/intent (Semantic)",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-concept",async s=>{let e=ae(s);await Xr(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});Z.command("search-symbol","Search for specific code symbols",{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-symbol",async s=>{let e=ae(s);await Zr(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});Z.command("search-fuzzy",'Fuzzy search for symbols (e.g., "usc" finds "UserServiceClient")',{parameters:["<query>"],flags:{dir:{type:String,alias:"d",default:"."},interactive:{type:Boolean,alias:"i",description:"Interactive TUI: pick a result to inspect",default:!1}}}).on("search-fuzzy",async s=>{let e=ae(s);await eo(s.parameters.query,{...s.flags,dir:s.flags.dir??e.dir})});Z.command("hooks","Manage git hooks for automatic intelligence updates",{parameters:["<action>","[path]"]}).on("hooks",async s=>{await no([s.parameters.action,s.parameters.path])});Z.command("workspace","Workspace-level mission orchestration",{parameters:["<action>","[args...]"]}).on("workspace",async s=>{await mo([s.parameters.action,...s.parameters.args])});Z.command("mission","Mission management (start, plan, briefing, distill)",{parameters:["<action>","[args...]"]}).on("mission",async s=>{await Co([s.parameters.action,...s.parameters.args])});Z.command("inspect","Deep inspection of specific files or symbols",{parameters:["<mode>","[args...]"]}).on("inspect",async s=>{await Lo([s.parameters.mode,...s.parameters.args])});Z.command("watch","Watch repo and reindex on file changes",{parameters:["[dir]"]}).on("watch",async s=>{let e=ae(s);await Ao(s.parameters.dir||e.dir)});Z.command("chronicle","Generate a repository-wide narrative feed (ADRs/Epics)",{parameters:["[dir]"],flags:{format:{type:String,alias:"f",description:"Output format (markdown|json)",default:"markdown"},limit:{type:Number,alias:"l",description:"Limit number of entries",default:10},offset:{type:Number,description:"Pagination offset",default:0},since:{type:String,description:"Show entries since date (YYYY-MM-DD)"},until:{type:String,description:"Show entries until date (YYYY-MM-DD)"}}}).on("chronicle",async s=>{let e=ae(s);await Mo(s.parameters.dir||e.dir,{...s.flags,format:s.flags.format,limit:s.flags.limit?parseInt(String(s.flags.limit),10):void 0,offset:s.flags.offset?parseInt(String(s.flags.offset),10):void 0,since:s.flags.since?Math.floor(new Date(String(s.flags.since)).getTime()/1e3):void 0,until:s.flags.until?Math.floor(new Date(String(s.flags.until)).getTime()/1e3):void 0})});Z.command("completion","Generate shell completion script (bash or zsh)",{parameters:["<shell>"]}).on("completion",async s=>{await No(s.parameters.shell||"")});Z.parse();
|