@precisionutilityguild/liquid-shadow 1.0.4 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/data/migrations/000_baseline.sql +315 -0
- package/dist/data/migrations/010_type_graph_edges.sql +27 -0
- package/dist/data/migrations/011_handoff_embeddings.sql +2 -0
- package/dist/data/migrations/012_ember_state.sql +18 -0
- package/dist/entry/cli/index.js +640 -616
- package/dist/entry/ember/index.js +545 -0
- package/dist/entry/mcp/server.js +497 -324
- package/dist/index.js +493 -322
- package/dist/logic/domain/embeddings/worker.js +1 -1
- package/dist/logic/parser/index.js +14 -13
- package/dist/skills/shadow_audit/SKILL.md +43 -0
- package/dist/skills/shadow_chronicle/SKILL.md +40 -0
- package/dist/skills/shadow_continue/SKILL.md +63 -0
- package/dist/skills/shadow_crystallize/SKILL.md +41 -0
- package/dist/skills/shadow_mission/SKILL.md +53 -0
- package/dist/skills/shadow_onboard/SKILL.md +39 -0
- package/dist/skills/shadow_research/SKILL.md +34 -0
- package/dist/skills/shadow_sync/SKILL.md +18 -0
- package/dist/skills/shadow_synthesize/SKILL.md +48 -0
- package/dist/skills/shadow_trace_impact/SKILL.md +55 -0
- package/dist/skills/shadow_understand/SKILL.md +57 -0
- package/dist/skills/shadow_workspace/SKILL.md +30 -0
- package/dist/web-manifest.json +11 -4
- package/package.json +4 -3
- package/skills/shadow_audit/SKILL.md +43 -0
- package/skills/shadow_chronicle/SKILL.md +40 -0
- package/skills/shadow_continue/SKILL.md +63 -0
- package/skills/shadow_crystallize/SKILL.md +41 -0
- package/skills/shadow_mission/SKILL.md +53 -0
- package/skills/shadow_onboard/SKILL.md +39 -0
- package/skills/shadow_research/SKILL.md +34 -0
- package/skills/shadow_sync/SKILL.md +18 -0
- package/skills/shadow_synthesize/SKILL.md +48 -0
- package/skills/shadow_trace_impact/SKILL.md +55 -0
- package/skills/shadow_understand/SKILL.md +57 -0
- package/skills/shadow_workspace/SKILL.md +30 -0
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
var ot=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var at=(s,e)=>{for(var t in e)ot(s,t,{get:e[t],enumerable:!0})};import lt from"pino";var ct,ut,d,M=P(()=>{"use strict";ct={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},ut=lt({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:ct[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),d=ut});import{fileURLToPath as At}from"node:url";import{dirname as ae,join as De,resolve as xt}from"node:path";import{existsSync as wt}from"node:fs";function vt(){let s=Ie;for(;s!==ae(s);){if(wt(De(s,"package.json")))return s;s=ae(s)}return xt(Ie,"..","..")}function Me(...s){return De(vt(),...s)}var kt,Ie,Ce=P(()=>{"use strict";kt=At(import.meta.url),Ie=ae(kt)});import{Worker as Ht}from"node:worker_threads";import{cpus as Wt}from"node:os";import{fileURLToPath as Ft}from"node:url";import{dirname as Ut,join as Ae}from"node:path";import{existsSync as xe}from"node:fs";function Bt(){if(ke.endsWith(".ts")){let e=Ae(we,"worker.ts");if(xe(e))return e}let s=Ae(we,"worker.js");return xe(s)?s:Me("dist/logic/domain/embeddings/worker.js")}function x(s){return A||(A=new H(s)),A}async function ve(){A&&(await A.shutdown(),A=null)}var ke,we,H,A,He=P(()=>{"use strict";M();Ce();ke=Ft(import.meta.url),we=Ut(ke);H=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;cacheDir;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(2,Wt().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{d.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((i,n)=>{e=setTimeout(()=>n(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,d.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,d.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=Bt();d.debug({workerPath:e},"Resolved worker path");let t=[];for(let i=0;i<this.numWorkers;i++)i>0&&await new Promise(n=>setTimeout(n,25)),t.push(this.createWorker(e,i));await Promise.all(t)}async createWorker(e,t){return new Promise((i,n)=>{let r=setTimeout(()=>{n(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),c=new Ht(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),l={worker:c,busy:!1,currentTaskId:null};c.on("message",a=>{if(a.type==="ready"){if(clearTimeout(r),this.shutdownRequested){d.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),c.terminate().catch(()=>{}),i();return}this.workers.push(l),d.debug({workerIndex:t},"Worker ready"),i()}else a.type==="result"&&a.id?this.handleTaskComplete(l,a.id,a.embeddings||[]):a.type==="error"&&a.id&&this.handleTaskError(l,a.id,new Error(a.error||"Unknown error"))}),c.on("error",a=>{if(clearTimeout(r),d.error({err:a,workerIndex:t},"Worker error"),l.currentTaskId&&this.handleTaskError(l,l.currentTaskId,a),!this.initialized){n(a);return}let o=this.workers.indexOf(l);o!==-1&&this.workers.splice(o,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(u=>{d.error({err:u},"Failed to replace crashed worker")})}),c.on("exit",a=>{a!==0&&!this.shutdownRequested&&d.warn({workerIndex:t,code:a},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,i){let n=this.pendingTasks.get(t);n&&(this.pendingTasks.delete(t),n.resolve(i)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,i){let n=this.pendingTasks.get(t);n&&(this.pendingTasks.delete(t),n.reject(i)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(i=>!i.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=128,i){if(this.initialized||await this.initialize(),e.length===0)return[];let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));let r=new Array(n.length),c=0,l=n.map((o,u)=>new Promise((p,m)=>{let f={id:`task_${++this.taskIdCounter}`,texts:o,resolve:T=>{if(r[u]=T,c++,i){let N=Math.min(c*t,e.length);i(N,e.length)}p()},reject:T=>{if(r[u]=new Array(o.length).fill(null),c++,d.warn({err:T,chunkIndex:u},"Chunk embedding failed"),i){let N=Math.min(c*t,e.length);i(N,e.length)}p()}};this.taskQueue.push(f),this.processQueue()}));await Promise.all(l);let a=[];for(let o of r)a.push(...o);return d.info({total:e.length,successful:a.filter(o=>o!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),a}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}d.info({numWorkers:this.workers.length},"Shutting down embedding worker pool");let e=this.workers.map(t=>new Promise(i=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>i()),setTimeout(()=>{t.worker.terminate().then(()=>i())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,d.info("Embedding worker pool shutdown complete")}},A=null});var I={};at(I,{EmbeddingPriorityQueue:()=>ce,EmbeddingWorkerPool:()=>H,cosineSimilarity:()=>qt,generateEmbedding:()=>Yt,generateEmbeddingsBatch:()=>Kt,getDefaultPool:()=>x,setUseWorkerThreads:()=>$t,shutdownDefaultPool:()=>ve});async function Pt(){return W||(W=await import("@xenova/transformers"),W.env.cacheDir="./.cache",W.env.allowLocalModels=!0),W}function $t(s){ue=s,d.info({useWorkerThreads:s},"Worker thread mode updated")}function We(s=!1){let e=(F||"").toLowerCase(),t={};return F&&(t.dtype=F),s?(t.quantized=!1,t):(e==="fp32"||e==="fp16"||e==="float32"||e==="float16"?t.quantized=!1:e.startsWith("q")&&(t.quantized=!0),t)}async function zt(){d.info({model:G,dtype:F},"Loading embedding model...");let{pipeline:s}=await Pt(),e=We(!1);try{return await s("feature-extraction",G,e)}catch(t){let i=t?.message||"";if(!(i.includes("/onnx/model_quantized.onnx")||i.includes("model_quantized.onnx")))throw t;return d.warn({model:G,dtype:F},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",G,We(!0))}}async function Ue(){return le||(le=zt()),le}async function Yt(s){try{let t=await(await Ue())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return d.error({err:e},"Failed to generate embedding"),null}}async function Kt(s,e=Fe,t){return s.length===0?[]:ue?x().generateEmbeddings(s,e,t):Be(s,e,t)}async function Be(s,e,t){let i=new Array(s.length).fill(null),n=await Ue();for(let r=0;r<s.length;r+=e){let c=Math.min(r+e,s.length),l=s.slice(r,c);try{let a=await n(l,{pooling:"mean",normalize:!0}),[o,u]=a.dims;for(let p=0;p<o;p++){let m=p*u,y=m+u;i[r+p]=Array.from(a.data.slice(m,y))}}catch(a){d.error({err:a,batchStart:r,batchEnd:c},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let o=0;o<l.length;o++)try{let u=l[o];if(!u||u.trim().length===0)continue;let p=await n(u,{pooling:"mean",normalize:!0});i[r+o]=Array.from(p.data)}catch{i[r+o]=null}}t&&t(c,s.length)}return d.debug({total:s.length,successful:i.filter(r=>r!==null).length},"Batch embedding complete"),i}function qt(s,e){let t=0,i=0,n=0;for(let r=0;r<s.length;r++)t+=s[r]*e[r],i+=s[r]*s[r],n+=e[r]*e[r];return t/(Math.sqrt(i)*Math.sqrt(n))}var G,F,W,Fe,ue,le,ce,S=P(()=>{"use strict";M();He();G=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",F=process.env.EMBEDDING_DTYPE??"fp32",W=null;Fe=128,ue=!1;le=null;ce=class{queue=[];processing=!1;results=new Map;enqueue(e){this.queue.push(e),this.queue.sort((t,i)=>i.priority-t.priority)}enqueueMany(e){this.queue.push(...e),this.queue.sort((t,i)=>i.priority-t.priority)}get size(){return this.queue.length}get isProcessing(){return this.processing}getResult(e){return this.results.get(e)}async processQueue(e=Fe,t){if(this.processing)return d.warn("Queue processing already in progress"),this.results;this.processing=!0;let i=this.queue.length;try{ue?await this.processQueueParallel(e,i,t):await this.processQueueSequential(e,i,t)}finally{this.processing=!1}return this.results}async processQueueSequential(e,t,i){for(;this.queue.length>0;){let n=this.queue.splice(0,e),r=n.map(l=>l.text),c=await Be(r,r.length);if(n.forEach((l,a)=>{this.results.set(l.id,c[a])}),i){let l=t-this.queue.length;i(l,t)}}}async processQueueParallel(e,t,i){let n=this.queue.splice(0),r=n.map(a=>a.text),l=await x().generateEmbeddings(r,e,(a,o)=>{i&&i(a,o)});n.forEach((a,o)=>{this.results.set(a.id,l[o])})}clear(){this.queue=[],this.results.clear()}}});import de from"node:os";M();import yt from"better-sqlite3";import z from"path";import Te from"fs";import Tt from"crypto";M();import O from"fs";import $ from"path";import{fileURLToPath as dt}from"url";var R=d.child({module:"migrations"}),pt=dt(import.meta.url),mt=$.dirname(pt);function Et(){let s=mt;if(O.readdirSync(s).some(i=>i.match(/^\d{3}_.*\.sql$/)))return s;let t=$.resolve(s,"../../data/migrations");return O.existsSync(t)&&O.readdirSync(t).some(i=>i.match(/^\d{3}_.*\.sql$/))?t:s}function ht(s){s.exec(`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
3
|
+
version INTEGER PRIMARY KEY,
|
|
4
|
+
name TEXT NOT NULL,
|
|
5
|
+
applied_at REAL DEFAULT (unixepoch())
|
|
6
|
+
);
|
|
7
|
+
`)}function gt(s){ht(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function ft(s){return O.readdirSync(s).filter(t=>t.match(/^\d{3}_.*\.sql$/)&&!t.startsWith("000_")).sort().map(t=>{let i=t.match(/^(\d{3})_(.+)\.sql$/),n=parseInt(i[1],10),r=i[2],l=O.readFileSync($.join(s,t),"utf-8").split(/^-- DOWN$/m);return{version:n,name:r,up:l[0].trim(),down:l[1]?.trim()}})}function bt(s,e){R.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)})(),R.info({version:e.version},"Migration applied successfully")}function _t(s,e,t){let i=$.join(e,"000_baseline.sql");if(!O.existsSync(i)){R.warn("000_baseline.sql not found \u2014 falling back to incremental migrations");return}R.info("Fresh database detected \u2014 applying consolidated baseline schema");let n=O.readFileSync(i,"utf-8");s.transaction(()=>{s.exec(n);let r=s.prepare("INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (?, ?)");for(let c of t)r.run(c.version,c.name)})(),R.info({stamped:t.length},"Baseline applied \u2014 incremental migrations stamped")}function ye(s){let e=gt(s),t=Et(),i=ft(t);if(e.size===0){_t(s,t,i);return}let n=i.filter(r=>!e.has(r.version));if(n.length===0){R.debug("No pending migrations");return}R.info({count:n.length},"Running pending migrations");for(let r of n)bt(s,r);R.info("All migrations complete")}import Rt from"os";var C=d.child({module:"db"});function re(s){let e=Rt.homedir(),t=z.join(e,".mcp-liquid-shadow"),i=z.join(t,"dbs");Te.existsSync(i)||Te.mkdirSync(i,{recursive:!0});let n=Tt.createHash("sha256").update(s).digest("hex").substring(0,12),c=`${z.basename(s).replace(/[^a-zA-Z0-9-_]/g,"_")}_${n}.db`;return z.join(i,c)}function Lt(s,e){let t=e||re(s);C.debug({repoPath:s,dbPath:t},"Initializing database");let i=new yt(t);return i.pragma("journal_mode = WAL"),i.pragma("busy_timeout = 5000"),ye(i),Y.set(s,t),L.set(t,i),C.debug({repoPath:s,dbPath:t},"Database initialized successfully"),i}var L=new Map,Y=new Map;function v(s){let e=Y.get(s)||re(s),t=L.get(e);if(t){if(t.open)return t;L.delete(e)}let i=Lt(s);return L.set(e,i),i}function Re(s){let e=Y.get(s)||re(s),t=L.get(e);t&&(t.open&&(C.debug({repoPath:s,dbPath:e},"Closing database connection"),t.close()),L.delete(e)),Y.delete(s)}function Le(){for(let[s,e]of L.entries())try{e.open&&(C.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){C.error({dbPath:s,err:t},"Error closing database execution")}L.clear()}process.on("exit",()=>Le());var Se=s=>{C.debug({signal:s},"Received termination signal, closing databases"),Le(),process.exit(0)};process.on("SIGINT",()=>Se("SIGINT"));process.on("SIGTERM",()=>Se("SIGTERM"));import Ct from"path";var E=class{db;constructor(e){this.db=e}get database(){return this.db}all(e,...t){return this.db.prepare(e).all(...t)}get(e,...t){return this.db.prepare(e).get(...t)}run(e,...t){return this.db.prepare(e).run(...t).changes}insert(e,...t){return this.db.prepare(e).run(...t).lastInsertRowid}transaction(e){return this.db.transaction(e)()}};var St=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","symbol","object","bigint","readonly","keyof","infer","extends","implements","class","interface","type","function","new"]);function Nt(s,e){if(!s)return!1;let t=s.trim();return!t||St.has(t.toLowerCase())||e.has(t)?!1:/^[A-Za-z_$][A-Za-z0-9_$.]*$/.test(t)}function Ot(s){return s.split(/[,|&]/).map(e=>e.trim()).filter(Boolean)}function It(s){let e=s.replace(/^[({\[]+/,"").replace(/[)}\]]+$/,"").replace(/^readonly\s+/,"").trim();return e&&e.match(/^([A-Za-z_$][A-Za-z0-9_$.]*)/)?.[1]||null}function Dt(s){let e=[],t=0,i="",n=!1;for(let r of s){if(r==="<"&&(t++,t===1)){n=!0,i="";continue}if(r===">"&&(t>0&&t--,t===0&&n)){n=!1,i.trim()&&e.push(i),i="";continue}n&&(i+=r)}return e}function Mt(s){let e=new Set;for(let t of s){let i=t.split(",").map(n=>n.trim());for(let n of i){let r=n.match(/^([A-Za-z_$][A-Za-z0-9_$]*)/);r?.[1]&&e.add(r[1])}}return e}function oe(s,e){let t=[];for(let i of Ot(s)){let n=It(i);n&&Nt(n,e)&&t.push(n)}return t}function Ne(s){if(!s)return[];let e=s.replace(/\s+/g," ").trim();if(!e)return[];let t=Dt(e),i=Mt(t),n=[],r=new Set,c=(o,u,p)=>{let m=`${o}:${u}`;r.has(m)||(r.add(m),n.push({relationship:o,targetName:u,...p?{metadata:p}:{}}))},l=e.match(/\bextends\s+(.+?)(?=\bimplements\b|\{|=|$)/);if(l?.[1]){let o=oe(l[1],i);for(let u of o)c("extends",u,l[1].trim())}let a=e.match(/\bimplements\s+(.+?)(?=\{|=|$)/);if(a?.[1]){let o=oe(a[1],i);for(let u of o)c("implements",u,a[1].trim())}for(let o of t){let u=/([A-Za-z_$][A-Za-z0-9_$]*)\s+extends\s+([^,>]+)/g,p=null;for(;(p=u.exec(o))!==null;){let m=p[2]?.trim();if(!m)continue;let y=oe(m,i);for(let f of y)c("constrained_by",f,m)}}return n}var K=class extends E{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 i=Ct.resolve(e,t),n=i.endsWith("/")?i:i+"/";return this.all(`
|
|
8
|
+
SELECT * FROM files
|
|
9
|
+
WHERE (path LIKE ? OR path = ?)
|
|
10
|
+
ORDER BY path ASC
|
|
11
|
+
`,`${n}%`,i)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
|
|
12
|
+
SELECT files.*, files_fts.rank
|
|
13
|
+
FROM files_fts
|
|
14
|
+
JOIN files ON files.rowid = files_fts.rowid
|
|
15
|
+
WHERE files_fts MATCH ?
|
|
16
|
+
ORDER BY rank
|
|
17
|
+
LIMIT ?
|
|
18
|
+
`,e,t)}findByPathKeywords(e,t=10){let i=e.map(()=>"LOWER(path) LIKE ?").join(" OR ");return this.all(`
|
|
19
|
+
SELECT * FROM files
|
|
20
|
+
WHERE ${i}
|
|
21
|
+
LIMIT ?
|
|
22
|
+
`,...e.map(n=>`%${n}%`),t)}findContentFts(e,t=50){let i=this.buildContentFtsQuery(e);return i?this.all(`
|
|
23
|
+
SELECT
|
|
24
|
+
files.*,
|
|
25
|
+
bm25(content_fts, 0.2, 1.0) AS bm25_rank
|
|
26
|
+
FROM content_fts
|
|
27
|
+
JOIN files ON files.path = content_fts.file_path
|
|
28
|
+
WHERE content_fts MATCH ?
|
|
29
|
+
ORDER BY bm25_rank ASC
|
|
30
|
+
LIMIT ?
|
|
31
|
+
`,i,Math.max(1,Math.min(t,1e3))):[]}getContent(e){return this.get("SELECT content FROM file_content WHERE file_path = ?",e)?.content}findContentByToken(e,t=10){return this.all(`
|
|
32
|
+
SELECT file_path
|
|
33
|
+
FROM content_fts
|
|
34
|
+
WHERE content_fts MATCH ?
|
|
35
|
+
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')
|
|
36
|
+
AND file_path NOT LIKE '%/test/%'
|
|
37
|
+
AND file_path NOT LIKE '%.spec.%'
|
|
38
|
+
LIMIT ?
|
|
39
|
+
`,`"${e.replace(/[^a-zA-Z0-9_\/]/g," ")}"`,t).map(n=>n.file_path)}findSynapses(e){let t="SELECT * FROM event_synapses WHERE 1=1",i=[];if(e.type&&(t+=" AND type = ?",i.push(e.type)),e.name){let n=e.name;n.startsWith("/")&&(n=n.substring(1)),n.endsWith("/")&&(n=n.substring(0,n.length-1)),n.length>0&&(t+=" AND (name LIKE ? OR name LIKE ? OR name = ?)",i.push(`${n}%`),i.push(`%/${n}%`),i.push(e.name))}return e.direction&&(t+=" AND direction = ?",i.push(e.direction)),t+=` LIMIT ${e.limit||50}`,this.all(t,...i)}exists(e){return!!this.get("SELECT 1 FROM files WHERE path = ?",e)}update(e,t){let i=Object.keys(t);if(i.length===0)return;let n=i.map(c=>`${c} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE files SET ${n} WHERE path = ?`,...r)}getStats(){let e=this.get(`
|
|
40
|
+
SELECT
|
|
41
|
+
COUNT(*) as total,
|
|
42
|
+
SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
|
|
43
|
+
FROM files
|
|
44
|
+
`);return{total:e?.total||0,withSummary:e?.withSummary||0}}getGravityMap(e=[],t){let i={},n=`
|
|
45
|
+
SELECT ws.file_path, m.name as mission_name, m.status
|
|
46
|
+
FROM working_set ws
|
|
47
|
+
JOIN missions m ON ws.mission_id = m.id
|
|
48
|
+
WHERE (
|
|
49
|
+
(m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
|
|
50
|
+
OR m.id IN (${e.length>0?e.join(","):"-1"})
|
|
51
|
+
)
|
|
52
|
+
AND ws.file_path IS NOT NULL
|
|
53
|
+
`,r=[];t&&r.push(t);let c=this.all(n,...r);for(let o of c){i[o.file_path]||(i[o.file_path]={score:1,reasons:[]});let u=o.status==="in-progress"||o.status==="verifying"?1:.5;i[o.file_path].score+=u;let p=o.status==="in-progress"||o.status==="verifying"?"Working Set":"Lineage Bleed";i[o.file_path].reasons.push(`${p}: ${o.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,a=this.all(`
|
|
54
|
+
SELECT file_path, type, mission_id
|
|
55
|
+
FROM intent_logs
|
|
56
|
+
WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
|
|
57
|
+
AND file_path IS NOT NULL
|
|
58
|
+
ORDER BY created_at DESC
|
|
59
|
+
LIMIT 100
|
|
60
|
+
`,l);for(let o of a){i[o.file_path]||(i[o.file_path]={score:1,reasons:[]});let u=o.mission_id?e.includes(o.mission_id):!1,p=u?.1:.2;i[o.file_path].score<5&&(i[o.file_path].score+=p);let m=u?`Lineage Intent: ${o.type}`:`Recent Intent: ${o.type}`;!i[o.file_path].reasons.includes(m)&&i[o.file_path].reasons.length<5&&i[o.file_path].reasons.push(m)}return i}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
|
|
61
|
+
SELECT
|
|
62
|
+
SUBSTR(path, LENGTH(?) + 2,
|
|
63
|
+
INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
|
|
64
|
+
) as root,
|
|
65
|
+
COUNT(*) as total_files,
|
|
66
|
+
SUM(CASE
|
|
67
|
+
WHEN path LIKE '%.ts' OR path LIKE '%.tsx'
|
|
68
|
+
OR path LIKE '%.js' OR path LIKE '%.jsx'
|
|
69
|
+
OR path LIKE '%.mjs' OR path LIKE '%.cjs'
|
|
70
|
+
THEN 1 ELSE 0
|
|
71
|
+
END) as ts_files
|
|
72
|
+
FROM files
|
|
73
|
+
WHERE path LIKE ? || '/%/%'
|
|
74
|
+
GROUP BY root
|
|
75
|
+
ORDER BY total_files DESC
|
|
76
|
+
LIMIT ?
|
|
77
|
+
`,e,e,e,t)}hasFilesPattern(e){return!!this.get("SELECT 1 FROM files WHERE path LIKE ? LIMIT 1",e)}findPackageJsonChildren(e){return this.all(`
|
|
78
|
+
SELECT
|
|
79
|
+
path,
|
|
80
|
+
SUBSTR(path, LENGTH(?) + 2) as relPath
|
|
81
|
+
FROM files
|
|
82
|
+
WHERE path LIKE ? || '/%/package.json'
|
|
83
|
+
`,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(n=>{for(let r of n)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,i,n){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),c=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),l=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),a=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),o=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),u=this.db.prepare("DELETE FROM type_graph_edges WHERE file_path = ?"),p=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),y=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),f=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),T=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),N=this.db.prepare("INSERT INTO type_graph_edges (file_path, source_symbol_id, source_symbol_name, target_symbol_name, relationship, line_number, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)"),Ve=this.db.prepare(`
|
|
84
|
+
INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
|
|
85
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
86
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
87
|
+
mtime=excluded.mtime,
|
|
88
|
+
last_scanned_at=excluded.last_scanned_at,
|
|
89
|
+
classification=excluded.classification,
|
|
90
|
+
summary=excluded.summary,
|
|
91
|
+
embedding=excluded.embedding,
|
|
92
|
+
content_hash=excluded.content_hash
|
|
93
|
+
`),Je=this.db.transaction(D=>{for(let Qe of D){let{meta:b,exports:me,imports:Ee,configs:he,events:ge,content:U,classification:Xe,summary:Ze,embedding:fe,contentHash:et}=Qe;r.run(b.path),c.run(b.path),l.run(b.path),a.run(b.path),o.run(b.path),u.run(b.path);let tt=et??(U&&i?i(U):null);if(Ve.run(b.path,b.mtime,Date.now(),Xe||"Unknown",Ze||"",fe?JSON.stringify(fe):null,tt),me){let h=(k,it,nt)=>{for(let g of it){let st=g.embedding?JSON.stringify(g.embedding):null,be=p.run(k,g.name,g.kind,g.signature,g.doc||"",g.line,g.endLine||g.line,g.classification||"Other",g.capabilities||"[]",nt,st),_e=Number(be.lastInsertRowid);if(Number.isFinite(_e)){let rt=Ne(g.signature);for(let B of rt)B.targetName!==g.name&&N.run(k,_e,g.name,B.targetName,B.relationship,g.line,B.metadata||null)}g.members&&g.members.length>0&&h(k,g.members,be.lastInsertRowid)}};h(b.path,me,null)}if(Ee)for(let h of Ee){let k=h.resolved_path!==void 0?h.resolved_path:n?.(h.module,b.path,t)??"";m.run(b.path,h.module,h.name,k)}if(he)for(let h of he)y.run(b.path,h.key,h.value,h.kind);if(U!==void 0&&f.run(b.path,U),ge)for(let h of ge)T.run(b.path,h.type,h.name,h.direction,h.line,h.snippet)}}),pe=500;for(let D=0;D<e.length;D+=pe)Je(e.slice(D,D+pe))}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}buildContentFtsQuery(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>=2).slice(0,12);if(t.length===0)return"";if(t.length===1)return`${t[0]}*`;let i=`"${t.join(" ")}"`,n=t.map(r=>`${r}*`).join(" OR ");return`${i} OR ${n}`}};var q=class s extends E{static HTTP_METHOD_EXPORTS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]);findByNameAndFile(e,t){return this.all("SELECT * FROM exports WHERE file_path = ? AND name = ?",t,e)}findByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ?",e)}findAtLine(e,t){return this.get(`
|
|
94
|
+
SELECT * FROM exports
|
|
95
|
+
WHERE file_path = ? AND start_line <= ? AND end_line >= ?
|
|
96
|
+
ORDER BY (end_line - start_line) ASC -- Get innermost symbol
|
|
97
|
+
LIMIT 1
|
|
98
|
+
`,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 i=this.all(`
|
|
99
|
+
SELECT id, mission_id, type, content, created_at, confidence, is_crystallized, crystal_id
|
|
100
|
+
FROM intent_logs
|
|
101
|
+
WHERE symbol_id = ?
|
|
102
|
+
ORDER BY created_at DESC
|
|
103
|
+
LIMIT 10
|
|
104
|
+
`,e),r=this.get("SELECT COUNT(*) as count FROM intent_logs WHERE symbol_id = ?",e)?.count||0,c=this.all(`
|
|
105
|
+
SELECT m.id, m.name, m.status
|
|
106
|
+
FROM missions m
|
|
107
|
+
JOIN working_set ws ON ws.mission_id = m.id
|
|
108
|
+
WHERE ws.symbol_id = ?
|
|
109
|
+
AND m.status IN ('in-progress', 'planned', 'verifying')
|
|
110
|
+
GROUP BY m.id
|
|
111
|
+
`,e);return{...t,recent_intents:i,intent_log_count:r,active_missions:c}}findRoutesByCapability(e){return this.all(`
|
|
112
|
+
SELECT name, file_path, signature
|
|
113
|
+
FROM exports
|
|
114
|
+
WHERE kind = 'HTTP Route'
|
|
115
|
+
AND capabilities LIKE ?
|
|
116
|
+
`,`%${e}%`)}findRoutesByToken(e,t=5){return this.all(`
|
|
117
|
+
SELECT *
|
|
118
|
+
FROM exports
|
|
119
|
+
WHERE (kind = 'HTTP Route' OR classification = 'Service Boundary')
|
|
120
|
+
AND (name LIKE ? OR signature LIKE ?)
|
|
121
|
+
LIMIT ?
|
|
122
|
+
`,`%${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)}findWithEmbeddings(e=5e3){return this.all(`
|
|
123
|
+
SELECT *
|
|
124
|
+
FROM exports
|
|
125
|
+
WHERE embedding IS NOT NULL
|
|
126
|
+
ORDER BY file_path, start_line
|
|
127
|
+
LIMIT ?
|
|
128
|
+
`,e)}findSiblings(e){return this.all(`
|
|
129
|
+
SELECT name, kind, signature, start_line, end_line,
|
|
130
|
+
parent_id, id,
|
|
131
|
+
(SELECT name FROM exports WHERE id = e.parent_id) as parent_name
|
|
132
|
+
FROM exports e
|
|
133
|
+
WHERE file_path = ?
|
|
134
|
+
AND parent_id IS NULL
|
|
135
|
+
ORDER BY start_line ASC
|
|
136
|
+
`,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 i=[e],n=`
|
|
137
|
+
SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
|
|
138
|
+
f.path as file_path, e.classification, e.capabilities,
|
|
139
|
+
p.name as parent_name, p.kind as parent_kind
|
|
140
|
+
FROM exports e
|
|
141
|
+
JOIN files f ON e.file_path = f.path
|
|
142
|
+
LEFT JOIN exports p ON e.parent_id = p.id
|
|
143
|
+
WHERE e.name = ?
|
|
144
|
+
`;return t&&(n+=" AND f.path = ?",i.push(t)),n+=`
|
|
145
|
+
ORDER BY
|
|
146
|
+
CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
|
|
147
|
+
CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
|
|
148
|
+
LIMIT 10
|
|
149
|
+
`,this.all(n,...i)}findMemberCandidates(e,t,i){let n=[e,t],r=`
|
|
150
|
+
SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
|
|
151
|
+
f.path as file_path, e.classification, e.capabilities,
|
|
152
|
+
p.name as parent_name, p.kind as parent_kind
|
|
153
|
+
FROM exports e
|
|
154
|
+
JOIN files f ON e.file_path = f.path
|
|
155
|
+
LEFT JOIN exports p ON e.parent_id = p.id
|
|
156
|
+
WHERE p.name = ? AND e.name = ?
|
|
157
|
+
`;return i&&(r+=" AND f.path = ?",n.push(i)),r+=`
|
|
158
|
+
ORDER BY
|
|
159
|
+
CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
|
|
160
|
+
CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
|
|
161
|
+
LIMIT 10
|
|
162
|
+
`,this.all(r,...n)}findPotentialParents(e){return this.all(`
|
|
163
|
+
SELECT name, kind, file_path
|
|
164
|
+
FROM exports
|
|
165
|
+
WHERE kind IN ('ClassDeclaration', 'ClassExpression', 'TsInterfaceDeclaration')
|
|
166
|
+
AND id IN (
|
|
167
|
+
SELECT rowid FROM content_fts WHERE content MATCH ?
|
|
168
|
+
)
|
|
169
|
+
LIMIT 3
|
|
170
|
+
`,`"${e}"`)}findFuzzyCandidates(e){let t=e.charAt(0).toLowerCase();return this.all(`
|
|
171
|
+
SELECT DISTINCT name FROM exports
|
|
172
|
+
WHERE parent_id IS NULL
|
|
173
|
+
AND (name LIKE ? OR name LIKE ? OR ABS(LENGTH(name) - LENGTH(?)) <= 5)
|
|
174
|
+
ORDER BY ABS(LENGTH(name) - LENGTH(?)) ASC
|
|
175
|
+
LIMIT 1000
|
|
176
|
+
`,t+"%","%"+t+"%",e,e)}findTopLevelByFile(e){return this.all(`
|
|
177
|
+
SELECT * FROM exports
|
|
178
|
+
WHERE file_path = ? AND parent_id IS NULL
|
|
179
|
+
ORDER BY start_line ASC
|
|
180
|
+
`,e)}findFts(e,t=20){return this.all(`
|
|
181
|
+
SELECT e.*
|
|
182
|
+
FROM exports e
|
|
183
|
+
JOIN exports_fts ON e.id = exports_fts.rowid
|
|
184
|
+
WHERE exports_fts MATCH ?
|
|
185
|
+
LIMIT ?
|
|
186
|
+
`,e,t)}findByPartialName(e,t=20){return this.all(`
|
|
187
|
+
SELECT * FROM exports
|
|
188
|
+
WHERE lower(name) LIKE ?
|
|
189
|
+
LIMIT ?
|
|
190
|
+
`,`%${e.toLowerCase()}%`,t)}getAllNames(e=5e3){return this.all("SELECT DISTINCT name FROM exports WHERE parent_id IS NULL LIMIT ?",e).map(i=>i.name)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM exports WHERE file_path = ?",e)?.count||0}findDeadExports(e={}){let{limit:t=50,includeTests:i=!1,includeMigrations:n=!1,includeFixtures:r=!1,excludePatterns:c=[],confidenceThreshold:l="all"}=e,a=[];i||(a.push("e.file_path NOT LIKE '%/test/%'"),a.push("e.file_path NOT LIKE '%/tests/%'"),a.push("e.file_path NOT LIKE '%/__tests__/%'"),a.push("e.file_path NOT LIKE '%.spec.%'"),a.push("e.file_path NOT LIKE '%.test.%'")),n||(a.push("e.file_path NOT LIKE '%/migrations/%'"),a.push("e.file_path NOT LIKE '%/migration/%'"),a.push("e.file_path NOT LIKE '%Migration.%'")),r||(a.push("e.file_path NOT LIKE '%/__fixtures__/%'"),a.push("e.file_path NOT LIKE '%/__mocks__/%'"),a.push("e.file_path NOT LIKE '%/fixtures/%'"),a.push("e.file_path NOT LIKE '%/mocks/%'"),a.push("e.file_path NOT LIKE '%.fixture.%'"),a.push("e.file_path NOT LIKE '%.mock.%'"));for(let f of c){let T=f.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");a.push(`e.file_path NOT LIKE '${T}'`)}let o=a.length>0?`AND ${a.join(" AND ")}`:"",m=this.all(`
|
|
191
|
+
SELECT e.name, e.kind, e.file_path, e.start_line
|
|
192
|
+
FROM exports e
|
|
193
|
+
WHERE e.kind IN (
|
|
194
|
+
'FunctionDeclaration', 'ClassDeclaration',
|
|
195
|
+
'TsInterfaceDeclaration', 'TsTypeAliasDeclaration', 'TsEnumDeclaration',
|
|
196
|
+
'ArrowFunctionExpression', 'FunctionExpression'
|
|
197
|
+
)
|
|
198
|
+
AND e.parent_id IS NULL
|
|
199
|
+
${o}
|
|
200
|
+
AND NOT EXISTS (
|
|
201
|
+
SELECT 1
|
|
202
|
+
FROM imports i
|
|
203
|
+
WHERE REPLACE(i.imported_symbols, ' ', '') = e.name
|
|
204
|
+
OR REPLACE(i.imported_symbols, ' ', '') LIKE e.name || ',%'
|
|
205
|
+
OR REPLACE(i.imported_symbols, ' ', '') LIKE '%,' || e.name
|
|
206
|
+
OR REPLACE(i.imported_symbols, ' ', '') LIKE '%,' || e.name || ',%'
|
|
207
|
+
)
|
|
208
|
+
AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
|
|
209
|
+
ORDER BY e.file_path, e.start_line
|
|
210
|
+
LIMIT ?
|
|
211
|
+
`,t*2).filter(f=>!this.isFrameworkEntrypointExport(f)).map(f=>{let{confidence:T,reason:N}=this.scoreDeadExportConfidence(f);return{...f,confidence:T,reason:N}}),y=m;return l==="high"?y=m.filter(f=>f.confidence==="high"):l==="medium"&&(y=m.filter(f=>f.confidence==="high"||f.confidence==="medium")),y.slice(0,t)}scoreDeadExportConfidence(e){let t=e.file_path.toLowerCase(),i=e.name;return t.includes("/index.")||t.endsWith("index.ts")||t.endsWith("index.js")?{confidence:"low",reason:"Barrel/index file - likely re-export"}:e.kind==="TsInterfaceDeclaration"||e.kind==="TsTypeAliasDeclaration"?{confidence:"medium",reason:"Type definition - may be used externally"}:t.includes("/entry/")||t.includes("/bin/")||t.includes("main.")||t.includes("server.")||t.includes("cli.")?{confidence:"medium",reason:"Entry point - may be invoked externally"}:(t.includes("/components/")||t.endsWith(".tsx")||t.endsWith(".jsx"))&&/^[A-Z][A-Za-z0-9_]*$/.test(i)?{confidence:"medium",reason:"Component export - may be used by runtime composition"}:(t.includes("/contexts/")||t.includes("/context/"))&&(/Provider$/.test(i)||i.startsWith("use"))?{confidence:"medium",reason:"Context/provider export - may be wired dynamically"}:i.startsWith("create")||i.endsWith("Factory")||i.endsWith("Builder")?{confidence:"medium",reason:"Factory/builder pattern - may be used dynamically"}:i.startsWith("use")&&i.length>3?{confidence:"medium",reason:"Hook pattern - may be used in components"}:{confidence:"high",reason:"No detected usage"}}isFrameworkEntrypointExport(e){let i=e.file_path.toLowerCase().replace(/\\/g,"/"),n=e.name;return!!(/(^|\/)(src\/)?app\/.*\/route\.(t|j)sx?$/.test(i)&&s.HTTP_METHOD_EXPORTS.has(n)||/(^|\/)(src\/)?app\/.*\/(page|layout|loading|error|not-found|default|template)\.(t|j)sx?$/.test(i)||/(^|\/)(src\/)?middleware\.(t|j)sx?$/.test(i)||i.includes("/routes/")&&["loader","action","meta","headers"].includes(n))}getGravityMap(e=[],t){let i={},n=`
|
|
212
|
+
SELECT ws.symbol_id, m.name as mission_name, m.status
|
|
213
|
+
FROM working_set ws
|
|
214
|
+
JOIN missions m ON ws.mission_id = m.id
|
|
215
|
+
WHERE (
|
|
216
|
+
(m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
|
|
217
|
+
OR m.id IN (${e.length>0?e.join(","):"-1"})
|
|
218
|
+
)
|
|
219
|
+
AND ws.symbol_id IS NOT NULL
|
|
220
|
+
`,r=[];t&&r.push(t);let c=this.all(n,...r);for(let o of c){i[o.symbol_id]||(i[o.symbol_id]={score:1,reasons:[]});let u=o.status==="in-progress"||o.status==="verifying"?1:.5;i[o.symbol_id].score+=u;let p=o.status==="in-progress"||o.status==="verifying"?"Working Set":"Lineage Bleed";i[o.symbol_id].reasons.push(`${p}: ${o.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,a=this.all(`
|
|
221
|
+
SELECT symbol_id, type, mission_id
|
|
222
|
+
FROM intent_logs
|
|
223
|
+
WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
|
|
224
|
+
AND symbol_id IS NOT NULL
|
|
225
|
+
ORDER BY created_at DESC
|
|
226
|
+
LIMIT 200
|
|
227
|
+
`,l);for(let o of a){i[o.symbol_id]||(i[o.symbol_id]={score:1,reasons:[]});let u=o.mission_id?e.includes(o.mission_id):!1,p=u?.1:.2;i[o.symbol_id].score<5&&(i[o.symbol_id].score+=p);let m=u?`Lineage Intent: ${o.type}`:`Recent Intent: ${o.type}`;!i[o.symbol_id].reasons.includes(m)&&i[o.symbol_id].reasons.length<5&&i[o.symbol_id].reasons.push(m)}return i}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
|
|
228
|
+
SELECT kind, COUNT(*) as c
|
|
229
|
+
FROM exports
|
|
230
|
+
WHERE kind IS NOT NULL AND kind != ''
|
|
231
|
+
GROUP BY kind
|
|
232
|
+
ORDER BY c DESC
|
|
233
|
+
LIMIT ?
|
|
234
|
+
`,e)}getWithEmbeddingsCount(){return this.get("SELECT COUNT(*) as count FROM exports WHERE embedding IS NOT NULL")?.count||0}findByMethodName(e){return this.all(`
|
|
235
|
+
SELECT * FROM exports
|
|
236
|
+
WHERE name = ?
|
|
237
|
+
OR name LIKE ?
|
|
238
|
+
OR name LIKE ?
|
|
239
|
+
LIMIT 10
|
|
240
|
+
`,e,`%.${e}`,`%::${e}`)}findTypeGraphEdges(e,t={}){let{filePath:i,direction:n="both",relationship:r,limit:c=50}=t,l=Math.max(1,Math.min(c,500)),a=[];if(n==="both"||n==="outbound"){let o=`
|
|
241
|
+
SELECT
|
|
242
|
+
id,
|
|
243
|
+
file_path,
|
|
244
|
+
source_symbol_id,
|
|
245
|
+
source_symbol_name,
|
|
246
|
+
target_symbol_name,
|
|
247
|
+
relationship,
|
|
248
|
+
line_number,
|
|
249
|
+
metadata,
|
|
250
|
+
'outbound' AS direction
|
|
251
|
+
FROM type_graph_edges
|
|
252
|
+
WHERE source_symbol_name = ?
|
|
253
|
+
`,u=[e];i&&(o+=" AND file_path = ?",u.push(i)),r&&(o+=" AND relationship = ?",u.push(r)),o+=" ORDER BY file_path ASC, line_number ASC, target_symbol_name ASC LIMIT ?",u.push(l),a.push(...this.all(o,...u))}if(n==="both"||n==="inbound"){let o=`
|
|
254
|
+
SELECT
|
|
255
|
+
id,
|
|
256
|
+
file_path,
|
|
257
|
+
source_symbol_id,
|
|
258
|
+
source_symbol_name,
|
|
259
|
+
target_symbol_name,
|
|
260
|
+
relationship,
|
|
261
|
+
line_number,
|
|
262
|
+
metadata,
|
|
263
|
+
'inbound' AS direction
|
|
264
|
+
FROM type_graph_edges
|
|
265
|
+
WHERE target_symbol_name = ?
|
|
266
|
+
`,u=[e];r&&(o+=" AND relationship = ?",u.push(r)),o+=" ORDER BY file_path ASC, line_number ASC, source_symbol_name ASC LIMIT ?",u.push(l),a.push(...this.all(o,...u))}return a.slice(0,l)}findTypeGraphEdgesBySymbolId(e,t={}){let i=this.findById(e);return i?this.findTypeGraphEdges(i.name,{...t,filePath:i.file_path}):[]}};var Oe=`
|
|
267
|
+
WITH RECURSIVE dependency_chain AS (
|
|
268
|
+
-- Base case: Direct dependents of the target symbol
|
|
269
|
+
-- Meaning: Files that import the file where the symbol is defined
|
|
270
|
+
SELECT
|
|
271
|
+
i.file_path as consumer_path,
|
|
272
|
+
i.module_specifier,
|
|
273
|
+
i.imported_symbols,
|
|
274
|
+
f.path as source_path,
|
|
275
|
+
1 as depth,
|
|
276
|
+
i.file_path || '<-' || f.path as path_chain
|
|
277
|
+
FROM imports i
|
|
278
|
+
JOIN files f ON i.resolved_path = f.path
|
|
279
|
+
WHERE f.path = ? -- The file where our changed symbol lives
|
|
280
|
+
AND (
|
|
281
|
+
-- Exact symbol match or wildcard import
|
|
282
|
+
i.imported_symbols LIKE ?
|
|
283
|
+
OR i.imported_symbols = '*'
|
|
284
|
+
OR i.imported_symbols = 'default'
|
|
285
|
+
OR i.imported_symbols = ''
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
UNION ALL
|
|
289
|
+
|
|
290
|
+
-- Recursive step: Find consumers of the consumers
|
|
291
|
+
SELECT
|
|
292
|
+
i.file_path as consumer_path,
|
|
293
|
+
i.module_specifier,
|
|
294
|
+
i.imported_symbols,
|
|
295
|
+
dc.consumer_path as source_path,
|
|
296
|
+
dc.depth + 1,
|
|
297
|
+
i.file_path || '<-' || dc.path_chain
|
|
298
|
+
FROM imports i
|
|
299
|
+
JOIN dependency_chain dc ON i.resolved_path = dc.consumer_path
|
|
300
|
+
WHERE dc.depth < ? -- Max depth limit
|
|
301
|
+
AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection
|
|
302
|
+
AND (
|
|
303
|
+
-- If the intermediate file is a re-exporter (barrel),
|
|
304
|
+
-- the next consumer must still be looking for the symbol
|
|
305
|
+
i.imported_symbols LIKE ?
|
|
306
|
+
OR i.imported_symbols = '*'
|
|
307
|
+
OR i.imported_symbols = ''
|
|
308
|
+
)
|
|
309
|
+
)
|
|
310
|
+
SELECT DISTINCT
|
|
311
|
+
dc.consumer_path,
|
|
312
|
+
dc.depth,
|
|
313
|
+
dc.source_path,
|
|
314
|
+
dc.imported_symbols
|
|
315
|
+
FROM dependency_chain dc
|
|
316
|
+
ORDER BY dc.depth, dc.consumer_path;
|
|
317
|
+
`;var j=class extends E{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(`
|
|
318
|
+
SELECT * FROM imports
|
|
319
|
+
WHERE resolved_path IS NOT NULL AND resolved_path != ''
|
|
320
|
+
`)}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(`
|
|
321
|
+
SELECT *
|
|
322
|
+
FROM imports
|
|
323
|
+
WHERE file_path = ?
|
|
324
|
+
AND (imported_symbols LIKE ? OR imported_symbols = '*')
|
|
325
|
+
LIMIT 1
|
|
326
|
+
`,e,`%${t}%`)}findProxies(e){return this.all(`
|
|
327
|
+
SELECT i.file_path
|
|
328
|
+
FROM imports i
|
|
329
|
+
JOIN exports e ON i.file_path = e.file_path
|
|
330
|
+
WHERE i.resolved_path = ?
|
|
331
|
+
AND (e.kind = 'ExportAllDeclaration' OR e.kind = 'ExportMapping')
|
|
332
|
+
`,e)}findVerifiedDependents(e,t){if(e.length===0)return[];let i=e.map(()=>"?").join(", ");return this.all(`
|
|
333
|
+
SELECT i.file_path, i.imported_symbols, f.classification, f.summary
|
|
334
|
+
FROM imports i
|
|
335
|
+
JOIN files f ON i.file_path = f.path
|
|
336
|
+
WHERE i.resolved_path IN (${i})
|
|
337
|
+
AND (i.imported_symbols LIKE ? OR i.imported_symbols = '' OR i.imported_symbols = '*')
|
|
338
|
+
LIMIT 10
|
|
339
|
+
`,...e,`%${t}%`)}countVerifiedDependents(e,t){if(e.length===0)return 0;let i=e.map(()=>"?").join(", ");return this.get(`
|
|
340
|
+
SELECT COUNT(*) as count FROM imports
|
|
341
|
+
WHERE resolved_path IN (${i})
|
|
342
|
+
AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
|
|
343
|
+
`,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,i){return this.all(Oe,e,t,i,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}};var V=class extends E{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')",i=[];return e&&(t+=" AND git_branch = ?",i.push(e)),t+=` ORDER BY
|
|
344
|
+
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
345
|
+
created_at ASC`,this.all(t,...i)}findAll(e){let t="SELECT * FROM missions",i=[];return e&&(t+=" WHERE status = ?",i.push(e)),t+=` ORDER BY
|
|
346
|
+
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
347
|
+
created_at ASC`,this.all(t,...i)}findRecentCompleted(e=3){return this.all(`
|
|
348
|
+
SELECT * FROM missions
|
|
349
|
+
WHERE status = 'completed'
|
|
350
|
+
ORDER BY updated_at DESC, id DESC
|
|
351
|
+
LIMIT ?
|
|
352
|
+
`,e)}create(e){return this.insert(`
|
|
353
|
+
INSERT INTO missions (name, goal, strategy_graph, status, git_branch, commit_sha, parent_id, verification_context, outcome_contract)
|
|
354
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
355
|
+
`,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,i,n){this.run("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,t,i,n?JSON.stringify(n):null)}getArtifacts(e){return this.all("SELECT * FROM mission_artifacts WHERE mission_id = ?",e)}update(e,t){let i=Object.keys(t);if(i.length===0)return;let n=i.map(c=>`${c} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE missions SET ${n}, updated_at = unixepoch() WHERE id = ?`,...r)}updateStatus(e,t,i){i?this.run("UPDATE missions SET status = ?, updated_at = unixepoch(), commit_sha = ? WHERE id = ?",t,i,e):this.run("UPDATE missions SET status = ?, updated_at = unixepoch() WHERE id = ?",t,e)}getWorkingSet(e){let t=this.all(`
|
|
356
|
+
SELECT file_path, type, source_priority, created_at
|
|
357
|
+
FROM (
|
|
358
|
+
SELECT
|
|
359
|
+
ws.file_path,
|
|
360
|
+
COALESCE(ws.type, 'file') AS type,
|
|
361
|
+
0 AS source_priority,
|
|
362
|
+
ws.created_at
|
|
363
|
+
FROM working_set ws
|
|
364
|
+
WHERE ws.mission_id = ?
|
|
365
|
+
|
|
366
|
+
UNION ALL
|
|
367
|
+
|
|
368
|
+
SELECT
|
|
369
|
+
il.file_path,
|
|
370
|
+
'intent' AS type,
|
|
371
|
+
1 AS source_priority,
|
|
372
|
+
il.created_at
|
|
373
|
+
FROM intent_logs il
|
|
374
|
+
WHERE il.mission_id = ?
|
|
375
|
+
AND il.file_path IS NOT NULL
|
|
376
|
+
|
|
377
|
+
UNION ALL
|
|
378
|
+
|
|
379
|
+
SELECT
|
|
380
|
+
e.file_path,
|
|
381
|
+
'symbol' AS type,
|
|
382
|
+
2 AS source_priority,
|
|
383
|
+
il.created_at
|
|
384
|
+
FROM intent_logs il
|
|
385
|
+
JOIN exports e ON e.id = il.symbol_id
|
|
386
|
+
WHERE il.mission_id = ?
|
|
387
|
+
AND e.file_path IS NOT NULL
|
|
388
|
+
)
|
|
389
|
+
WHERE file_path IS NOT NULL
|
|
390
|
+
ORDER BY source_priority ASC, created_at DESC, file_path ASC
|
|
391
|
+
`,e,e,e),i=new Map;for(let n of t)!n.file_path||i.has(n.file_path)||i.set(n.file_path,{file_path:n.file_path,type:n.type||"file"});return[...i.values()]}clearWorkingSet(e){this.run("DELETE FROM working_set WHERE mission_id = ?",e)}addToWorkingSet(e,t,i="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,i)}findColdMissions(e,t=10){return this.all(`
|
|
392
|
+
SELECT m.id, COUNT(il.id) as log_count
|
|
393
|
+
FROM missions m
|
|
394
|
+
LEFT JOIN intent_logs il ON il.mission_id = m.id
|
|
395
|
+
WHERE m.updated_at < ?
|
|
396
|
+
AND m.status != 'distilled'
|
|
397
|
+
GROUP BY m.id
|
|
398
|
+
HAVING log_count > ?
|
|
399
|
+
`,e,t).map(n=>n.id)}getStats(){let e=this.get(`
|
|
400
|
+
SELECT
|
|
401
|
+
COUNT(*) as total,
|
|
402
|
+
SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
|
|
403
|
+
SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
|
|
404
|
+
FROM missions
|
|
405
|
+
`);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,i=this.get(`
|
|
406
|
+
SELECT AVG(updated_at - created_at) AS avg_duration
|
|
407
|
+
FROM missions
|
|
408
|
+
WHERE status = 'completed' AND updated_at > created_at
|
|
409
|
+
`),n=i?.avg_duration!=null?Math.round(i.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,c=Math.floor(Date.now()/1e3)-720*3600,l=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),a=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",c),o=l?.n??0,u=a?.n??0,p=`${o} completed in last 7 days, ${u} in last 30 days.`;if(n!=null){let m=Math.round(n/60);p+=` Avg mission duration: ${m} min.`}return{completionRate:t,averageDurationSeconds:n,completedLast7Days:o,completedLast30Days:u,velocityNote:p}}suspendByBranch(e){return this.run(`UPDATE missions
|
|
410
|
+
SET status = 'suspended', updated_at = unixepoch()
|
|
411
|
+
WHERE git_branch = ? AND status IN ('in-progress', 'verifying')`,e)}resumeByBranch(e){return this.run(`UPDATE missions
|
|
412
|
+
SET status = 'in-progress', updated_at = unixepoch()
|
|
413
|
+
WHERE git_branch = ? AND status = 'suspended'`,e)}findMergedMissions(e,t){if(t.length===0)return[];let i=t.filter(r=>r!==e);if(i.length===0)return[];let n=i.map(()=>"?").join(",");return this.all(`SELECT * FROM missions
|
|
414
|
+
WHERE status IN ('in-progress', 'planned', 'verifying', 'suspended')
|
|
415
|
+
AND git_branch IN (${n})`,...i)}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),i=t?.steps??t;return!Array.isArray(i)||i.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,i,n,r){this.db.exec(`
|
|
416
|
+
CREATE TABLE IF NOT EXISTS cross_repo_links (
|
|
417
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
418
|
+
mission_id INTEGER NOT NULL,
|
|
419
|
+
linked_repo_path TEXT NOT NULL,
|
|
420
|
+
linked_mission_id INTEGER NOT NULL,
|
|
421
|
+
relationship TEXT,
|
|
422
|
+
direction TEXT,
|
|
423
|
+
created_at REAL DEFAULT (unixepoch()),
|
|
424
|
+
FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
|
|
425
|
+
);
|
|
426
|
+
CREATE INDEX IF NOT EXISTS idx_cross_repo_mission ON cross_repo_links(mission_id);
|
|
427
|
+
`),this.run(`
|
|
428
|
+
INSERT INTO cross_repo_links (mission_id, linked_repo_path, linked_mission_id, relationship, direction)
|
|
429
|
+
VALUES (?, ?, ?, ?, ?)
|
|
430
|
+
`,e,t,i,n,r)}getLinks(e){try{return this.all(`
|
|
431
|
+
SELECT linked_repo_path, linked_mission_id, relationship, direction
|
|
432
|
+
FROM cross_repo_links
|
|
433
|
+
WHERE mission_id = ?
|
|
434
|
+
`,e)}catch{return[]}}findLastMission(){return this.get("SELECT * FROM missions ORDER BY updated_at DESC, id DESC LIMIT 1")}findActiveByPriority(){return this.get("SELECT * FROM missions WHERE status IN ('in-progress', 'active', 'verifying') ORDER BY CASE WHEN status = 'in-progress' THEN 0 ELSE 1 END, created_at ASC LIMIT 1")}addHandoff(e,t){let i=JSON.stringify(t),n=e??0,r=this.insert("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",n,"handoff",t.kind,i),c=[`[handoff:${t.kind}]`,...t.findings.map(l=>l.statement),...t.risks.map(l=>l.description),...t.gaps].filter(Boolean).join(" ");return Promise.resolve().then(()=>(S(),I)).then(({generateEmbedding:l})=>l(c)).then(l=>{l&&this.run("UPDATE mission_artifacts SET embedding = ? WHERE id = ?",JSON.stringify(l),r)}).catch(()=>{}),r}getHandoffs(e,t,i=20){let n=["type = 'handoff'"],r=[];e!==void 0&&(n.push("mission_id = ?"),r.push(e??0)),t&&(n.push("identifier = ?"),r.push(t));let c=`SELECT * FROM mission_artifacts WHERE ${n.join(" AND ")} ORDER BY created_at DESC LIMIT ?`;return r.push(i),this.all(c,...r)}async findSemanticHandoffs(e,t=5){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(S(),I)),n=this.all("SELECT * FROM mission_artifacts WHERE type = 'handoff' AND embedding IS NOT NULL"),r=[];for(let c of n)try{let l=JSON.parse(c.embedding),a=i(e,l);a>.3&&r.push({...c,similarity:a})}catch{}return r.sort((c,l)=>l.similarity-c.similarity).slice(0,t)}};M();var J=class s extends E{findByMission(e,t=50){return this.all(`
|
|
435
|
+
SELECT
|
|
436
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
437
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
438
|
+
created_at
|
|
439
|
+
FROM intent_logs
|
|
440
|
+
WHERE mission_id = ?
|
|
441
|
+
ORDER BY created_at DESC
|
|
442
|
+
LIMIT ?
|
|
443
|
+
`,e,t)}findRecentDecisionActivity(e=10){return this.all(`
|
|
444
|
+
SELECT
|
|
445
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
446
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
447
|
+
created_at
|
|
448
|
+
FROM intent_logs
|
|
449
|
+
WHERE type IN ('decision', 'system', 'fix', 'heritage', 'adr')
|
|
450
|
+
ORDER BY created_at DESC
|
|
451
|
+
LIMIT ?
|
|
452
|
+
`,e)}create(e){let t=this.insert(`
|
|
453
|
+
INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
|
|
454
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
455
|
+
`,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha);return s.EMBEDDABLE_TYPES.has(e.type)&&this.generateAndStoreEmbedding(Number(t),e).catch(i=>{d.debug({err:i,intentLogId:t},"Failed to generate intent log embedding")}),t}static EMBEDDABLE_TYPES=new Set(["decision","discovery","fix","blocker","note","heritage","crystal"]);static buildEmbeddingText(e){let t=[`[${e.type}]`];return e.symbol_name&&t.push(`symbol: ${e.symbol_name}`),e.file_path&&t.push(`file: ${e.file_path.split("/").pop()}`),t.push(e.content),t.join(" ")}async generateAndStoreEmbedding(e,t){let{generateEmbedding:i}=await Promise.resolve().then(()=>(S(),I)),n=s.buildEmbeddingText(t),r=await i(n);r&&this.run("UPDATE intent_logs SET embedding = ? WHERE id = ?",JSON.stringify(r),e)}findWithEmbeddings(){return this.all("SELECT * FROM intent_logs WHERE embedding IS NOT NULL AND type NOT IN ('system', 'lapsed')")}async findSemanticMatches(e,t,i){let{cosineSimilarity:n}=await Promise.resolve().then(()=>(S(),I)),r=this.findWithEmbeddings();if(r.length>5e3)return d.warn({count:r.length},"Intent log count exceeds brute-force vector scan limit (5000). Skipping semantic recall."),[];let c=[];for(let l of r)if(!(i&&l.symbol_id===i))try{let a=JSON.parse(l.embedding),o=n(e,a);o>.25&&c.push({id:l.id,mission_id:l.mission_id,type:l.type,content:l.content,symbol_name:l.symbol_name,file_path:l.file_path,similarity:o,created_at:l.created_at})}catch{}return c.sort((l,a)=>a.similarity-l.similarity).slice(0,t)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let i=Object.keys(t);if(i.length===0)return;let n=i.map(c=>`${c} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${n} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
|
|
456
|
+
SELECT id, file_path, symbol_name, signature
|
|
457
|
+
FROM intent_logs
|
|
458
|
+
WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
|
|
459
|
+
`)}findOrphans(){return this.all(`
|
|
460
|
+
SELECT il.id, il.symbol_id, il.file_path, il.symbol_name
|
|
461
|
+
FROM intent_logs il
|
|
462
|
+
WHERE (il.symbol_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM exports e WHERE e.id = il.symbol_id))
|
|
463
|
+
OR (il.symbol_id IS NULL AND il.type != 'lapsed' AND il.type != 'system' AND il.type != 'adr')
|
|
464
|
+
`)}findLogsForMissingFiles(){return this.all(`
|
|
465
|
+
SELECT il.id
|
|
466
|
+
FROM intent_logs il
|
|
467
|
+
WHERE il.file_path IS NOT NULL
|
|
468
|
+
AND NOT EXISTS (
|
|
469
|
+
SELECT 1 FROM files f WHERE f.path = il.file_path
|
|
470
|
+
)
|
|
471
|
+
`)}markAsLapsed(e){this.run(`
|
|
472
|
+
UPDATE intent_logs
|
|
473
|
+
SET symbol_id = NULL,
|
|
474
|
+
type = 'lapsed',
|
|
475
|
+
content = 'Lapsed: ' || content
|
|
476
|
+
WHERE id = ?
|
|
477
|
+
`,e)}importHeritage(e,t,i,n){this.run(`
|
|
478
|
+
INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
|
|
479
|
+
VALUES ('heritage', ?, ?, ?, ?, NULL)
|
|
480
|
+
`,e,t,i,n)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}findRawByMission(e){return this.all(`SELECT
|
|
481
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
482
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
483
|
+
created_at
|
|
484
|
+
FROM intent_logs
|
|
485
|
+
WHERE mission_id = ? AND is_crystallized = 0
|
|
486
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
487
|
+
ORDER BY created_at ASC`,e)}findCrystalByMission(e){return this.get(`SELECT
|
|
488
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
489
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
490
|
+
created_at
|
|
491
|
+
FROM intent_logs
|
|
492
|
+
WHERE mission_id = ? AND type = 'crystal'
|
|
493
|
+
ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t){return this.transaction(()=>{let i=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
|
|
494
|
+
VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
|
|
495
|
+
SET is_crystallized = 1, crystal_id = ?
|
|
496
|
+
WHERE mission_id = ? AND is_crystallized = 0 AND id != ?
|
|
497
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,i,e,i),i})}findRawBySymbol(e){return this.all(`SELECT * FROM intent_logs
|
|
498
|
+
WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0
|
|
499
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
500
|
+
ORDER BY created_at ASC`,e)}crystallizeBySymbol(e,t){return this.transaction(()=>{let i=this.insert(`INSERT INTO intent_logs (mission_id, symbol_id, type, content, confidence, is_crystallized, file_path, symbol_name, signature, commit_sha)
|
|
501
|
+
VALUES (NULL, ?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
|
|
502
|
+
SET is_crystallized = 1, crystal_id = ?
|
|
503
|
+
WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0 AND id != ?
|
|
504
|
+
AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,i,e,i),i})}countByMissions(e){if(e.length===0)return{};let t=e.map(()=>"?").join(","),i=this.all(`SELECT mission_id, COUNT(*) as cnt
|
|
505
|
+
FROM intent_logs
|
|
506
|
+
WHERE mission_id IN (${t})
|
|
507
|
+
AND type NOT IN ('system', 'adr', 'lapsed')
|
|
508
|
+
GROUP BY mission_id`,...e),n={};for(let r of i)n[r.mission_id]=r.cnt;return n}findMissionsWithBlockers(e){if(e.length===0)return new Set;let t=e.map(()=>"?").join(","),i=this.all(`SELECT DISTINCT mission_id
|
|
509
|
+
FROM intent_logs
|
|
510
|
+
WHERE mission_id IN (${t})
|
|
511
|
+
AND type = 'blocker'`,...e);return new Set(i.map(n=>n.mission_id))}findByMissionPreferCrystal(e,t=50){let i=this.findCrystalByMission(e);if(i){let n=this.all(`SELECT
|
|
512
|
+
id, mission_id, symbol_id, file_path, type, content, confidence,
|
|
513
|
+
symbol_name, signature, commit_sha, is_crystallized, crystal_id,
|
|
514
|
+
created_at
|
|
515
|
+
FROM intent_logs
|
|
516
|
+
WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
|
|
517
|
+
AND created_at > ?
|
|
518
|
+
ORDER BY created_at DESC LIMIT ?`,e,i.created_at,t-1);return[i,...n]}return this.findByMission(e,t)}async findSemanticTheme(e,t,i=200){let{cosineSimilarity:n}=await Promise.resolve().then(()=>(S(),I)),r=this.findWithEmbeddings(),c=[];for(let l of r)if(s.EMBEDDABLE_TYPES.has(l.type)&&!(t&&l.mission_id!==null&&!t.includes(l.mission_id)))try{let a=JSON.parse(l.embedding),o=n(e,a);o>.35&&c.push({...l,_similarity:o})}catch{}return c.sort((l,a)=>a._similarity-l._similarity).slice(0,i).map(({_similarity:l,...a})=>a)}crystallizeTheme(e,t,i){return this.transaction(()=>{let n=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
|
|
519
|
+
VALUES (NULL, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,i);if(t.length>0){let r=t.map(()=>"?").join(",");this.run(`UPDATE intent_logs SET is_crystallized = 1, crystal_id = ? WHERE id IN (${r})`,n,...t)}return n})}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:i}=await Promise.resolve().then(()=>(S(),I)),n=[...s.EMBEDDABLE_TYPES].map(u=>`'${u}'`).join(","),r=this.all(`SELECT * FROM intent_logs WHERE embedding IS NULL AND type IN (${n})`);if(r.length===0)return 0;let c=r.map(u=>s.buildEmbeddingText(u)),l=await i(c,e,t),a=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),o=0;return this.transaction(()=>{for(let u=0;u<r.length;u++)l[u]&&(a.run(JSON.stringify(l[u]),r[u].id),o++)}),d.info({total:r.length,embedded:o},"Intent log embedding backfill complete"),o}};var Q=class extends E{findByKey(e,t=20){return this.all(`
|
|
520
|
+
SELECT file_path, key, value, kind
|
|
521
|
+
FROM configs
|
|
522
|
+
WHERE key LIKE ? OR value LIKE ?
|
|
523
|
+
LIMIT ?
|
|
524
|
+
`,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let i="SELECT key, value, kind, file_path FROM configs",n=[];return e&&(i+=" WHERE kind = ?",n.push(e)),i+=" LIMIT ?",n.push(t),this.all(i,...n)}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 X=class extends E{search(e,t=10){return this.all(`
|
|
525
|
+
SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
|
|
526
|
+
FROM content_fts
|
|
527
|
+
WHERE content_fts MATCH ?
|
|
528
|
+
LIMIT ?
|
|
529
|
+
`,e,t)}};var Pe=500,Z=class extends E{record(e,t,i=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,i),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
|
|
530
|
+
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)<=Pe||this.run(`DELETE FROM search_history WHERE id NOT IN (
|
|
531
|
+
SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
|
|
532
|
+
)`,Pe)}};var ee=class extends E{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(`
|
|
533
|
+
INSERT INTO hologram_snapshot (section, data, updated_at)
|
|
534
|
+
VALUES (?, ?, unixepoch())
|
|
535
|
+
ON CONFLICT(section) DO UPDATE SET
|
|
536
|
+
data = excluded.data,
|
|
537
|
+
updated_at = excluded.updated_at
|
|
538
|
+
`,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 te=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=v(e),c=t.files?.database,l=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(c===r&&r.open&&!l)return t;this.repositoryCache.delete(e)}let i=v(e),n={files:new K(i),exports:new q(i),imports:new j(i),missions:new V(i),intentLogs:new J(i),configs:new Q(i),content:new X(i),searchHistory:new Z(i),hologram:new ee(i)};return this.repositoryCache.set(e,n),n}static closeInstance(e){this.repositoryCache.delete(e),Re(e)}static clearCache(e){this.repositoryCache.delete(e)}};S();var $e=new Set(["FunctionDeclaration","ClassDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","HTTP Route","Socket Event","Pub/Sub Topic","function","class","interface","type","enum"]),ze={"HTTP Route":0,"Socket Event":0,"Pub/Sub Topic":0,TsInterfaceDeclaration:1,TsTypeAliasDeclaration:1,TsEnumDeclaration:1,interface:1,type:1,enum:1,FunctionDeclaration:2,function:2,ClassDeclaration:3,class:3};function Ye(s,e,t=[]){let i=t.length>0?`${t.join(" > ")} > ${e.name}`:String(e.name),n=[`Symbol: ${e.name}`,`Kind: ${e.kind??"Unknown"}`,`Scope: ${i}`,`File: ${s}`];return e.signature&&n.push(`Signature: ${String(e.signature)}`),e.doc&&n.push(`Doc: ${String(e.doc)}`),n.join(`
|
|
539
|
+
`)}function Ke(s){return s.map(()=>"?").join(",")}var jt=de.constants.priority.PRIORITY_LOWEST??de.constants.priority.PRIORITY_LOW,ie=process.argv[2];ie||(process.stderr.write(`Ember: repoPath argument missing
|
|
540
|
+
`),process.exit(1));try{de.setPriority(jt)}catch{}function w(s,e){s.transaction(()=>{let t=s.prepare("INSERT OR REPLACE INTO ember_state (key, value, updated_at) VALUES (?, ?, unixepoch())");for(let[i,n]of Object.entries(e))t.run(i,n??null)})()}var qe=100,se=[...$e],je=Ke(se),Gt=se.map(s=>`WHEN '${s.replace(/'/g,"''")}' THEN ${ze[s]??2}`).join(" ").trim(),ne=x({numWorkers:2}),_;async function Vt(){_=v(ie),w(_,{status:"running",pid:String(process.pid),started_at:String(Date.now()),repo_path:ie}),await ne.initialize();let e=_.prepare(`SELECT COUNT(*) as c FROM exports WHERE embedding IS NULL AND kind IN (${je})`).get(...se).c,t=0;w(_,{progress:`0/${e}`});let i=_.prepare(`SELECT id, file_path, name, kind, signature, doc, start_line, end_line
|
|
541
|
+
FROM exports
|
|
542
|
+
WHERE embedding IS NULL AND kind IN (${je})
|
|
543
|
+
ORDER BY CASE kind ${Gt} END
|
|
544
|
+
LIMIT ${qe}`),n=_.prepare("UPDATE exports SET embedding = ? WHERE id = ?");for(;;){let r=i.all(...se);if(r.length===0)break;let c=r.map(a=>Ye(a.file_path,a)),l=await ne.generateEmbeddings(c,qe);_.transaction(()=>{for(let a=0;a<r.length;a++){let o=l[a];o&&n.run(JSON.stringify(o),r[a].id)}})(),t+=r.length,w(_,{progress:`${t}/${e}`})}try{await te.getInstance(ie).intentLogs.backfillEmbeddings(64)}catch{}w(_,{status:"done",progress:`${t}/${e}`}),await ne.shutdown(),process.exit(0)}async function Ge(){try{_&&w(_,{status:"idle"}),await ne.shutdown()}catch{}process.exit(0)}process.on("SIGTERM",()=>{Ge()});process.on("SIGINT",()=>{Ge()});Vt().catch(s=>{process.stderr.write(`Ember error: ${s instanceof Error?s.message:String(s)}
|
|
545
|
+
`);try{_&&w(_,{status:"error"})}catch{}process.exit(1)});
|