@precisionutilityguild/liquid-shadow 1.0.9 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +3 -3
  2. package/dist/data/migrations/000_baseline.sql +17 -0
  3. package/dist/data/migrations/014_tribunal_state.sql +24 -0
  4. package/dist/data/migrations/015_repo_level_handoffs_nullable.sql +52 -0
  5. package/dist/data/migrations/016_repair_tribunal_artifact_fk.sql +58 -0
  6. package/dist/entry/cli/index.js +540 -493
  7. package/dist/entry/ember/index.js +44 -20
  8. package/dist/entry/mcp/server.js +388 -347
  9. package/dist/entry/tribunal/index.js +650 -0
  10. package/dist/index.js +387 -346
  11. package/dist/logic/parser/index.js +16 -16
  12. package/dist/skills/shadow_audit/SKILL.md +22 -30
  13. package/dist/skills/shadow_chronicle/SKILL.md +16 -29
  14. package/dist/skills/shadow_continue/SKILL.md +37 -53
  15. package/dist/skills/shadow_coordinate/SKILL.md +46 -0
  16. package/dist/skills/shadow_crystallize/SKILL.md +13 -27
  17. package/dist/skills/shadow_mission/SKILL.md +27 -41
  18. package/dist/skills/shadow_onboard/SKILL.md +26 -35
  19. package/dist/skills/shadow_research/SKILL.md +15 -23
  20. package/dist/skills/shadow_sync/SKILL.md +18 -9
  21. package/dist/skills/shadow_synthesize/SKILL.md +14 -36
  22. package/dist/skills/shadow_trace_impact/SKILL.md +30 -50
  23. package/dist/skills/shadow_understand/SKILL.md +37 -52
  24. package/dist/skills/shadow_workspace/SKILL.md +17 -17
  25. package/dist/web-manifest.json +13 -6
  26. package/package.json +1 -1
  27. package/skills/shadow_audit/SKILL.md +22 -30
  28. package/skills/shadow_chronicle/SKILL.md +16 -29
  29. package/skills/shadow_continue/SKILL.md +37 -53
  30. package/skills/shadow_coordinate/SKILL.md +46 -0
  31. package/skills/shadow_crystallize/SKILL.md +13 -27
  32. package/skills/shadow_mission/SKILL.md +27 -41
  33. package/skills/shadow_onboard/SKILL.md +26 -35
  34. package/skills/shadow_research/SKILL.md +15 -23
  35. package/skills/shadow_sync/SKILL.md +18 -9
  36. package/skills/shadow_synthesize/SKILL.md +14 -36
  37. package/skills/shadow_trace_impact/SKILL.md +30 -50
  38. package/skills/shadow_understand/SKILL.md +37 -52
  39. package/skills/shadow_workspace/SKILL.md +17 -17
