@precisionutilityguild/liquid-shadow 1.0.10 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,96 +1,73 @@
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(`
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,A=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{existsSync as xt}from"node:fs";import{dirname as le,join as Ae,resolve as kt}from"node:path";import{fileURLToPath as wt}from"node:url";function Wt(){let s=Ce;for(;s!==le(s);){if(xt(Ae(s,"package.json")))return s;s=le(s)}return kt(Ce,"..","..")}function De(...s){return Ae(Wt(),...s)}var Ft,Ce,Me=P(()=>{"use strict";Ft=wt(import.meta.url),Ce=le(Ft)});import{existsSync as xe}from"node:fs";import{cpus as Ht}from"node:os";import{dirname as vt,join as ke}from"node:path";import{fileURLToPath as Ut}from"node:url";import{Worker as Bt}from"node:worker_threads";function Pt(){if(Fe.endsWith(".ts")){let e=ke(we,"worker.ts");if(xe(e))return e}let s=ke(we,"worker.js");return xe(s)?s:De("dist/logic/domain/embeddings/worker.js")}function x(s){return M||(M=new W(s)),M}async function We(){M&&(await M.shutdown(),M=null)}var Fe,we,W,M,He=P(()=>{"use strict";Me();A();Fe=Ut(import.meta.url),we=vt(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 Bt(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")}},M=null});var O={};lt(O,{EmbeddingPriorityQueue:()=>ue,EmbeddingWorkerPool:()=>W,cosineSimilarity:()=>jt,generateEmbedding:()=>Yt,generateEmbeddingsBatch:()=>qt,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 Kt(){d.info({model:X,dtype:v},"Loading embedding model...");let{pipeline:s}=await $t(),e=ve(!1);try{return await s("feature-extraction",X,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:X,dtype:v},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),await s("feature-extraction",X,ve(!0))}}async function Be(){return ce||(ce=Kt()),ce}async function Yt(s){try{let t=await(await Be())(s,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return d.error({err:e},"Failed to generate embedding"),null}}async function qt(s,e=Ue,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 Be();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 jt(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 X,v,H,Ue,de,ce,ue,S=P(()=>{"use strict";A();He();X=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",v=process.env.EMBEDDING_DTYPE??"fp32",H=null;Ue=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=Ue,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";A();import Tt from"better-sqlite3";import Rt from"crypto";import Re from"fs";import z from"path";A();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 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
- 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(`
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 D=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);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),K.set(s,t),L.set(t,i),D.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&&(D.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&&(D.debug({dbPath:s},"Closing database connection"),e.close())}catch(t){D.error({dbPath:s,err:t},"Error closing database execution")}L.clear()}process.on("exit",()=>Se());var Ne=s=>{D.debug({signal:s},"Received termination signal, closing databases"),Se(),process.exit(0)};process.on("SIGINT",()=>Ne("SIGINT"));process.on("SIGTERM",()=>Ne("SIGTERM"));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 Y=class extends E{claimFile(e,t){try{this.run(`
8
+ INSERT INTO file_claims (file_path, mission_id, claimed_at, updated_at)
9
+ VALUES (?, ?, unixepoch(), unixepoch())
10
+ `,e,t);let i=this.getClaim(e);if(!i)throw new Error(`Failed to hydrate claim after insert for file ${e}`);return{status:"claimed",claim:i}}catch{let i=this.getClaim(e);if(!i)throw new Error(`Failed to read existing claim for file ${e}`);return i.mission_id===t?(this.run("UPDATE file_claims SET updated_at = unixepoch() WHERE file_path = ?",e),{status:"already_claimed",claim:this.getClaim(e)??i}):{status:"conflict",claim:i}}}releaseFile(e,t){let i=this.getClaim(e);return i?t!==void 0&&i.mission_id!==t?{released:!1,reason:"not_owner",claim:i}:(this.run("DELETE FROM file_claims WHERE file_path = ?",e),{released:!0}):{released:!1,reason:"not_found"}}releaseAllForMission(e){return this.run("DELETE FROM file_claims WHERE mission_id = ?",e)}getClaim(e){return this.get(`
23
11
  SELECT
24
- files.*,
25
- bm25(content_fts, 0.2, 1.0) AS bm25_rank
12
+ fc.file_path,
13
+ fc.mission_id,
14
+ fc.claimed_at,
15
+ fc.updated_at,
16
+ m.name AS mission_name,
17
+ m.status AS mission_status,
18
+ m.git_branch AS mission_branch
19
+ FROM file_claims fc
20
+ LEFT JOIN missions m ON m.id = fc.mission_id
21
+ WHERE fc.file_path = ?
22
+ `,e)}getClaimsForMission(e){return this.all(`
23
+ SELECT
24
+ fc.file_path,
25
+ fc.mission_id,
26
+ fc.claimed_at,
27
+ fc.updated_at,
28
+ m.name AS mission_name,
29
+ m.status AS mission_status,
30
+ m.git_branch AS mission_branch
31
+ FROM file_claims fc
32
+ LEFT JOIN missions m ON m.id = fc.mission_id
33
+ WHERE fc.mission_id = ?
34
+ ORDER BY fc.file_path ASC
35
+ `,e)}listClaims(){return this.all(`
36
+ SELECT
37
+ fc.file_path,
38
+ fc.mission_id,
39
+ fc.claimed_at,
40
+ fc.updated_at,
41
+ m.name AS mission_name,
42
+ m.status AS mission_status,
43
+ m.git_branch AS mission_branch
44
+ FROM file_claims fc
45
+ LEFT JOIN missions m ON m.id = fc.mission_id
46
+ ORDER BY fc.updated_at DESC, fc.file_path ASC
47
+ `)}getClaimsByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`
48
+ SELECT
49
+ fc.file_path,
50
+ fc.mission_id,
51
+ fc.claimed_at,
52
+ fc.updated_at,
53
+ m.name AS mission_name,
54
+ m.status AS mission_status,
55
+ m.git_branch AS mission_branch
56
+ FROM file_claims fc
57
+ LEFT JOIN missions m ON m.id = fc.mission_id
58
+ WHERE fc.file_path IN (${t})
59
+ ORDER BY fc.file_path ASC
60
+ `,...e)}};var q=class extends E{findByKey(e,t=20){return this.all(`
61
+ SELECT file_path, key, value, kind
62
+ FROM configs
63
+ WHERE key LIKE ? OR value LIKE ?
64
+ LIMIT ?
65
+ `,`%${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 j=class extends E{search(e,t=10){return this.all(`
66
+ SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
26
67
  FROM content_fts
27
- JOIN files ON files.path = content_fts.file_path
28
68
  WHERE content_fts MATCH ?
29
- ORDER BY bm25_rank ASC
30
69
  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 m=o.status==="in-progress"||o.status==="verifying"?"Working Set":"Lineage Bleed";i[o.file_path].reasons.push(`${m}: ${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,m=u?.1:.2;i[o.file_path].score<5&&(i[o.file_path].score+=m);let p=u?`Lineage Intent: ${o.type}`:`Recent Intent: ${o.type}`;!i[o.file_path].reasons.includes(p)&&i[o.file_path].reasons.length<5&&i[o.file_path].reasons.push(p)}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 = ?"),m=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),p=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 (?, ?, ?, ?)"),g=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 (?, ?, ?, ?, ?, ?, ?)"),Je=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
- `),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(`
70
+ `,e,t)}};var G=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
71
  SELECT * FROM exports
95
72
  WHERE file_path = ? AND start_line <= ? AND end_line >= ?
96
73
  ORDER BY (end_line - start_line) ASC -- Get innermost symbol
@@ -263,7 +240,99 @@ var at=Object.defineProperty;var P=(s,e)=>()=>(s&&(e=s(s=0)),e);var lt=(s,e)=>{f
263
240
  'inbound' AS direction
264
241
  FROM type_graph_edges
265
242
  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=`
243
+ `,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}):[]}};import Mt from"path";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 At(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 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=At(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 V=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=Mt.resolve(e,t),n=i.endsWith("/")?i:i+"/";return this.all(`
244
+ SELECT * FROM files
245
+ WHERE (path LIKE ? OR path = ?)
246
+ ORDER BY path ASC
247
+ `,`${n}%`,i)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
248
+ SELECT files.*, files_fts.rank
249
+ FROM files_fts
250
+ JOIN files ON files.rowid = files_fts.rowid
251
+ WHERE files_fts MATCH ?
252
+ ORDER BY rank
253
+ LIMIT ?
254
+ `,e,t)}findByPathKeywords(e,t=10){let i=e.map(()=>"LOWER(path) LIKE ?").join(" OR ");return this.all(`
255
+ SELECT * FROM files
256
+ WHERE ${i}
257
+ LIMIT ?
258
+ `,...e.map(n=>`%${n}%`),t)}findContentFts(e,t=50){let i=this.buildContentFtsQuery(e);return i?this.all(`
259
+ SELECT
260
+ files.*,
261
+ bm25(content_fts, 0.2, 1.0) AS bm25_rank
262
+ FROM content_fts
263
+ JOIN files ON files.path = content_fts.file_path
264
+ WHERE content_fts MATCH ?
265
+ ORDER BY bm25_rank ASC
266
+ LIMIT ?
267
+ `,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(`
268
+ SELECT file_path
269
+ FROM content_fts
270
+ WHERE content_fts MATCH ?
271
+ 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')
272
+ AND file_path NOT LIKE '%/test/%'
273
+ AND file_path NOT LIKE '%.spec.%'
274
+ LIMIT ?
275
+ `,`"${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(`
276
+ SELECT
277
+ COUNT(*) as total,
278
+ SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
279
+ FROM files
280
+ `);return{total:e?.total||0,withSummary:e?.withSummary||0}}getGravityMap(e=[],t){let i={},n=`
281
+ SELECT ws.file_path, m.name as mission_name, m.status
282
+ FROM working_set ws
283
+ JOIN missions m ON ws.mission_id = m.id
284
+ WHERE (
285
+ (m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
286
+ OR m.id IN (${e.length>0?e.join(","):"-1"})
287
+ )
288
+ AND ws.file_path IS NOT NULL
289
+ `,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 m=o.status==="in-progress"||o.status==="verifying"?"Working Set":"Lineage Bleed";i[o.file_path].reasons.push(`${m}: ${o.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,a=this.all(`
290
+ SELECT file_path, type, mission_id
291
+ FROM intent_logs
292
+ WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
293
+ AND file_path IS NOT NULL
294
+ ORDER BY created_at DESC
295
+ LIMIT 100
296
+ `,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,m=u?.1:.2;i[o.file_path].score<5&&(i[o.file_path].score+=m);let p=u?`Lineage Intent: ${o.type}`:`Recent Intent: ${o.type}`;!i[o.file_path].reasons.includes(p)&&i[o.file_path].reasons.length<5&&i[o.file_path].reasons.push(p)}return i}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
297
+ SELECT
298
+ SUBSTR(path, LENGTH(?) + 2,
299
+ INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
300
+ ) as root,
301
+ COUNT(*) as total_files,
302
+ SUM(CASE
303
+ WHEN path LIKE '%.ts' OR path LIKE '%.tsx'
304
+ OR path LIKE '%.js' OR path LIKE '%.jsx'
305
+ OR path LIKE '%.mjs' OR path LIKE '%.cjs'
306
+ THEN 1 ELSE 0
307
+ END) as ts_files
308
+ FROM files
309
+ WHERE path LIKE ? || '/%/%'
310
+ GROUP BY root
311
+ ORDER BY total_files DESC
312
+ LIMIT ?
313
+ `,e,e,e,t)}hasFilesPattern(e){return!!this.get("SELECT 1 FROM files WHERE path LIKE ? LIMIT 1",e)}findPackageJsonChildren(e){return this.all(`
314
+ SELECT
315
+ path,
316
+ SUBSTR(path, LENGTH(?) + 2) as relPath
317
+ FROM files
318
+ WHERE path LIKE ? || '/%/package.json'
319
+ `,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 = ?"),m=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),p=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 (?, ?, ?, ?)"),g=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 (?, ?, ?, ?, ?, ?, ?)"),Je=this.db.prepare(`
320
+ INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
321
+ VALUES (?, ?, ?, ?, ?, ?, ?)
322
+ ON CONFLICT(path) DO UPDATE SET
323
+ mtime=excluded.mtime,
324
+ last_scanned_at=excluded.last_scanned_at,
325
+ classification=excluded.classification,
326
+ summary=excluded.summary,
327
+ embedding=excluded.embedding,
328
+ content_hash=excluded.content_hash
329
+ `),Qe=this.db.transaction(C=>{for(let Xe of C){let{meta:_,exports:Ee,imports:he,configs:fe,events:ge,content:U,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??(U&&i?i(U):null);if(Je.run(_.path,_.mtime,Date.now(),Ze||"Unknown",et||"",_e?JSON.stringify(_e):null,it),Ee){let h=(w,nt,st)=>{for(let f of nt){let rt=f.embedding?JSON.stringify(f.embedding):null,be=m.run(w,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 B of ot)B.targetName!==f.name&&N.run(w,ye,f.name,B.targetName,B.relationship,f.line,B.metadata||null)}f.members&&f.members.length>0&&h(w,f.members,be.lastInsertRowid)}};h(_.path,Ee,null)}if(he)for(let h of he){let w=h.resolved_path!==void 0?h.resolved_path:n?.(h.module,_.path,t)??"";p.run(_.path,h.module,h.name,w)}if(fe)for(let h of fe)y.run(_.path,h.key,h.value,h.kind);if(U!==void 0&&g.run(_.path,U),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 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(`
330
+ INSERT INTO hologram_snapshot (section, data, updated_at)
331
+ VALUES (?, ?, unixepoch())
332
+ ON CONFLICT(section) DO UPDATE SET
333
+ data = excluded.data,
334
+ updated_at = excluded.updated_at
335
+ `,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 Oe=`
267
336
  WITH RECURSIVE dependency_chain AS (
268
337
  -- Base case: Direct dependents of the target symbol
269
338
  -- Meaning: Files that import the file where the symbol is defined
@@ -314,7 +383,7 @@ SELECT DISTINCT
314
383
  dc.imported_symbols
315
384
  FROM dependency_chain dc
316
385
  ORDER BY dc.depth, dc.consumer_path;
317
- `;var q=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(`
386
+ `;var Q=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
387
  SELECT * FROM imports
319
388
  WHERE resolved_path IS NOT NULL AND resolved_path != ''
320
389
  `)}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(`
@@ -340,98 +409,7 @@ ORDER BY dc.depth, dc.consumer_path;
340
409
  SELECT COUNT(*) as count FROM imports
341
410
  WHERE resolved_path IN (${i})
342
411
  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,m=`${o} completed in last 7 days, ${u} in last 30 days.`;if(n!=null){let p=Math.round(n/60);m+=` Avg mission duration: ${p} min.`}return{completionRate:t,averageDurationSeconds:n,completedLast7Days:o,completedLast30Days:u,velocityNote:m}}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=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(`
412
+ `,...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}};A();var Z=class s extends E{findByMission(e,t=50){return this.all(`
435
413
  SELECT
436
414
  id, mission_id, symbol_id, file_path, type, content, confidence,
437
415
  symbol_name, signature, commit_sha, is_crystallized, crystal_id,
@@ -540,83 +518,140 @@ ORDER BY dc.depth, dc.consumer_path;
540
518
  WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
541
519
  AND created_at > ?
542
520
  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(`
544
- SELECT file_path, key, value, kind
545
- FROM configs
546
- WHERE key LIKE ? OR value LIKE ?
547
- LIMIT ?
548
- `,`%${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(`
549
- SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
550
- FROM content_fts
551
- WHERE content_fts MATCH ?
521
+ 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 ee=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
522
+ CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
523
+ 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
524
+ CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
525
+ created_at ASC`,this.all(t,...i)}findRecentCompleted(e=3){return this.all(`
526
+ SELECT * FROM missions
527
+ WHERE status = 'completed'
528
+ ORDER BY updated_at DESC, id DESC
552
529
  LIMIT ?
553
- `,e,t)}};var $e=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
+ `,e)}create(e){return this.insert(`
531
+ INSERT INTO missions (name, goal, strategy_graph, status, git_branch, commit_sha, parent_id, verification_context, outcome_contract)
532
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
533
+ `,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(`
534
+ SELECT file_path, type, source_priority, created_at
535
+ FROM (
536
+ SELECT
537
+ ws.file_path,
538
+ COALESCE(ws.type, 'file') AS type,
539
+ 0 AS source_priority,
540
+ ws.created_at
541
+ FROM working_set ws
542
+ WHERE ws.mission_id = ?
543
+
544
+ UNION ALL
545
+
546
+ SELECT
547
+ il.file_path,
548
+ 'intent' AS type,
549
+ 1 AS source_priority,
550
+ il.created_at
551
+ FROM intent_logs il
552
+ WHERE il.mission_id = ?
553
+ AND il.file_path IS NOT NULL
554
+
555
+ UNION ALL
556
+
557
+ SELECT
558
+ e.file_path,
559
+ 'symbol' AS type,
560
+ 2 AS source_priority,
561
+ il.created_at
562
+ FROM intent_logs il
563
+ JOIN exports e ON e.id = il.symbol_id
564
+ WHERE il.mission_id = ?
565
+ AND e.file_path IS NOT NULL
566
+ )
567
+ WHERE file_path IS NOT NULL
568
+ ORDER BY source_priority ASC, created_at DESC, file_path ASC
569
+ `,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(`
570
+ SELECT m.id, COUNT(il.id) as log_count
571
+ FROM missions m
572
+ LEFT JOIN intent_logs il ON il.mission_id = m.id
573
+ WHERE m.updated_at < ?
574
+ AND m.status != 'distilled'
575
+ GROUP BY m.id
576
+ HAVING log_count > ?
577
+ `,e,t).map(n=>n.id)}getStats(){let e=this.get(`
578
+ SELECT
579
+ COUNT(*) as total,
580
+ SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
581
+ SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
582
+ FROM missions
583
+ `);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(`
584
+ SELECT AVG(updated_at - created_at) AS avg_duration
585
+ FROM missions
586
+ WHERE status = 'completed' AND updated_at > created_at
587
+ `),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,m=`${o} completed in last 7 days, ${u} in last 30 days.`;if(n!=null){let p=Math.round(n/60);m+=` Avg mission duration: ${p} min.`}return{completionRate:t,averageDurationSeconds:n,completedLast7Days:o,completedLast30Days:u,velocityNote:m}}suspendByBranch(e){return this.run(`UPDATE missions
588
+ SET status = 'suspended', updated_at = unixepoch()
589
+ WHERE git_branch = ? AND status IN ('in-progress', 'verifying')`,e)}resumeByBranch(e){return this.run(`UPDATE missions
590
+ SET status = 'in-progress', updated_at = unixepoch()
591
+ 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
592
+ WHERE status IN ('in-progress', 'planned', 'verifying', 'suspended')
593
+ 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){return this.ensureCrossRepoLinksSchema(),this.run(`
594
+ INSERT OR IGNORE INTO cross_repo_links (mission_id, linked_repo_path, linked_mission_id, relationship, direction)
595
+ VALUES (?, ?, ?, ?, ?)
596
+ `,e,t,i,n,r)}getLink(e,t,i,n){return this.ensureCrossRepoLinksSchema(),this.get(`
597
+ SELECT relationship, direction
598
+ FROM cross_repo_links
599
+ WHERE mission_id = ?
600
+ AND linked_repo_path = ?
601
+ AND linked_mission_id = ?
602
+ AND direction = ?
603
+ LIMIT 1
604
+ `,e,t,i,n)}upsertLink(e,t,i,n,r){return this.ensureCrossRepoLinksSchema(),this.run(`
605
+ INSERT INTO cross_repo_links (
606
+ mission_id,
607
+ linked_repo_path,
608
+ linked_mission_id,
609
+ relationship,
610
+ direction
611
+ )
612
+ VALUES (?, ?, ?, ?, ?)
613
+ ON CONFLICT(mission_id, linked_repo_path, linked_mission_id, direction)
614
+ DO UPDATE SET relationship = excluded.relationship
615
+ `,e,t,i,n,r)}hasLink(e,t,i,n){return this.ensureCrossRepoLinksSchema(),!!this.get(`
616
+ SELECT id
617
+ FROM cross_repo_links
618
+ WHERE mission_id = ?
619
+ AND linked_repo_path = ?
620
+ AND linked_mission_id = ?
621
+ AND direction = ?
622
+ LIMIT 1
623
+ `,e,t,i,n)}deleteLink(e,t,i,n){return this.ensureCrossRepoLinksSchema(),this.run(`
624
+ DELETE FROM cross_repo_links
625
+ WHERE mission_id = ?
626
+ AND linked_repo_path = ?
627
+ AND linked_mission_id = ?
628
+ AND direction = ?
629
+ `,e,t,i,n)}ensureCrossRepoLinksSchema(){this.db.exec(`
630
+ CREATE TABLE IF NOT EXISTS cross_repo_links (
631
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
632
+ mission_id INTEGER NOT NULL,
633
+ linked_repo_path TEXT NOT NULL,
634
+ linked_mission_id INTEGER NOT NULL,
635
+ relationship TEXT,
636
+ direction TEXT,
637
+ created_at REAL DEFAULT (unixepoch()),
638
+ FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
639
+ );
640
+ CREATE INDEX IF NOT EXISTS idx_cross_repo_mission ON cross_repo_links(mission_id);
641
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_cross_repo_unique
642
+ ON cross_repo_links(mission_id, linked_repo_path, linked_mission_id, direction);
643
+ `)}getLinks(e){try{return this.all(`
644
+ SELECT linked_repo_path, linked_mission_id, relationship, direction
645
+ FROM cross_repo_links
646
+ WHERE mission_id = ?
647
+ `,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)}};var $e=500,te=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
554
648
  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)<=$e||this.run(`DELETE FROM search_history WHERE id NOT IN (
555
649
  SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
556
- )`,$e)}};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(`
557
- INSERT INTO hologram_snapshot (section, data, updated_at)
558
- VALUES (?, ?, unixepoch())
559
- ON CONFLICT(section) DO UPDATE SET
560
- data = excluded.data,
561
- updated_at = excluded.updated_at
562
- `,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 extends E{claimFile(e,t){try{this.run(`
563
- INSERT INTO file_claims (file_path, mission_id, claimed_at, updated_at)
564
- VALUES (?, ?, unixepoch(), unixepoch())
565
- `,e,t);let i=this.getClaim(e);if(!i)throw new Error(`Failed to hydrate claim after insert for file ${e}`);return{status:"claimed",claim:i}}catch{let i=this.getClaim(e);if(!i)throw new Error(`Failed to read existing claim for file ${e}`);return i.mission_id===t?(this.run("UPDATE file_claims SET updated_at = unixepoch() WHERE file_path = ?",e),{status:"already_claimed",claim:this.getClaim(e)??i}):{status:"conflict",claim:i}}}releaseFile(e,t){let i=this.getClaim(e);return i?t!==void 0&&i.mission_id!==t?{released:!1,reason:"not_owner",claim:i}:(this.run("DELETE FROM file_claims WHERE file_path = ?",e),{released:!0}):{released:!1,reason:"not_found"}}releaseAllForMission(e){return this.run("DELETE FROM file_claims WHERE mission_id = ?",e)}getClaim(e){return this.get(`
566
- SELECT
567
- fc.file_path,
568
- fc.mission_id,
569
- fc.claimed_at,
570
- fc.updated_at,
571
- m.name AS mission_name,
572
- m.status AS mission_status,
573
- m.git_branch AS mission_branch
574
- FROM file_claims fc
575
- LEFT JOIN missions m ON m.id = fc.mission_id
576
- WHERE fc.file_path = ?
577
- `,e)}getClaimsForMission(e){return this.all(`
578
- SELECT
579
- fc.file_path,
580
- fc.mission_id,
581
- fc.claimed_at,
582
- fc.updated_at,
583
- m.name AS mission_name,
584
- m.status AS mission_status,
585
- m.git_branch AS mission_branch
586
- FROM file_claims fc
587
- LEFT JOIN missions m ON m.id = fc.mission_id
588
- WHERE fc.mission_id = ?
589
- ORDER BY fc.file_path ASC
590
- `,e)}listClaims(){return this.all(`
591
- SELECT
592
- fc.file_path,
593
- fc.mission_id,
594
- fc.claimed_at,
595
- fc.updated_at,
596
- m.name AS mission_name,
597
- m.status AS mission_status,
598
- m.git_branch AS mission_branch
599
- FROM file_claims fc
600
- LEFT JOIN missions m ON m.id = fc.mission_id
601
- ORDER BY fc.updated_at DESC, fc.file_path ASC
602
- `)}getClaimsByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`
603
- SELECT
604
- fc.file_path,
605
- fc.mission_id,
606
- fc.claimed_at,
607
- fc.updated_at,
608
- m.name AS mission_name,
609
- m.status AS mission_status,
610
- m.git_branch AS mission_branch
611
- FROM file_claims fc
612
- LEFT JOIN missions m ON m.id = fc.mission_id
613
- WHERE fc.file_path IN (${t})
614
- ORDER BY fc.file_path ASC
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(`
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
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
650
+ )`,$e)}};var ie=class s{static repositoryCache=new Map;static getInstance(e){let t=s.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;s.repositoryCache.delete(e)}let i=F(e),n={files:new V(i),exports:new G(i),imports:new Q(i),missions:new ee(i),intentLogs:new Z(i),configs:new q(i),content:new j(i),searchHistory:new te(i),hologram:new J(i),claims:new Y(i)};return s.repositoryCache.set(e,n),n}static closeInstance(e){s.repositoryCache.delete(e),Le(e)}static clearCache(e){s.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(`
651
+ `)}function qe(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
652
+ `),process.exit(1));try{me.setPriority(Gt)}catch{}function k(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 je=100,re=[...ze],Ge=qe(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),k(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;k(b,{progress:`0/${e}`});let i=b.prepare(`SELECT id, file_path, name, kind, signature, doc, start_line, end_line
618
653
  FROM exports
619
654
  WHERE embedding IS NULL AND kind IN (${Ge})
620
655
  ORDER BY CASE kind ${Vt} END
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)}
622
- `);try{b&&w(b,{status:"error"})}catch{}process.exit(1)});
656
+ LIMIT ${je}`),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,je);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,k(b,{progress:`${t}/${e}`})}try{await ie.getInstance(ne).intentLogs.backfillEmbeddings(64)}catch{}k(b,{status:"done",progress:`${t}/${e}`}),await se.shutdown(),process.exit(0)}async function Ve(){try{b&&k(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)}
657
+ `);try{b&&k(b,{status:"error"})}catch{}process.exit(1)});