@@ -1,10 +1,10 @@
1
- var at=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var lt=(s,e)=>{for(var t in e)at(s,t,{get:e[t],enumerable:!0})};import ct from"pino";var ut,dt,d,M=P(()=>{"use strict";ut={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},dt=ct({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:ut[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),d=dt});import{fileURLToPath as xt}from"node:url";import{dirname as le,join as Me,resolve as wt}from"node:path";import{existsSync as kt}from"node:fs";function Wt(){let s=Ce;for(;s!==le(s);){if(kt(Me(s,"package.json")))return s;s=le(s)}return wt(Ce,"..","..")}function De(...s){return Me(Wt(),...s)}var Ft,Ce,Ae=P(()=>{"use strict";Ft=xt(import.meta.url),Ce=le(Ft)});import{Worker as Ht}from"node:worker_threads";import{cpus as vt}from"node:os";import{fileURLToPath as Bt}from"node:url";import{dirname as Ut,join as xe}from"node:path";import{existsSync as we}from"node:fs";function Pt(){if(Fe.endsWith(".ts")){let e=xe(ke,"worker.ts");if(we(e))return e}let s=xe(ke,"worker.js");return we(s)?s:De("dist/logic/domain/embeddings/worker.js")}function x(s){return A||(A=new W(s)),A}async function We(){A&&(await A.shutdown(),A=null)}var Fe,ke,W,A,He=P(()=>{"use strict";M();Ae();Fe=Bt(import.meta.url),ke=Ut(Fe);W=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,vt().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=Pt();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((m,p)=>{let g={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)}m()},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)}m()}};this.taskQueue.push(g),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={};lt(I,{EmbeddingPriorityQueue:()=>ue,EmbeddingWorkerPool:()=>W,cosineSimilarity:()=>qt,generateEmbedding:()=>Kt,generateEmbeddingsBatch:()=>jt,getDefaultPool:()=>x,setUseWorkerThreads:()=>zt,shutdownDefaultPool:()=>We});async function $t(){return H||(H=await import("@xenova/transformers"),H.env.cacheDir="./.cache",H.env.allowLocalModels=!0),H}function zt(s){de=s,d.info({useWorkerThreads:s},"Worker thread mode updated")}function ve(s=!1){let e=(v||"").toLowerCase(),t={};return v&&(t.dtype=v),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 Yt(){d.info({model:G,dtype:v},"Loading embedding model...");let{pipeline:s}=await $t(),e=ve(!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:v},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",G,ve(!0))}}async function Ue(){return ce||(ce=Yt()),ce}async function Kt(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 jt(s,e=Be,t){return s.length===0?[]:de?x().generateEmbeddings(s,e,t):Pe(s,e,t)}async function Pe(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 m=0;m<o;m++){let p=m*u,y=p+u;i[r+m]=Array.from(a.data.slice(p,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 m=await n(u,{pooling:"mean",normalize:!0});i[r+o]=Array.from(m.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,v,H,Be,de,ce,ue,L=P(()=>{"use strict";M();He();G=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",v=process.env.EMBEDDING_DTYPE??"fp32",H=null;Be=128,de=!1;ce=null;ue=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=Be,t){if(this.processing)return d.warn("Queue processing already in progress"),this.results;this.processing=!0;let i=this.queue.length;try{de?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 Pe(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 me from"node:os";M();import Tt from"better-sqlite3";import z from"path";import Re from"fs";import Rt from"crypto";M();import O from"fs";import $ from"path";import{fileURLToPath as mt}from"url";var R=d.child({module:"migrations"}),pt=mt(import.meta.url),Et=$.dirname(pt);function ht(){let s=Et;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 ft(s){s.exec(`
1
+ var at=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var lt=(s,e)=>{for(var t in e)at(s,t,{get:e[t],enumerable:!0})};import ct from"pino";var ut,dt,d,M=P(()=>{"use strict";ut={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},dt=ct({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(s,e){return{level:s,severity:ut[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),d=dt});import{fileURLToPath as xt}from"node:url";import{dirname as le,join as Me,resolve as wt}from"node:path";import{existsSync as kt}from"node:fs";function Wt(){let s=Ce;for(;s!==le(s);){if(kt(Me(s,"package.json")))return s;s=le(s)}return wt(Ce,"..","..")}function Ae(...s){return Me(Wt(),...s)}var Ft,Ce,De=P(()=>{"use strict";Ft=xt(import.meta.url),Ce=le(Ft)});import{Worker as vt}from"node:worker_threads";import{cpus as Ht}from"node:os";import{fileURLToPath as Bt}from"node:url";import{dirname as Ut,join as xe}from"node:path";import{existsSync as we}from"node:fs";function Pt(){if(Fe.endsWith(".ts")){let e=xe(ke,"worker.ts");if(we(e))return e}let s=xe(ke,"worker.js");return we(s)?s:Ae("dist/logic/domain/embeddings/worker.js")}function x(s){return D||(D=new W(s)),D}async function We(){D&&(await D.shutdown(),D=null)}var Fe,ke,W,D,ve=P(()=>{"use strict";M();De();Fe=Bt(import.meta.url),ke=Ut(Fe);W=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,Ht().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=Pt();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 vt(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((m,p)=>{let g={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)}m()},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)}m()}};this.taskQueue.push(g),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")}},D=null});var O={};lt(O,{EmbeddingPriorityQueue:()=>ue,EmbeddingWorkerPool:()=>W,cosineSimilarity:()=>qt,generateEmbedding:()=>Yt,generateEmbeddingsBatch:()=>jt,getDefaultPool:()=>x,setUseWorkerThreads:()=>zt,shutdownDefaultPool:()=>We});async function $t(){return v||(v=await import("@xenova/transformers"),v.env.cacheDir="./.cache",v.env.allowLocalModels=!0),v}function zt(s){de=s,d.info({useWorkerThreads:s},"Worker thread mode updated")}function He(s=!1){let e=(H||"").toLowerCase(),t={};return H&&(t.dtype=H),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 Kt(){d.info({model:G,dtype:H},"Loading embedding model...");let{pipeline:s}=await $t(),e=He(!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:H},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",G,He(!0))}}async function Ue(){return ce||(ce=Kt()),ce}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 jt(s,e=Be,t){return s.length===0?[]:de?x().generateEmbeddings(s,e,t):Pe(s,e,t)}async function Pe(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 m=0;m<o;m++){let p=m*u,y=p+u;i[r+m]=Array.from(a.data.slice(p,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 m=await n(u,{pooling:"mean",normalize:!0});i[r+o]=Array.from(m.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,H,v,Be,de,ce,ue,S=P(()=>{"use strict";M();ve();G=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",H=process.env.EMBEDDING_DTYPE??"fp32",v=null;Be=128,de=!1;ce=null;ue=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=Be,t){if(this.processing)return d.warn("Queue processing already in progress"),this.results;this.processing=!0;let i=this.queue.length;try{de?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 Pe(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 me from"node:os";M();import Tt from"better-sqlite3";import z from"path";import Re from"fs";import Rt from"crypto";M();import I from"fs";import $ from"path";import{fileURLToPath as mt}from"url";var R=d.child({module:"migrations"}),pt=mt(import.meta.url),Et=$.dirname(pt);function ht(){let s=Et;if(I.readdirSync(s).some(i=>i.match(/^\d{3}_.*\.sql$/)))return s;let t=$.resolve(s,"../../data/migrations");return I.existsSync(t)&&I.readdirSync(t).some(i=>i.match(/^\d{3}_.*\.sql$/))?t:s}function ft(s){s.exec(`
2
2
  CREATE TABLE IF NOT EXISTS schema_migrations (
3
3
  version INTEGER PRIMARY KEY,
4
4
  name TEXT NOT NULL,
5
5
  applied_at REAL DEFAULT (unixepoch())
6
6
  );
7
- `)}function gt(s){ft(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function _t(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 yt(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 Te(s){let e=gt(s),t=ht(),i=_t(t);if(e.size===0){yt(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 St from"os";var D=d.child({module:"db"});function oe(s){let e=St.homedir(),t=z.join(e,".mcp-liquid-shadow"),i=z.join(t,"dbs");Re.existsSync(i)||Re.mkdirSync(i,{recursive:!0});let n=Rt.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||oe(s);D.debug({repoPath:s,dbPath:t},"Initializing database");let i=new Tt(t);return i.pragma("journal_mode = WAL"),i.pragma("busy_timeout = 5000"),Te(i),Y.set(s,t),S.set(t,i),D.debug({repoPath:s,dbPath:t},"Database initialized successfully"),i}var S=new Map,Y=new Map;function F(s){let e=Y.get(s)||oe(s),t=S.get(e);if(t){if(t.open)return t;S.delete(e)}let i=Lt(s);return S.set(e,i),i}function Se(s){let e=Y.get(s)||oe(s),t=S.get(e);t&&(t.open&&(D.debug({repoPath:s,dbPath:e},"Closing database connection"),t.close()),S.delete(e)),Y.delete(s)}function Le(){for(let[s,e]of S.entries())try{e.open&&(D.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){D.error({dbPath:s,err:t},"Error closing database execution")}S.clear()}process.on("exit",()=>Le());var Ne=s=>{D.debug({signal:s},"Received termination signal, closing databases"),Le(),process.exit(0)};process.on("SIGINT",()=>Ne("SIGINT"));process.on("SIGTERM",()=>Ne("SIGTERM"));import At 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 Nt=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 Ot(s,e){if(!s)return!1;let t=s.trim();return!t||Nt.has(t.toLowerCase())||e.has(t)?!1:/^[A-Za-z_$][A-Za-z0-9_$.]*$/.test(t)}function It(s){return s.split(/[,|&]/).map(e=>e.trim()).filter(Boolean)}function Ct(s){let e=s.replace(/^[({\[]+/,"").replace(/[)}\]]+$/,"").replace(/^readonly\s+/,"").trim();return e&&e.match(/^([A-Za-z_$][A-Za-z0-9_$.]*)/)?.[1]||null}function Mt(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 Dt(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 ae(s,e){let t=[];for(let i of It(s)){let n=Ct(i);n&&Ot(n,e)&&t.push(n)}return t}function Oe(s){if(!s)return[];let e=s.replace(/\s+/g," ").trim();if(!e)return[];let t=Mt(e),i=Dt(t),n=[],r=new Set,c=(o,u,m)=>{let p=`${o}:${u}`;r.has(p)||(r.add(p),n.push({relationship:o,targetName:u,...m?{metadata:m}:{}}))},l=e.match(/\bextends\s+(.+?)(?=\bimplements\b|\{|=|$)/);if(l?.[1]){let o=ae(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=ae(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,m=null;for(;(m=u.exec(o))!==null;){let p=m[2]?.trim();if(!p)continue;let y=ae(p,i);for(let g of y)c("constrained_by",g,p)}}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=At.resolve(e,t),n=i.endsWith("/")?i:i+"/";return this.all(`
7
+ `)}function gt(s){ft(s);let e=s.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function _t(s){return I.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=I.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 yt(s,e,t){let i=$.join(e,"000_baseline.sql");if(!I.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=I.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 Te(s){let e=gt(s),t=ht(),i=_t(t);if(e.size===0){yt(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 Lt from"os";var A=d.child({module:"db"});function oe(s){let e=Lt.homedir(),t=z.join(e,".mcp-liquid-shadow"),i=z.join(t,"dbs");Re.existsSync(i)||Re.mkdirSync(i,{recursive:!0});let n=Rt.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 St(s,e){let t=e||oe(s);A.debug({repoPath:s,dbPath:t},"Initializing database");let i=new Tt(t);return i.pragma("journal_mode = WAL"),i.pragma("busy_timeout = 5000"),Te(i),K.set(s,t),L.set(t,i),A.debug({repoPath:s,dbPath:t},"Database initialized successfully"),i}var L=new Map,K=new Map;function F(s){let e=K.get(s)||oe(s),t=L.get(e);if(t){if(t.open)return t;L.delete(e)}let i=St(s);return L.set(e,i),i}function Le(s){let e=K.get(s)||oe(s),t=L.get(e);t&&(t.open&&(A.debug({repoPath:s,dbPath:e},"Closing database connection"),t.close()),L.delete(e)),K.delete(s)}function Se(){for(let[s,e]of L.entries())try{e.open&&(A.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){A.error({dbPath:s,err:t},"Error closing database execution")}L.clear()}process.on("exit",()=>Se());var Ne=s=>{A.debug({signal:s},"Received termination signal, closing databases"),Se(),process.exit(0)};process.on("SIGINT",()=>Ne("SIGINT"));process.on("SIGTERM",()=>Ne("SIGTERM"));import Dt 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 Nt=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 It(s,e){if(!s)return!1;let t=s.trim();return!t||Nt.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 Ct(s){let e=s.replace(/^[({\[]+/,"").replace(/[)}\]]+$/,"").replace(/^readonly\s+/,"").trim();return e&&e.match(/^([A-Za-z_$][A-Za-z0-9_$.]*)/)?.[1]||null}function Mt(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 At(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 ae(s,e){let t=[];for(let i of Ot(s)){let n=Ct(i);n&&It(n,e)&&t.push(n)}return t}function Ie(s){if(!s)return[];let e=s.replace(/\s+/g," ").trim();if(!e)return[];let t=Mt(e),i=At(t),n=[],r=new Set,c=(o,u,m)=>{let p=`${o}:${u}`;r.has(p)||(r.add(p),n.push({relationship:o,targetName:u,...m?{metadata:m}:{}}))},l=e.match(/\bextends\s+(.+?)(?=\bimplements\b|\{|=|$)/);if(l?.[1]){let o=ae(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=ae(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,m=null;for(;(m=u.exec(o))!==null;){let p=m[2]?.trim();if(!p)continue;let y=ae(p,i);for(let g of y)c("constrained_by",g,p)}}return n}var Y=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=Dt.resolve(e,t),n=i.endsWith("/")?i:i+"/";return this.all(`
8
8
  SELECT * FROM files
9
9
  WHERE (path LIKE ? OR path = ?)
10
10
  ORDER BY path ASC
@@ -90,7 +90,7 @@ var at=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var lt=(s,e)=>{f
90
90
  summary=excluded.summary,
91
91
  embedding=excluded.embedding,
92
92
  content_hash=excluded.content_hash
93
- `),Qe=this.db.transaction(C=>{for(let Xe of C){let{meta:_,exports:Ee,imports:he,configs:fe,events:ge,content:B,classification:Ze,summary:et,embedding:_e,contentHash:tt}=Xe;r.run(_.path),c.run(_.path),l.run(_.path),a.run(_.path),o.run(_.path),u.run(_.path);let it=tt??(B&&i?i(B):null);if(Je.run(_.path,_.mtime,Date.now(),Ze||"Unknown",et||"",_e?JSON.stringify(_e):null,it),Ee){let h=(k,nt,st)=>{for(let f of nt){let rt=f.embedding?JSON.stringify(f.embedding):null,be=m.run(k,f.name,f.kind,f.signature,f.doc||"",f.line,f.endLine||f.line,f.classification||"Other",f.capabilities||"[]",st,rt),ye=Number(be.lastInsertRowid);if(Number.isFinite(ye)){let ot=Oe(f.signature);for(let U of ot)U.targetName!==f.name&&N.run(k,ye,f.name,U.targetName,U.relationship,f.line,U.metadata||null)}f.members&&f.members.length>0&&h(k,f.members,be.lastInsertRowid)}};h(_.path,Ee,null)}if(he)for(let h of he){let k=h.resolved_path!==void 0?h.resolved_path:n?.(h.module,_.path,t)??"";p.run(_.path,h.module,h.name,k)}if(fe)for(let h of fe)y.run(_.path,h.key,h.value,h.kind);if(B!==void 0&&g.run(_.path,B),ge)for(let h of ge)T.run(_.path,h.type,h.name,h.direction,h.line,h.snippet)}}),pe=500;for(let C=0;C<e.length;C+=pe)Qe(e.slice(C,C+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 j=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(`
93
+ `),Qe=this.db.transaction(C=>{for(let Xe of C){let{meta:_,exports:Ee,imports:he,configs:fe,events:ge,content:B,classification:Ze,summary:et,embedding:_e,contentHash:tt}=Xe;r.run(_.path),c.run(_.path),l.run(_.path),a.run(_.path),o.run(_.path),u.run(_.path);let it=tt??(B&&i?i(B):null);if(Je.run(_.path,_.mtime,Date.now(),Ze||"Unknown",et||"",_e?JSON.stringify(_e):null,it),Ee){let h=(k,nt,st)=>{for(let f of nt){let rt=f.embedding?JSON.stringify(f.embedding):null,be=m.run(k,f.name,f.kind,f.signature,f.doc||"",f.line,f.endLine||f.line,f.classification||"Other",f.capabilities||"[]",st,rt),ye=Number(be.lastInsertRowid);if(Number.isFinite(ye)){let ot=Ie(f.signature);for(let U of ot)U.targetName!==f.name&&N.run(k,ye,f.name,U.targetName,U.relationship,f.line,U.metadata||null)}f.members&&f.members.length>0&&h(k,f.members,be.lastInsertRowid)}};h(_.path,Ee,null)}if(he)for(let h of he){let k=h.resolved_path!==void 0?h.resolved_path:n?.(h.module,_.path,t)??"";p.run(_.path,h.module,h.name,k)}if(fe)for(let h of fe)y.run(_.path,h.key,h.value,h.kind);if(B!==void 0&&g.run(_.path,B),ge)for(let h of ge)T.run(_.path,h.type,h.name,h.direction,h.line,h.snippet)}}),pe=500;for(let C=0;C<e.length;C+=pe)Qe(e.slice(C,C+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 j=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)}findTopLevelByNameGlobal(e){return this.all("SELECT * FROM exports WHERE name = ? AND parent_id IS NULL",e)}findAtLine(e,t){return this.get(`
94
94
  SELECT * FROM exports
95
95
  WHERE file_path = ? AND start_line <= ? AND end_line >= ?
96
96
  ORDER BY (end_line - start_line) ASC -- Get innermost symbol
@@ -187,7 +187,7 @@ var at=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var lt=(s,e)=>{f
187
187
  SELECT * FROM exports
188
188
  WHERE lower(name) LIKE ?
189
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 g of c){let T=g.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");a.push(`e.file_path NOT LIKE '${T}'`)}let o=a.length>0?`AND ${a.join(" AND ")}`:"",p=this.all(`
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.%'")),a.push("e.file_path NOT LIKE '%/dist/%'"),a.push("e.file_path NOT LIKE '%/build/%'"),a.push("e.file_path NOT LIKE '%/.next/%'"),a.push("e.file_path NOT LIKE '%/.nuxt/%'"),a.push("e.file_path NOT LIKE '%/.cache/%'"),a.push("e.file_path NOT LIKE '%/coverage/%'"),a.push("e.file_path NOT LIKE '%/node_modules/%'"),a.push("e.file_path NOT LIKE '%/storage/runtime/%'"),a.push("e.file_path NOT LIKE '%/compiled_templates/%'"),a.push("e.file_path NOT LIKE '%/compiled_classes/%'"),a.push("e.file_path NOT LIKE '%.generated.%'"),a.push("e.file_path NOT LIKE '%.gen.%'");for(let g of c){let T=g.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");a.push(`e.file_path NOT LIKE '${T}'`)}let o=a.length>0?`AND ${a.join(" AND ")}`:"",p=this.all(`
191
191
  SELECT e.name, e.kind, e.file_path, e.start_line
192
192
  FROM exports e
193
193
  WHERE e.kind IN (
@@ -208,7 +208,7 @@ var at=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var lt=(s,e)=>{f
208
208
  AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
209
209
  ORDER BY e.file_path, e.start_line
210
210
  LIMIT ?
211
- `,t*2).filter(g=>!this.isFrameworkEntrypointExport(g)).map(g=>{let{confidence:T,reason:N}=this.scoreDeadExportConfidence(g);return{...g,confidence:T,reason:N}}),y=p;return l==="high"?y=p.filter(g=>g.confidence==="high"):l==="medium"&&(y=p.filter(g=>g.confidence==="high"||g.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=`
211
+ `,t*2).filter(g=>!this.isFrameworkEntrypointExport(g)).map(g=>{let{confidence:T,reason:N}=this.scoreDeadExportConfidence(g);return{...g,confidence:T,reason:N}}),y=p;return l==="high"?y=p.filter(g=>g.confidence==="high"):l==="medium"&&(y=p.filter(g=>g.confidence==="high"||g.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("/app/exceptions/handler.php")||i.includes("/app/http/middleware/")||i.includes("/app/providers/")||i.includes("/app/console/commands/")||i.includes("/database/seeds/")||i.includes("/config/")&&i.endsWith(".php")||i.includes("/routes/")&&["loader","action","meta","headers"].includes(n))}getGravityMap(e=[],t){let i={},n=`
212
212
  SELECT ws.symbol_id, m.name as mission_name, m.status
213
213
  FROM working_set ws
214
214
  JOIN missions m ON ws.mission_id = m.id
@@ -263,7 +263,7 @@ var at=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var lt=(s,e)=>{f
263
263
  'inbound' AS direction
264
264
  FROM type_graph_edges
265
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 Ie=`
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
267
  WITH RECURSIVE dependency_chain AS (
268
268
  -- Base case: Direct dependents of the target symbol
269
269
  -- Meaning: Files that import the file where the symbol is defined
@@ -340,7 +340,7 @@ ORDER BY dc.depth, dc.consumer_path;
340
340
  SELECT COUNT(*) as count FROM imports
341
341
  WHERE resolved_path IN (${i})
342
342
  AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
343
- `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,i){return this.all(Ie,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
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
344
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
345
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
346
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
@@ -431,7 +431,7 @@ ORDER BY dc.depth, dc.consumer_path;
431
431
  SELECT linked_repo_path, linked_mission_id, relationship, direction
432
432
  FROM cross_repo_links
433
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(()=>(L(),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(()=>(L(),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(`
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=this.insert("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,"handoff",t.kind,i),r=[`[handoff:${t.kind}]`,...t.findings.map(c=>c.statement),...t.risks.map(c=>c.description),...t.gaps].filter(Boolean).join(" ");return Promise.resolve().then(()=>(S(),O)).then(({generateEmbedding:c})=>c(r)).then(c=>{c&&this.run("UPDATE mission_artifacts SET embedding = ? WHERE id = ?",JSON.stringify(c),n)}).catch(()=>{}),n}getHandoffs(e,t,i=20){let n=["type = 'handoff'"],r=[];e!==void 0&&(e===null?n.push("mission_id IS NULL"):(n.push("mission_id = ?"),r.push(e))),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){let{cosineSimilarity:i}=await Promise.resolve().then(()=>(S(),O)),n=["type = 'handoff'","embedding IS NOT NULL"],r=[];t?.missionId!==void 0&&(t.missionId===null?n.push("mission_id IS NULL"):(n.push("mission_id = ?"),r.push(t.missionId))),t?.kind&&(n.push("identifier = ?"),r.push(t.kind));let c=this.all(`SELECT * FROM mission_artifacts WHERE ${n.join(" AND ")}`,...r),l=[];for(let a of c)try{let o=JSON.parse(a.embedding),u=i(e,o);u>.3&&l.push({...a,similarity:u})}catch{}return l.sort((a,o)=>o.similarity-a.similarity).slice(0,t?.limit??5)}};M();var J=class s extends E{findByMission(e,t=50){return this.all(`
435
435
  SELECT
436
436
  id, mission_id, symbol_id, file_path, type, content, confidence,
437
437
  symbol_name, signature, commit_sha, is_crystallized, crystal_id,
@@ -452,7 +452,7 @@ ORDER BY dc.depth, dc.consumer_path;
452
452
  `,e)}create(e){let t=this.insert(`
453
453
  INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
454
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(()=>(L(),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(()=>(L(),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(`
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(),O)),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(),O)),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
456
  SELECT id, file_path, symbol_name, signature
457
457
  FROM intent_logs
458
458
  WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
@@ -484,24 +484,48 @@ ORDER BY dc.depth, dc.consumer_path;
484
484
  FROM intent_logs
485
485
  WHERE mission_id = ? AND is_crystallized = 0
486
486
  AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
487
+ ORDER BY created_at ASC`,e)}findCrystallizableByMission(e){return this.all(`SELECT
488
+ id, mission_id, symbol_id, file_path, type, content, confidence,
489
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
490
+ created_at
491
+ FROM intent_logs
492
+ WHERE mission_id = ?
493
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
487
494
  ORDER BY created_at ASC`,e)}findCrystalByMission(e){return this.get(`SELECT
488
495
  id, mission_id, symbol_id, file_path, type, content, confidence,
489
496
  symbol_name, signature, commit_sha, is_crystallized, crystal_id,
490
497
  created_at
491
498
  FROM intent_logs
492
499
  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
500
+ ORDER BY created_at DESC LIMIT 1`,e)}findCrystalBySymbol(e){return this.get(`SELECT
501
+ id, mission_id, symbol_id, file_path, type, content, confidence,
502
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
503
+ created_at
504
+ FROM intent_logs
505
+ WHERE symbol_id = ? AND mission_id IS NULL AND type = 'crystal'
506
+ ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t,i){return this.transaction(()=>{let n=i;return typeof n=="number"?this.run(`UPDATE intent_logs
507
+ SET content = ?, confidence = 1.0
508
+ WHERE id = ? AND mission_id = ? AND type = 'crystal'`,t,n,e):n=Number(this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
509
+ VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
495
510
  SET is_crystallized = 1, crystal_id = ?
496
511
  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
512
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),this.generateAndStoreEmbedding(n,{type:"crystal",content:t}).catch(r=>{d.debug({err:r,intentLogId:n},"Failed to refresh crystal embedding")}),n})}findRawBySymbol(e){return this.all(`SELECT * FROM intent_logs
498
513
  WHERE symbol_id = ? AND mission_id IS NULL AND is_crystallized = 0
499
514
  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
515
+ ORDER BY created_at ASC`,e)}findCrystallizableBySymbol(e){return this.all(`SELECT
516
+ id, mission_id, symbol_id, file_path, type, content, confidence,
517
+ symbol_name, signature, commit_sha, is_crystallized, crystal_id,
518
+ created_at
519
+ FROM intent_logs
520
+ WHERE symbol_id = ? AND mission_id IS NULL
521
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
522
+ ORDER BY created_at ASC`,e)}crystallizeBySymbol(e,t,i){return this.transaction(()=>{let n=i;return typeof n=="number"?this.run(`UPDATE intent_logs
523
+ SET content = ?, confidence = 1.0
524
+ WHERE id = ? AND symbol_id = ? AND mission_id IS NULL AND type = 'crystal'`,t,n,e):n=Number(this.insert(`INSERT INTO intent_logs (mission_id, symbol_id, type, content, confidence, is_crystallized, file_path, symbol_name, signature, commit_sha)
525
+ VALUES (NULL, ?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL)`,e,t)),this.run(`UPDATE intent_logs
502
526
  SET is_crystallized = 1, crystal_id = ?
503
527
  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
528
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),this.generateAndStoreEmbedding(n,{type:"crystal",content:t}).catch(r=>{d.debug({err:r,intentLogId:n},"Failed to refresh crystal embedding")}),n})}countByMissions(e){if(e.length===0)return{};let t=e.map(()=>"?").join(","),i=this.all(`SELECT mission_id, COUNT(*) as cnt
505
529
  FROM intent_logs
506
530
  WHERE mission_id IN (${t})
507
531
  AND type NOT IN ('system', 'adr', 'lapsed')
@@ -515,8 +539,8 @@ ORDER BY dc.depth, dc.consumer_path;
515
539
  FROM intent_logs
516
540
  WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
517
541
  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(()=>(L(),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(()=>(L(),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(`
542
+ 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(),O)),r=this.findWithEmbeddings(),c=[];for(let l of r)if(s.EMBEDDABLE_TYPES.has(l.type)&&l.type!=="crystal"&&l.mission_id!=null&&!(t&&!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)
543
+ 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(),O)),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
544
  SELECT file_path, key, value, kind
521
545
  FROM configs
522
546
  WHERE key LIKE ? OR value LIKE ?
@@ -588,11 +612,11 @@ ORDER BY dc.depth, dc.consumer_path;
588
612
  LEFT JOIN missions m ON m.id = fc.mission_id
589
613
  WHERE fc.file_path IN (${t})
590
614
  ORDER BY fc.file_path ASC
591
- `,...e)}};var ie=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=F(e),c=t.files?.database,a=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram||!t.claims;if(c===r&&r.open&&!a)return t;this.repositoryCache.delete(e)}let i=F(e),n={files:new K(i),exports:new j(i),imports:new q(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),claims:new te(i)};return this.repositoryCache.set(e,n),n}static closeInstance(e){this.repositoryCache.delete(e),Se(e)}static clearCache(e){this.repositoryCache.delete(e)}};L();var ze=new Set(["FunctionDeclaration","ClassDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","HTTP Route","Socket Event","Pub/Sub Topic","function","class","interface","type","enum"]),Ye={"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 Ke(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(`
615
+ `,...e)}};var ie=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=F(e),c=t.files?.database,a=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram||!t.claims;if(c===r&&r.open&&!a)return t;this.repositoryCache.delete(e)}let i=F(e),n={files:new Y(i),exports:new j(i),imports:new q(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),claims:new te(i)};return this.repositoryCache.set(e,n),n}static closeInstance(e){this.repositoryCache.delete(e),Le(e)}static clearCache(e){this.repositoryCache.delete(e)}};S();var ze=new Set(["FunctionDeclaration","ClassDeclaration","TsInterfaceDeclaration","TsTypeAliasDeclaration","TsEnumDeclaration","HTTP Route","Socket Event","Pub/Sub Topic","function","class","interface","type","enum"]),Ke={"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(`
592
616
  `)}function je(s){return s.map(()=>"?").join(",")}var Gt=me.constants.priority.PRIORITY_LOWEST??me.constants.priority.PRIORITY_LOW,ne=process.argv[2];ne||(process.stderr.write(`Ember: repoPath argument missing
593
- `),process.exit(1));try{me.setPriority(Gt)}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,re=[...ze],Ge=je(re),Vt=re.map(s=>`WHEN '${s.replace(/'/g,"''")}' THEN ${Ye[s]??2}`).join(" ").trim(),se=x({numWorkers:2}),b;async function Jt(){b=F(ne),w(b,{status:"running",pid:String(process.pid),started_at:String(Date.now()),repo_path:ne}),await se.initialize();let e=b.prepare(`SELECT COUNT(*) as c FROM exports WHERE embedding IS NULL AND kind IN (${Ge})`).get(...re).c,t=0;w(b,{progress:`0/${e}`});let i=b.prepare(`SELECT id, file_path, name, kind, signature, doc, start_line, end_line
617
+ `),process.exit(1));try{me.setPriority(Gt)}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,re=[...ze],Ge=je(re),Vt=re.map(s=>`WHEN '${s.replace(/'/g,"''")}' THEN ${Ke[s]??2}`).join(" ").trim(),se=x({numWorkers:2}),b;async function Jt(){b=F(ne),w(b,{status:"running",pid:String(process.pid),started_at:String(Date.now()),repo_path:ne}),await se.initialize();let e=b.prepare(`SELECT COUNT(*) as c FROM exports WHERE embedding IS NULL AND kind IN (${Ge})`).get(...re).c,t=0;w(b,{progress:`0/${e}`});let i=b.prepare(`SELECT id, file_path, name, kind, signature, doc, start_line, end_line
594
618
  FROM exports
595
619
  WHERE embedding IS NULL AND kind IN (${Ge})
596
620
  ORDER BY CASE kind ${Vt} END
597
- LIMIT ${qe}`),n=b.prepare("UPDATE exports SET embedding = ? WHERE id = ?");for(;;){let r=i.all(...re);if(r.length===0)break;let c=r.map(a=>Ke(a.file_path,a)),l=await se.generateEmbeddings(c,qe);b.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(b,{progress:`${t}/${e}`})}try{await ie.getInstance(ne).intentLogs.backfillEmbeddings(64)}catch{}w(b,{status:"done",progress:`${t}/${e}`}),await se.shutdown(),process.exit(0)}async function Ve(){try{b&&w(b,{status:"idle"}),await se.shutdown()}catch{}process.exit(0)}process.on("SIGTERM",()=>{Ve()});process.on("SIGINT",()=>{Ve()});Jt().catch(s=>{process.stderr.write(`Ember error: ${s instanceof Error?s.message:String(s)}
621
+ LIMIT ${qe}`),n=b.prepare("UPDATE exports SET embedding = ? WHERE id = ?");for(;;){let r=i.all(...re);if(r.length===0)break;let c=r.map(a=>Ye(a.file_path,a)),l=await se.generateEmbeddings(c,qe);b.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(b,{progress:`${t}/${e}`})}try{await ie.getInstance(ne).intentLogs.backfillEmbeddings(64)}catch{}w(b,{status:"done",progress:`${t}/${e}`}),await se.shutdown(),process.exit(0)}async function Ve(){try{b&&w(b,{status:"idle"}),await se.shutdown()}catch{}process.exit(0)}process.on("SIGTERM",()=>{Ve()});process.on("SIGINT",()=>{Ve()});Jt().catch(s=>{process.stderr.write(`Ember error: ${s instanceof Error?s.message:String(s)}
598
622
  `);try{b&&w(b,{status:"error"})}catch{}process.exit(1)});