@precisionutilityguild/liquid-shadow 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It from"path";var ke=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],xt=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"];var vi={FILTERED_QUERY_LIMIT_MULTIPLIER:3,SCORE_BASE:1e3,EXACT_MATCH_BONUS:500,RECENT_FILE_BOOST:80,OLDER_FILE_BOOST:30,RECENT_FILE_THRESHOLD_DAYS:7,OLDER_FILE_THRESHOLD_DAYS:30,FUZZY_MATCH_LIMIT:30,ENABLE_LEXICAL_SCORING:process.env.ENABLE_LEXICAL_SCORING!=="false",LEXICAL_WEIGHT:parseFloat(process.env.LEXICAL_WEIGHT??String(.4)),GRAVITY_STRUCTURAL_WEIGHT:.5};var Ce={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function it(i,e=[]){let t=kn(),n=It.join(i,".gitignore");return nt.existsSync(n)&&t.add(nt.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await Ln(xt,{cwd:i,absolute:!0,ignore:ke})).filter(o=>{let c=It.relative(i,o);return!t.ignores(c)}).map(o=>({path:o,mtime:nt.statSync(o).mtimeMs}))}import $n from"@swc/core";import at from"fs";function Lt(i){let e=i.split(`
2
- `),t=[],n=0;for(let s of e)t.push(n),n+=s.length+1;return t}function O(i,e){for(let t=0;t<e.length;t++)if(e[t+1]>i||t===e.length-1)return t+1;return 1}function A(i,e){return e.slice(0,i).toString("utf8").length}function kt(i,e,t){let n=i.start-e,s=i.end-e;return n<0||s>t.length?"":t.slice(n,s).toString("utf8")}function Ct(i){let e=[],t=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=t.exec(i))!==null;)e.push({start:n.index,end:n.index+n[0].length,text:n[0]});return e}function G(i,e,t){for(let n of e){if(n.start===i)return n.text;if(n.start>i&&n.start<i+50){let s=t.substring(i,n.start);if(/^\s*$/.test(s))return n.text}if(n.end<=i&&n.end>i-50){let s=t.substring(n.end,i);if(/^\s*$/.test(s))return n.text}}return""}function vt(i){if(!i)return"";let t=i.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
3
- `)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function ve(i,e,t){let n=i.toLowerCase(),s=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||s.startsWith("use")?"Hook":n.includes("models/")||s.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||s.endsWith("service")||s.endsWith("controller")||s.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||s.endsWith("repository")||s.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function ge(i){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(i)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(i)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(i)||/\.query\s*\(|\.execute\s*\(/i.test(i)&&/db|database|client|pool/i.test(i))&&e.push("Database"),(/\bfs\./i.test(i)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(i)||/import\s+.*\bfs\b/.test(i))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(i)||/\bdocument\.cookie\b/.test(i))&&e.push("Browser Storage"),e}function Y(i,e){if(!i)return"";let t=i.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,s=0,r=t.length;for(let o=0;o<t.length;o++){let c=t[o];if(c==="(")n++;else if(c===")")n--;else if(c==="<")s++;else if(c===">")s--;else if(c==="{"){if(n===0&&s===0){r=o;break}}else if(c==="; "&&n===0&&s===0){r=o;break}else if(c==="="&&t[o+1]===">"&&n===0&&s===0){r=o+2;break}}return t.substring(0,r).trim()}function Nt(i){let e=[];for(let t of i)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join("","")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function Dt(i,e,t,n,s,r,o,c){let l=[];for(let a of i){if(a.type==="ExportDeclaration"){let p=a.declaration,d=p.type,m="";d==="VariableDeclaration"?m=p.declarations.map(h=>h.id.value).join("",""):m=p.id?.value||p.identifier?.value||"anonymous";let f=A(a.span.start-e,t),g=A(a.span.end-e,t),E=G(f,r,n),y=c(a.span),u=[];if(a.type==="ExportDeclaration"&&(d==="ClassDeclaration"||d==="ClassExpression")){let h=p.body||[];for(let b of h)if(b.type==="ClassMethod"||b.type==="ClassProperty"){let M=b.key.value;if(!M)continue;let C=A(b.span.start-e,t),I=A(b.span.end-e,t),v=c(b.span),$=G(C,r,n);u.push({name:M,kind:b.type,signature:Y(v,b.type),line:O(C,s),endLine:O(I,s),doc:$,classification:b.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(d==="FunctionDeclaration"&&p.body?.type==="BlockStatement")u=st(p.body.stmts,e,t,n,s,r,c);else if(d==="VariableDeclaration"){for(let h of p.declarations)if(h.init&&(h.init.type==="ArrowFunctionExpression"||h.init.type==="FunctionExpression")&&h.init.body?.type==="BlockStatement"){u=st(h.init.body.stmts,e,t,n,s,r,c);break}}l.push({name:m,kind:d,signature:Y(y,d),line:O(f,s),endLine:O(g,s),doc:E,classification:ve(o,m,d),capabilities:JSON.stringify(ge(y)),members:u})}if(a.type==="ExportNamedDeclaration"){for(let p of a.specifiers)if(p.type==="ExportSpecifier"){let d=A(a.span.start-e,t),m=A(a.span.end-e,t),f=G(d,r,n);l.push({name:p.exported?.value||p.orig.value,kind:"ExportSpecifier",signature:`export { ${p.orig.value} }`,line:O(d,s),endLine:O(m,s),doc:f,classification:"Export mapping",capabilities:"[]"})}}if(a.type==="ExportDefaultDeclaration"){let p=A(a.span.start-e,t),d=A(a.span.end-e,t),m=G(p,r,n),f=c(a.span),g=[];if(a.decl.type==="ClassExpression"||a.decl.type==="ClassDeclaration"){let E=a.decl.body||[];for(let y of E)if(y.type==="ClassMethod"||y.type==="ClassProperty"){let u=y.key.value;if(!u)continue;let h=A(y.span.start-e,t),b=A(y.span.end-e,t),M=c(y.span),C=G(h,r,n);g.push({name:u,kind:y.type,signature:Y(M,y.type),line:O(h,s),endLine:O(b,s),doc:C,classification:y.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(a.decl.type==="FunctionExpression"||a.decl.type==="FunctionDeclaration"||a.decl.type==="ArrowFunctionExpression")&&a.decl.body?.type==="BlockStatement"&&(g=st(a.decl.body.stmts,e,t,n,s,r,c));l.push({name:"default",kind:"DefaultExport",signature:Y(f,"DefaultExport"),line:O(p,s),endLine:O(d,s),doc:m,classification:"Default Export",capabilities:JSON.stringify(ge(f)),members:g})}if(a.type==="ExportAllDeclaration"){let p=A(a.span.start-e,t),d=A(a.span.end-e,t),m=a.source.value,f=G(p,r,n);l.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${m}"`,line:O(p,s),endLine:O(d,s),doc:f,classification:"Re-export",capabilities:"[]"})}}return l}function st(i,e,t,n,s,r,o){let c=[];for(let l of i){if(l.type==="VariableDeclaration")for(let a of l.declarations){let p=[],d=m=>{if(m.type==="Identifier")p.push({name:m.value,span:m.span});else if(m.type==="ArrayPattern")for(let f of m.elements)f&&d(f);else if(m.type==="ObjectPattern")for(let f of m.properties)f.type==="AssignmentPatternProperty"?p.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&d(f.value)};d(a.id);for(let m of p){let f=A(m.span.start-e,t),g=A(m.span.end-e,t),E=o(m.span),y=G(f,r,n);c.push({name:m.name,kind:"VariableDeclaration",signature:Y(E,"VariableDeclaration"),line:O(f,s),endLine:O(g,s),doc:y,classification:"Internal Variable",capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let a=l.identifier?.value||l.ident?.value||"anonymous",p=A(l.span.start-e,t),d=A(l.span.end-e,t),m=o(l.span),f=G(p,r,n);c.push({name:a,kind:"FunctionDeclaration",signature:Y(m,"FunctionDeclaration"),line:O(p,s),endLine:O(d,s),doc:f,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let a of l.argument.properties){let p="",d=a.span||a.key?.span||a.ident?.span;if(a.type==="KeyValueProperty"){let m=a.key;p=m?.value||m?.raw||(m?.type==="Identifier"?m.value:"")}else a.type==="MethodProperty"?p=a.key?.value||a.key?.raw||"":a.type==="ShorthandProperty"?p=a.ident?.value||"":a.type==="Identifier"&&(p=a.value||"");if(p&&d){let m=A(d.start-e,t),f=A(d.end-e,t),g=o(d),E=G(m,r,n);c.push({name:p,kind:"ReturnProperty",signature:Y(g,"ReturnProperty"),line:O(m,s),endLine:O(f,s),doc:E,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let a=l.expression;if(a.callee.type==="MemberExpression"&&(a.callee.property?.value==="on"||a.callee.property?.value==="once")){let p=a.arguments[0]?.expression?.value,d=a.arguments[1]?.expression;if(p&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let m=A(d.span.start-e,t),f=A(d.span.end-e,t),g=o(d.span);c.push({name:`on:${p}`,kind:d.type,signature:Y(g,d.type),line:O(m,s),endLine:O(f,s),doc:"",classification:"Event Handler",capabilities:"[]"})}}}}return c}function Mt(i,e,t,n,s){let r=[];function o(c){if(!(!c||typeof c!="object")){if(c.type==="CallExpression"){let l=Cn(c);if(l){let a=A(c.span.start-e,t);r.push({...l,line:O(a,n),snippet:s(c.span)})}}for(let l of Object.keys(c)){if(l==="span")continue;let a=c[l];Array.isArray(a)?a.forEach(o):typeof a=="object"&&o(a)}}}return i.forEach(o),r}function Cn(i){let{callee:e,arguments:t}=i;if(!t||t.length===0)return null;if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};let s=["get","post","put","delete","patch"];if(s.includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value;if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}if(s.includes(n)&&t[0].expression.type==="StringLiteral"&&e.object.type==="Identifier"&&["axios","http","request"].includes(e.object.value))return{type:"api_route",name:t[0].expression.value,direction:"produce"}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function ye(i){let{classification:e,capabilities:t,exports:n,fileName:s}=i,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(g=>r[g]).filter(Boolean).join(" and "),l={Component:(g,E)=>{let y=E.find(h=>h.kind==="FunctionDeclaration"||h.kind==="ClassDeclaration")?.name,u=y?`React component: ${y}`:"React UI component";return g?`${u} with ${g}`:u},Hook:(g,E)=>{let y=E.find(h=>h.name.startsWith("use"))?.name,u=y?`Custom React hook: ${y}`:"Custom React hook";return g?`${u} for ${g}`:u},Service:(g,E)=>{let u=`Service layer: ${E[0]?.name||"Service"}`;return g?`${u} handling ${g}`:u},Repository:(g,E)=>`Data repository: ${E[0]?.name||"Repository"} for ${g||"data access"}`,"Type Definition":(g,E)=>`Type definitions: ${E.slice(0,3).map(u=>u.name).join("")}${E.length>3?"...":""}`,Model:(g,E)=>`Data model: ${E[0]?.name||"Model"}`,"HTTP Route":(g,E)=>{let y=E.filter(u=>u.classification==="Service Boundary");return y.length>0?`API endpoints: ${y.slice(0,3).map(u=>u.name).join("")}`:"API route handler"},"Micro IR (PHP)":(g,E)=>{let y=E.some(h=>h.classification==="Service Boundary"),u=E.find(h=>h.kind==="ClassDeclaration")?.name;return y?"PHP controller with API routes":u?`PHP class: ${u}`:"PHP module"},"Micro IR (Python)":(g,E)=>{let y=E.some(h=>h.classification==="Service Boundary"),u=E.find(h=>h.kind==="ClassDeclaration")?.name;return y?"Python API handler with routes":u?`Python class: ${u}`:"Python module"},"Micro IR (Go/TS) ":(g,E)=>{let y=E.some(h=>h.kind==="TypeDeclaration"),u=E.filter(h=>h.kind==="FunctionDeclaration");return y&&u.length>0?`Go package: types and ${u.length} function(s)`:y?"Go package: type definitions":u.length>0?`Go package: ${u[0].name} and ${u.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(g,E)=>{let y=E.find(b=>b.kind==="TraitDeclaration")?.name,u=E.find(b=>b.kind==="StructDeclaration")?.name,h=E.filter(b=>b.kind==="FunctionDeclaration");return y?g.includes("Rust trait")?`Rust module: trait ${y}`:`Rust module: ${y}`:u?`Rust module: struct ${u}`:h.length>0?`Rust module: ${h.length} function(s)`:"Rust module"}}[e];if(l)return l(o,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let a=n.filter(g=>g.kind==="FunctionDeclaration"),p=n.filter(g=>g.kind==="ClassDeclaration"),d=n.filter(g=>g.kind==="TsInterfaceDeclaration"||g.kind==="TsTypeAliasDeclaration"),m=[];if(p.length>0&&m.push(`Class: ${p[0].name}`),a.length>0){let g=a.slice(0,2).map(E=>E.name).join("");m.push(`Functions: ${g}`)}d.length>0&&m.push(`Types: ${d.length}`);let f=m.length>0?m.join(" | "):`Module with ${n.length} export(s)`;return o?`${f} \u2014 ${o}`:f}function Ot(i){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&W(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&W(n,e);for(let s in n){if(s==="span"||s==="comments"||s==="interpreter")continue;let r=n[s];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return i.forEach(n=>t(n)),Array.from(e)}function W(i,e){if(i){if(i.type==="TsTypeAnnotation"){W(i.typeAnnotation,e);return}i.type==="TsTypeReference"&&(i.typeName?.type==="Identifier"&&e.add(i.typeName.value),i.typeName?.type==="TsQualifiedName"&&At(i.typeName,e),i.typeParams&&W(i.typeParams,e)),i.type==="TsArrayType"&&W(i.elementType,e),i.type==="TsUnionType"&&i.types?.forEach(t=>W(t,e)),i.type==="TsIntersectionType"&&i.types?.forEach(t=>W(t,e)),i.type==="TsTupleType"&&i.elemTypes?.forEach(t=>W(t.ty,e)),(i.type==="TsFunctionType"||i.type==="TsConstructorType")&&(i.params?.forEach(t=>W(t.typeAnnotation,e)),i.typeAnnotation&&W(i.typeAnnotation,e)),i.type==="TsTypeParameterDeclaration"&&i.params?.forEach(t=>{t.constraint&&W(t.constraint,e),t.default&&W(t.default,e)}),i.type==="TsTypeParameterInstantiation"&&i.params?.forEach(t=>W(t,e)),i.type==="TsMappedType"&&i.typeAnnotation&&W(i.typeAnnotation,e),i.type==="TsIndexedAccessType"&&(W(i.objectType,e),W(i.indexType,e)),i.type==="TsConditionalType"&&(W(i.checkType,e),W(i.extendsType,e),W(i.trueType,e),W(i.falseType,e)),i.type==="TsTypeLiteral"&&i.members?.forEach(t=>{t.typeAnnotation&&W(t.typeAnnotation,e)})}}function At(i,e){i.type==="TsQualifiedName"?(i.left&&At(i.left,e),i.right?.value&&e.add(i.right.value)):i.type==="Identifier"&&e.add(i.value)}import $t from"path";import ot from"path";import Pt from"path";import Wn from"fs";import{fileURLToPath as Pn}from"url";import*as ae from"web-tree-sitter";import vn from"pino";var Nn={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},Dn=vn({level:process.env.LOG_LEVEL||"info",base:{service:"liquid-shadow"},formatters:{level(i,e){return{level:i,severity:Nn[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),_=Dn;import{fileURLToPath as Mn}from"node:url";import{dirname as rt,join as Ft,resolve as On}from"node:path";import{existsSync as An}from"node:fs";var wn=Mn(import.meta.url),wt=rt(wn);function Fn(){let i=wt;for(;i!==rt(i);){if(An(Ft(i,"package.json")))return i;i=rt(i)}return On(wt,"..","..")}function Ne(...i){return Ft(Fn(),...i)}var as=Pt.dirname(Pn(import.meta.url)),Wt=_.child({module:"parser:tree-sitter"}),De=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=ae.Parser||ae;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=Ne("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!Wn.existsSync(t))return Wt.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await ae.Language.load(t);return this.languages.set(e,n),n}catch(n){return Wt.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
1
+ var Bn=Object.defineProperty;var Ae=(i,e)=>()=>(i&&(e=i(i=0)),e);var jn=(i,e)=>{for(var t in e)Bn(i,t,{get:e[t],enumerable:!0})};import Kn from"pino";var Jn,Yn,E,j=Ae(()=>{"use strict";Jn={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},Yn=Kn({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(i,e){return{level:i,severity:Jn[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),E=Yn});import{fileURLToPath as Qn}from"node:url";import{dirname as ft,join as Kt,resolve as Vn}from"node:path";import{existsSync as Xn}from"node:fs";function ei(){let i=Gt;for(;i!==ft(i);){if(Xn(Kt(i,"package.json")))return i;i=ft(i)}return Vn(Gt,"..","..")}function fe(...i){return Kt(ei(),...i)}var Zn,Gt,$e=Ae(()=>{"use strict";Zn=Qn(import.meta.url),Gt=ft(Zn)});import{Worker as wi}from"node:worker_threads";import{cpus as Oi}from"node:os";import{fileURLToPath as Ai}from"node:url";import{dirname as Fi,join as Tn}from"node:path";import{existsSync as Sn}from"node:fs";function Pi(){if(xn.endsWith(".ts")){let e=Tn(kn,"worker.ts");if(Sn(e))return e}let i=Tn(kn,"worker.js");return Sn(i)?i:fe("dist/logic/domain/embeddings/worker.js")}function de(i){return be||(be=new _e(i)),be}async function kt(){be&&(await be.shutdown(),be=null)}var xn,kn,_e,be,In=Ae(()=>{"use strict";j();$e();xn=Ai(import.meta.url),kn=Fi(xn);_e=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(4,Oi().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{E.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((n,s)=>{e=setTimeout(()=>s(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,E.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,E.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=Pi();E.debug({workerPath:e},"Resolved worker path");let t=[];for(let n=0;n<this.numWorkers;n++)n>0&&await new Promise(s=>setTimeout(s,25)),t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,s)=>{let r=setTimeout(()=>{s(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new wi(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),l={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){E.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(l),E.debug({workerIndex:t},"Worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(l,c.id,c.embeddings||[]):c.type==="error"&&c.id&&this.handleTaskError(l,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),E.error({err:c,workerIndex:t},"Worker error"),l.currentTaskId&&this.handleTaskError(l,l.currentTaskId,c),!this.initialized){s(c);return}let a=this.workers.indexOf(l);a!==-1&&this.workers.splice(a,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(u=>{E.error({err:u},"Failed to replace crashed worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&E.warn({workerIndex:t,code:c},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=128,n){if(this.initialized||await this.initialize(),e.length===0)return[];let s=[];for(let a=0;a<e.length;a+=t)s.push(e.slice(a,a+t));let r=new Array(s.length),o=0,l=s.map((a,u)=>new Promise((p,m)=>{let f={id:`task_${++this.taskIdCounter}`,texts:a,resolve:g=>{if(r[u]=g,o++,n){let b=Math.min(o*t,e.length);n(b,e.length)}p()},reject:g=>{if(r[u]=new Array(a.length).fill(null),o++,E.warn({err:g,chunkIndex:u},"Chunk embedding failed"),n){let b=Math.min(o*t,e.length);n(b,e.length)}p()}};this.taskQueue.push(f),this.processQueue()}));await Promise.all(l);let c=[];for(let a of r)c.push(...a);return E.info({total:e.length,successful:c.filter(a=>a!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),c}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}E.info({numWorkers:this.workers.length},"Shutting down embedding worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,E.info("Embedding worker pool shutdown complete")}},be=null});var Lt={};jn(Lt,{EmbeddingPriorityQueue:()=>nt,EmbeddingWorkerPool:()=>_e,cosineSimilarity:()=>Dn,generateEmbedding:()=>Cn,generateEmbeddingsBatch:()=>it,getDefaultPool:()=>de,setUseWorkerThreads:()=>Me,shutdownDefaultPool:()=>kt});async function Wi(){return De||(De=await import("@xenova/transformers"),De.env.cacheDir="./.cache",De.env.allowLocalModels=!0),De}function Me(i){It=i,E.info({useWorkerThreads:i},"Worker thread mode updated")}async function vn(){return xt||(xt=(async()=>{E.info("Loading embedding model (all-MiniLM-L6-v2)...");let{pipeline:i}=await Wi();return await i("feature-extraction","Xenova/all-MiniLM-L6-v2")})()),xt}async function Cn(i){try{let t=await(await vn())(i,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return E.error({err:e},"Failed to generate embedding"),null}}async function it(i,e=Ln,t){return i.length===0?[]:It?de().generateEmbeddings(i,e,t):Nn(i,e,t)}async function Nn(i,e,t){let n=new Array(i.length).fill(null),s=await vn();for(let r=0;r<i.length;r+=e){let o=Math.min(r+e,i.length),l=i.slice(r,o);try{let c=await s(l,{pooling:"mean",normalize:!0}),[a,u]=c.dims;for(let p=0;p<a;p++){let m=p*u,d=m+u;n[r+p]=Array.from(c.data.slice(m,d))}}catch(c){E.error({err:c,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let a=0;a<l.length;a++)try{let u=l[a];if(!u||u.trim().length===0)continue;let p=await s(u,{pooling:"mean",normalize:!0});n[r+a]=Array.from(p.data)}catch{n[r+a]=null}}t&&t(o,i.length)}return E.debug({total:i.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function Dn(i,e){let t=0,n=0,s=0;for(let r=0;r<i.length;r++)t+=i[r]*e[r],n+=i[r]*i[r],s+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(s))}var De,Ln,It,xt,nt,we=Ae(()=>{"use strict";j();In();De=null;Ln=128,It=!1;xt=null;nt=class{queue=[];processing=!1;results=new Map;enqueue(e){this.queue.push(e),this.queue.sort((t,n)=>n.priority-t.priority)}enqueueMany(e){this.queue.push(...e),this.queue.sort((t,n)=>n.priority-t.priority)}get size(){return this.queue.length}get isProcessing(){return this.processing}getResult(e){return this.results.get(e)}async processQueue(e=Ln,t){if(this.processing)return E.warn("Queue processing already in progress"),this.results;this.processing=!0;let n=this.queue.length;try{It?await this.processQueueParallel(e,n,t):await this.processQueueSequential(e,n,t)}finally{this.processing=!1}return this.results}async processQueueSequential(e,t,n){for(;this.queue.length>0;){let s=this.queue.splice(0,e),r=s.map(l=>l.text),o=await Nn(r,r.length);if(s.forEach((l,c)=>{this.results.set(l.id,o[c])}),n){let l=t-this.queue.length;n(l,t)}}}async processQueueParallel(e,t,n){let s=this.queue.splice(0),r=s.map(c=>c.text),l=await de().generateEmbeddings(r,e,(c,a)=>{n&&n(c,a)});s.forEach((c,a)=>{this.results.set(c.id,l[a])})}clear(){this.queue=[],this.results.clear()}}});import zn from"fast-glob";import Ot from"fs";import qn from"ignore";import At from"path";var Fe=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],wt=["**/*.{ts,tsx,yaml,yml,php,py,go}","**/*.prisma","**/*.{graphql,gql}","**/Dockerfile*","**/.env*","**/package.json","**/lerna.json","**/turbo.json","**/pnpm-workspace.yaml"];var rs={FILTERED_QUERY_LIMIT_MULTIPLIER:3,SCORE_BASE:1e3,EXACT_MATCH_BONUS:500,RECENT_FILE_BOOST:80,OLDER_FILE_BOOST:30,RECENT_FILE_THRESHOLD_DAYS:7,OLDER_FILE_THRESHOLD_DAYS:30,FUZZY_MATCH_LIMIT:30,ENABLE_LEXICAL_SCORING:process.env.ENABLE_LEXICAL_SCORING!=="false",LEXICAL_WEIGHT:parseFloat(process.env.LEXICAL_WEIGHT??String(.4)),GRAVITY_STRUCTURAL_WEIGHT:.5};var Pe={DEFAULT_CONCURRENCY:parseInt(process.env.INDEX_CONCURRENCY??String(5),10)};async function dt(i,e=[]){let t=qn(),n=At.join(i,".gitignore");return Ot.existsSync(n)&&t.add(Ot.readFileSync(n,"utf8")),e.length>0&&t.add(e),(await zn(wt,{cwd:i,absolute:!0,ignore:Fe,stats:!0})).filter(o=>{let l=At.relative(i,o.path);return!t.ignores(l)}).map(o=>({path:o.path,mtime:o.stats.mtimeMs}))}import gt from"@swc/core";import Vt from"fs";function Ft(i){let e=i.split(`
2
+ `),t=[],n=0;for(let s of e)t.push(n),n+=s.length+1;return t}function O(i,e){for(let t=0;t<e.length;t++)if(e[t+1]>i||t===e.length-1)return t+1;return 1}function We(i,e){return e.slice(0,i).toString("utf8").length}function Pt(i){if(i.toString("utf8").length===i.length)return n=>n;let t=new Map;return n=>{let s=t.get(n);return s===void 0&&(s=i.slice(0,n).toString("utf8").length,t.set(n,s)),s}}function Wt(i,e,t){let n=i.start-e,s=i.end-e;return n<0||s>t.length?"":t.slice(n,s).toString("utf8")}function Ht(i){let e=[],t=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=t.exec(i))!==null;)e.push({start:n.index,end:n.index+n[0].length,text:n[0]});return e}function V(i,e,t){for(let n of e){if(n.start===i)return n.text;if(n.start>i&&n.start<i+50){let s=t.substring(i,n.start);if(/^\s*$/.test(s))return n.text}if(n.end<=i&&n.end>i-50){let s=t.substring(n.end,i);if(/^\s*$/.test(s))return n.text}}return""}function $t(i){if(!i)return"";let t=i.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
3
+ `)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function He(i,e,t){let n=i.toLowerCase(),s=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||s.startsWith("use")?"Hook":n.includes("models/")||s.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||s.endsWith("service")||s.endsWith("controller")||s.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||s.endsWith("repository")||s.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function Te(i){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(i)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(i)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(i)||/\.query\s*\(|\.execute\s*\(/i.test(i)&&/db|database|client|pool/i.test(i))&&e.push("Database"),(/\bfs\./i.test(i)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(i)||/import\s+.*\bfs\b/.test(i))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(i)||/\bdocument\.cookie\b/.test(i))&&e.push("Browser Storage"),e}function X(i,e){if(!i)return"";let t=i.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,s=0,r=t.length;for(let o=0;o<t.length;o++){let l=t[o];if(l==="(")n++;else if(l===")")n--;else if(l==="<")s++;else if(l===">")s--;else if(l==="{"){if(n===0&&s===0){r=o;break}}else if(l==="; "&&n===0&&s===0){r=o;break}else if(l==="="&&t[o+1]===">"&&n===0&&s===0){r=o+2;break}}return t.substring(0,r).trim()}function Ut(i){let e=[];for(let t of i)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join("","")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function Bt(i,e,t,n,s,r,o,l,c){let a=c??(p=>We(p,t)),u=[];for(let p of i){if(p.type==="ExportDeclaration"){let m=p.declaration,d=m.type,f="";d==="VariableDeclaration"?f=m.declarations.map(_=>_.id.value).join("",""):f=m.id?.value||m.identifier?.value||"anonymous";let g=a(p.span.start-e),b=a(p.span.end-e),h=V(g,r,n),y=l(p.span),T=[];if(p.type==="ExportDeclaration"&&(d==="ClassDeclaration"||d==="ClassExpression")){let _=m.body||[];for(let x of _)if(x.type==="ClassMethod"||x.type==="ClassProperty"){let I=x.key.value;if(!I)continue;let D=a(x.span.start-e),z=a(x.span.end-e),w=l(x.span),N=V(D,r,n);T.push({name:I,kind:x.type,signature:X(w,x.type),line:O(D,s),endLine:O(z,s),doc:N,classification:x.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(d==="FunctionDeclaration"&&m.body?.type==="BlockStatement")T=mt(m.body.stmts,e,t,n,s,r,l,a);else if(d==="VariableDeclaration"){for(let _ of m.declarations)if(_.init&&(_.init.type==="ArrowFunctionExpression"||_.init.type==="FunctionExpression")&&_.init.body?.type==="BlockStatement"){T=mt(_.init.body.stmts,e,t,n,s,r,l,a);break}}u.push({name:f,kind:d,signature:X(y,d),line:O(g,s),endLine:O(b,s),doc:h,classification:He(o,f,d),capabilities:JSON.stringify(Te(y)),members:T})}if(p.type==="ExportNamedDeclaration"){for(let m of p.specifiers)if(m.type==="ExportSpecifier"){let d=a(p.span.start-e),f=a(p.span.end-e),g=V(d,r,n);u.push({name:m.exported?.value||m.orig.value,kind:"ExportSpecifier",signature:`export { ${m.orig.value} }`,line:O(d,s),endLine:O(f,s),doc:g,classification:"Export mapping",capabilities:"[]"})}}if(p.type==="ExportDefaultDeclaration"){let m=a(p.span.start-e),d=a(p.span.end-e),f=V(m,r,n),g=l(p.span),b=[];if(p.decl.type==="ClassExpression"||p.decl.type==="ClassDeclaration"){let h=p.decl.body||[];for(let y of h)if(y.type==="ClassMethod"||y.type==="ClassProperty"){let T=y.key.value;if(!T)continue;let _=a(y.span.start-e),x=a(y.span.end-e),I=l(y.span),D=V(_,r,n);b.push({name:T,kind:y.type,signature:X(I,y.type),line:O(_,s),endLine:O(x,s),doc:D,classification:y.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(p.decl.type==="FunctionExpression"||p.decl.type==="FunctionDeclaration"||p.decl.type==="ArrowFunctionExpression")&&p.decl.body?.type==="BlockStatement"&&(b=mt(p.decl.body.stmts,e,t,n,s,r,l,a));u.push({name:"default",kind:"DefaultExport",signature:X(g,"DefaultExport"),line:O(m,s),endLine:O(d,s),doc:f,classification:"Default Export",capabilities:JSON.stringify(Te(g)),members:b})}if(p.type==="ExportAllDeclaration"){let m=a(p.span.start-e),d=a(p.span.end-e),f=p.source.value,g=V(m,r,n);u.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${f}"`,line:O(m,s),endLine:O(d,s),doc:g,classification:"Re-export",capabilities:"[]"})}}return u}function mt(i,e,t,n,s,r,o,l){let c=[];for(let a of i){if(a.type==="VariableDeclaration")for(let u of a.declarations){let p=[],m=d=>{if(d.type==="Identifier")p.push({name:d.value,span:d.span});else if(d.type==="ArrayPattern")for(let f of d.elements)f&&m(f);else if(d.type==="ObjectPattern")for(let f of d.properties)f.type==="AssignmentPatternProperty"?p.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&m(f.value)};m(u.id);for(let d of p){let f=l(d.span.start-e),g=l(d.span.end-e),b=o(d.span),h=V(f,r,n);c.push({name:d.name,kind:"VariableDeclaration",signature:X(b,"VariableDeclaration"),line:O(f,s),endLine:O(g,s),doc:h,classification:"Internal Variable",capabilities:"[]"})}}if(a.type==="FunctionDeclaration"){let u=a.identifier?.value||a.ident?.value||"anonymous",p=l(a.span.start-e),m=l(a.span.end-e),d=o(a.span),f=V(p,r,n);c.push({name:u,kind:"FunctionDeclaration",signature:X(d,"FunctionDeclaration"),line:O(p,s),endLine:O(m,s),doc:f,classification:"Internal Function",capabilities:"[]"})}if(a.type==="ReturnStatement"&&a.argument?.type==="ObjectExpression")for(let u of a.argument.properties){let p="",m=u.span||u.key?.span||u.ident?.span;if(u.type==="KeyValueProperty"){let d=u.key;p=d?.value||d?.raw||(d?.type==="Identifier"?d.value:"")}else u.type==="MethodProperty"?p=u.key?.value||u.key?.raw||"":u.type==="ShorthandProperty"?p=u.ident?.value||"":u.type==="Identifier"&&(p=u.value||"");if(p&&m){let d=l(m.start-e),f=l(m.end-e),g=o(m),b=V(d,r,n);c.push({name:p,kind:"ReturnProperty",signature:X(g,"ReturnProperty"),line:O(d,s),endLine:O(f,s),doc:b,classification:"Return Member",capabilities:"[]"})}}if(a.type==="ExpressionStatement"&&a.expression.type==="CallExpression"){let u=a.expression;if(u.callee.type==="MemberExpression"&&(u.callee.property?.value==="on"||u.callee.property?.value==="once")){let p=u.arguments[0]?.expression?.value,m=u.arguments[1]?.expression;if(p&&m&&(m.type==="ArrowFunctionExpression"||m.type==="FunctionExpression")){let d=l(m.span.start-e),f=l(m.span.end-e),g=o(m.span);c.push({name:`on:${p}`,kind:m.type,signature:X(g,m.type),line:O(d,s),endLine:O(f,s),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(u.callee.type==="Identifier"&&u.callee.value==="addRoute"&&u.arguments.length>=3){let p=u.arguments[2].expression;if(p.type==="StringLiteral"){let m=p.value,d=l(u.span.start-e),f=l(u.span.end-e),g=o(u.span);c.push({name:m,kind:"HTTP Route",signature:X(g,"HTTP Route"),line:O(d,s),endLine:O(f,s),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:m})})}}}}return c}function jt(i,e,t,n,s,r){let o=r??(a=>We(a,t)),l=[];function c(a){if(!(!a||typeof a!="object")){if(a.type==="CallExpression"){let u=Gn(a);if(u){let p=o(a.span.start-e);l.push({...u,line:O(p,n),snippet:s(a.span)})}}for(let u of Object.keys(a)){if(u==="span")continue;let p=a[u];Array.isArray(p)?p.forEach(c):typeof p=="object"&&c(p)}}}return i.forEach(c),l}function Gn(i){let{callee:e,arguments:t}=i;if(!t||t.length===0)return null;if(e.type==="Identifier"&&e.value,e.type==="Identifier"&&e.value==="addRoute"&&t.length>=3){let n=t[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value,o=e.object.type==="Identifier"?e.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(o))return{type:"api_route",name:r,direction:"produce"};if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function Se(i){let{classification:e,capabilities:t,exports:n,fileName:s}=i,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(f=>r[f]).filter(Boolean).join(" and "),c={Component:(f,g)=>{let b=g.find(y=>y.kind==="FunctionDeclaration"||y.kind==="ClassDeclaration")?.name,h=b?`React component: ${b}`:"React UI component";return f?`${h} with ${f}`:h},Hook:(f,g)=>{let b=g.find(y=>y.name.startsWith("use"))?.name,h=b?`Custom React hook: ${b}`:"Custom React hook";return f?`${h} for ${f}`:h},Service:(f,g)=>{let h=`Service layer: ${g[0]?.name||"Service"}`;return f?`${h} handling ${f}`:h},Repository:(f,g)=>`Data repository: ${g[0]?.name||"Repository"} for ${f||"data access"}`,"Type Definition":(f,g)=>`Type definitions: ${g.slice(0,3).map(h=>h.name).join("")}${g.length>3?"...":""}`,Model:(f,g)=>`Data model: ${g[0]?.name||"Model"}`,"HTTP Route":(f,g)=>{let b=g.filter(h=>h.classification==="Service Boundary");return b.length>0?`API endpoints: ${b.slice(0,3).map(h=>h.name).join("")}`:"API route handler"},"Micro IR (PHP)":(f,g)=>{let b=g.some(y=>y.classification==="Service Boundary"),h=g.find(y=>y.kind==="ClassDeclaration")?.name;return b?"PHP controller with API routes":h?`PHP class: ${h}`:"PHP module"},"Micro IR (Python)":(f,g)=>{let b=g.some(y=>y.classification==="Service Boundary"),h=g.find(y=>y.kind==="ClassDeclaration")?.name;return b?"Python API handler with routes":h?`Python class: ${h}`:"Python module"},"Micro IR (Go/TS) ":(f,g)=>{let b=g.some(y=>y.kind==="TypeDeclaration"),h=g.filter(y=>y.kind==="FunctionDeclaration");return b&&h.length>0?`Go package: types and ${h.length} function(s)`:b?"Go package: type definitions":h.length>0?`Go package: ${h[0].name} and ${h.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(f,g)=>{let b=g.find(T=>T.kind==="TraitDeclaration")?.name,h=g.find(T=>T.kind==="StructDeclaration")?.name,y=g.filter(T=>T.kind==="FunctionDeclaration");return b?f.includes("Rust trait")?`Rust module: trait ${b}`:`Rust module: ${b}`:h?`Rust module: struct ${h}`:y.length>0?`Rust module: ${y.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let a=n.filter(f=>f.kind==="FunctionDeclaration"),u=n.filter(f=>f.kind==="ClassDeclaration"),p=n.filter(f=>f.kind==="TsInterfaceDeclaration"||f.kind==="TsTypeAliasDeclaration"),m=[];if(u.length>0&&m.push(`Class: ${u[0].name}`),a.length>0){let f=a.slice(0,2).map(g=>g.name).join("");m.push(`Functions: ${f}`)}p.length>0&&m.push(`Types: ${p.length}`);let d=m.length>0?m.join(" | "):`Module with ${n.length} export(s)`;return o?`${d} \u2014 ${o}`:d}function zt(i){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&A(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&A(n,e);for(let s in n){if(s==="span"||s==="comments"||s==="interpreter")continue;let r=n[s];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return i.forEach(n=>t(n)),Array.from(e)}function A(i,e){if(i){if(i.type==="TsTypeAnnotation"){A(i.typeAnnotation,e);return}i.type==="TsTypeReference"&&(i.typeName?.type==="Identifier"&&e.add(i.typeName.value),i.typeName?.type==="TsQualifiedName"&&qt(i.typeName,e),i.typeParams&&A(i.typeParams,e)),i.type==="TsArrayType"&&A(i.elementType,e),i.type==="TsUnionType"&&i.types?.forEach(t=>A(t,e)),i.type==="TsIntersectionType"&&i.types?.forEach(t=>A(t,e)),i.type==="TsTupleType"&&i.elemTypes?.forEach(t=>A(t.ty,e)),(i.type==="TsFunctionType"||i.type==="TsConstructorType")&&(i.params?.forEach(t=>A(t.typeAnnotation,e)),i.typeAnnotation&&A(i.typeAnnotation,e)),i.type==="TsTypeParameterDeclaration"&&i.params?.forEach(t=>{t.constraint&&A(t.constraint,e),t.default&&A(t.default,e)}),i.type==="TsTypeParameterInstantiation"&&i.params?.forEach(t=>A(t,e)),i.type==="TsMappedType"&&i.typeAnnotation&&A(i.typeAnnotation,e),i.type==="TsIndexedAccessType"&&(A(i.objectType,e),A(i.indexType,e)),i.type==="TsConditionalType"&&(A(i.checkType,e),A(i.extendsType,e),A(i.trueType,e),A(i.falseType,e)),i.type==="TsTypeLiteral"&&i.members?.forEach(t=>{t.typeAnnotation&&A(t.typeAnnotation,e)})}}function qt(i,e){i.type==="TsQualifiedName"?(i.left&&qt(i.left,e),i.right?.value&&e.add(i.right.value)):i.type==="Identifier"&&e.add(i.value)}import Xt from"path";import ht from"path";j();$e();import Yt from"path";import ti from"fs";import{fileURLToPath as ni}from"url";import*as ue from"web-tree-sitter";var Ps=Yt.dirname(ni(import.meta.url)),Jt=E.child({module:"parser:tree-sitter"}),Ue=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=ue.Parser||ue;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=fe("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!ti.existsSync(t))return Jt.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await ue.Language.load(t);return this.languages.set(e,n),n}catch(n){return Jt.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
4
4
  (function_definition name: (name) @name) @func
5
5
  (class_declaration name: (name) @name) @class
6
6
  (interface_declaration name: (name) @name) @interface
@@ -24,39 +24,30 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
24
24
  (trait_item name: (_type_identifier) @name) @trait
25
25
  (type_item name: (_type_identifier) @name) @type
26
26
  (use_declaration argument: (_) @name) @import
27
- `;default:return""}}mapKind(e,t){if(e==="import")return"ImportDeclaration";if(t===".php"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration";if(e==="interface")return"InterfaceDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="method")return"MethodDeclaration"}if(t===".py"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration"}if(t===".go"){if(e==="func")return"FunctionDeclaration";if(e==="type")return"TypeDeclaration"}if(t===".rs"){if(e==="func")return"FunctionDeclaration";if(e==="struct")return"StructDeclaration";if(e==="enum")return"EnumDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(e){return e==="import"?"Dependency":e==="func"||e==="method"?"Function":e==="class"||e==="interface"||e==="trait"||e==="struct"||e==="enum"||e==="type"?"Class":"Other"}async parse(e,t){await this.ensureInitialized();let n=Pt.extname(e).toLowerCase(),s=await this.getLanguage(n);if(!s||!this.parser)return[];this.parser.setLanguage(s);let r=this.parser.parse(t),o=t.split(`
28
- `),c=this.getQueries(n);if(!c)return[];let a=new ae.Query(s,c).matches(r.rootNode),p=[];for(let d of a){let m=d.captures.find(E=>E.name==="name")?.node,f=d.captures[0].node,g=d.captures[0].name;if(m){let E=f.startPosition.row+1,y=f.endPosition.row+1,u=o[f.startPosition.row].trim();p.push({name:m.text,kind:this.mapKind(g,n),classification:this.mapClassification(g),signature:u,line:E,endLine:y,doc:"",capabilities:"{}"})}}return p}};var Me=class{parse(e,t=!1){let n=[],s=[],r=e.split(`
29
- `),o="",c="",l=0,a=0,p=-1,d=-1,m=[],f=[],g=!1,E=t?"api":"",y="",u=/^namespace\s+([a-zA-Z0-9_\\]+);/,h=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,b=/^interface\s+([a-zA-Z0-9_]+)/,M=/^trait\s+([a-zA-Z0-9_]+)/,C=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,I=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,v=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,$=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,N=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let R=0;R<r.length;R++){let S=r[R].trim();if(!S)continue;let w=(S.match(/{/g)||[]).length,D=(S.match(/}/g)||[]).length,j=a;if(a+=w-D,c&&a<=d){let L=n.find(T=>T.name===c&&T.line===l);L&&(L.endLine=R+1),c="",d=-1}if(o&&a<=p){let L=n.find(T=>T.name===o&&(T.kind==="ClassDeclaration"||T.kind==="TraitDeclaration"||T.kind==="InterfaceDeclaration"));L&&(L.endLine=R+1),o="",p=-1}let Q=S.match(N);if(Q&&(E=Q[1]),S.includes("});")&&(E=""),S.startsWith("/**")){g=!0,f=[];continue}if(g){S.endsWith("*/")?g=!1:f.push(S.replace(/^\*\s?/,""));continue}let V=S.match(v);if(V){m.push(V[1]);continue}let F=S.match(u);if(F){y=F[1]||"",m=[],f=[];continue}let k=S.match(h);if(k){o=k[1],p=a-w;let L={attributes:m};y&&(L.namespace=y),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:R+1,endLine:R+1,doc:f.join(`
30
- `).trim(),capabilities:JSON.stringify(L),members:[]}),m=[],f=[];continue}let x=S.match(b);if(x){let L=x[1];o=L,p=a-w,n.push({name:L,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${L}`,line:R+1,endLine:R+1,doc:f.join(`
31
- `).trim(),capabilities:JSON.stringify({attributes:m}),members:[]}),m=[],f=[];continue}let U=S.match(M);if(U){let L=U[1];o=L,p=a-w,n.push({name:L,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${L}`,line:R+1,endLine:R+1,doc:f.join(`
32
- `).trim(),capabilities:JSON.stringify({attributes:m}),members:[]}),m=[],f=[];continue}let he=S.match(C);if(he){let L=he[1],T=!!o;c=L,l=R+1,d=a-w;let oe=!1,z={};for(let H of m)H.toLowerCase().includes("route")&&(oe=!0,z={type:"route",method:"GET",path:"/"});let J=f.join(`
33
- `).trim();if(oe){let H=z.path||"/";n.push({name:H,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${L}`,line:R+1,endLine:R+1,doc:J,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${L}`:L,...z})}),s.push({type:"api_route",name:H,direction:"consume",line:R+1,snippet:S})}n.push({name:L,kind:T?"MethodDeclaration":"FunctionDeclaration",classification:T?"Method":"Function",signature:`${T?o+":: ":""}${L}`,line:R+1,endLine:R+1,doc:J,capabilities:JSON.stringify({attributes:m})}),m=[],f=[];continue}let se=S.match(I);if(se){let L=se[1]||"",T=se[2]||L.split("\\").pop()||"";n.push({name:T,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${L}`,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:L})}),m=[],f=[];continue}let pe=S.match($);if(pe){let L=pe[1].toUpperCase(),T=pe[2];if(S.includes("Route::")||S.includes("router->")||S.includes("action")||S.includes(",")&&!S.includes("view(")){if(E){let Z=E.startsWith("/")?E:`/${E}`,tt=T.startsWith("/")?T:`/${T}`;T=(Z+tt).replace(/\/+/g,"/")}let z=null,J=S.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(J)z=`${J[1]}@${J[2]}`;else if(S.includes("::class")){let Z=S.match(/([a-zA-Z0-9_]+)::class/);Z&&(z=Z[1])}let H=S;!S.endsWith(");")&&R+1<r.length&&(H+=" "+r[R+1].trim(),!H.endsWith(");")&&R+2<r.length&&(H+=" "+r[R+2].trim())),n.push({name:T,kind:"HTTP Route",classification:"Service Boundary",signature:H,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"route",method:L,path:T,handler:z})}),s.push({type:"api_route",name:T,direction:"consume",line:R+1,snippet:H,method:L,url:T}),f=[];continue}}let Le=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,re=S.match(Le);if(re){let L=(re[1]||re[3]).toUpperCase(),T=(re[2]||re[4]).trim();(T.startsWith("'")&&T.endsWith("'")||T.startsWith('"')&&T.endsWith('"'))&&(T=T.substring(1,T.length-1)),s.push({type:"api_route",name:T,direction:"produce",line:R+1,snippet:S,method:L,url:T})}!S.startsWith("#[")&&!S.startsWith("//")&&!S.startsWith("*")&&!g&&(m=[],f=[])}return{nodes:n,events:s}}};var Oe=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],s=e.split(`
34
- `),r=[{indent:-1,name:"root",type:"root"}],o=[],c=/^class\s+([a-zA-Z0-9_]+)/,l=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,a=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,p=/^@(.*)/;function d(u){return u.trim().split(/[.(]/)[0]?.trim()||u}function m(u){let h=u.decorators.map(M=>d(M.raw)),b={decorators:u.decorators,decoratorNames:h};return u.async===!0&&(b.async=!0),JSON.stringify(b)}let f=!1,g="",E=[],y=[];for(let u=0;u<s.length;u++){let h=s[u],b=h.trim();if(!b||b.startsWith("#"))continue;let M=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,C=b.match(M);if(C&&(this.currentRoutePrefix=C[2]),f){if(b.endsWith(g)||b.includes(g)){f=!1;let k=b.replace(g,"").trim();k&&E.push(k);let x=r[r.length-1];x.node&&(x.node.doc=E.join(`
35
- `).trim()),E=[]}else E.push(b);continue}let I=h.search(/\S/),v=h.trim(),$=v.match(/^(['"]{3})/);if($){let k=$[1],x=r[r.length-1];if(x.node&&!x.node.doc){if(v.substring(3).includes(k)){let U=v.replace(new RegExp(k,"g"),"").trim();x.node.doc=U}else{f=!0,g=k;let U=v.substring(3).trim();U&&E.push(U)}continue}}for(;r.length>1&&r[r.length-1].indent>=I;)r.pop();let N=r[r.length-1],R=v.match(p);if(R){o.push({raw:R[1].trim(),line:u+1});continue}let S=v.match(c);if(S){let k=S[1],x={name:k,kind:"ClassDeclaration",classification:"Class",signature:`class ${k}`,line:u+1,endLine:u+1,doc:"",capabilities:m({decorators:o}),members:[]};y.push(x),N.node?(N.node.members||(N.node.members=[]),N.node.members.push(x)):t.push(x),r.push({indent:I,name:k,type:"class",node:x}),o=[];continue}let w=v.match(l);if(w){let k=!!w[1],x=w[1]||w[2],U=N.type==="class",he=!1,se={};for(let T of o)if(T.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){he=!0;let z=["get","post","put","delete","patch"].find(Z=>T.raw.toLowerCase().includes(`.${Z}`))?.toUpperCase()||"GET",J=T.raw.match(/['"]([^'"]+)['"]/),H=J?J[1]:"/";if(this.currentRoutePrefix){let Z=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,tt=H.startsWith("/")?H:`/${H}`;H=Z+tt}se={type:"route",method:z,path:H}}if(he){let T=se.path||"",oe={name:T||x,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${x}`,line:u+1,endLine:u+1,doc:"",capabilities:JSON.stringify({handler:U?`${N.name}.${x}`:x,async:k,...se})};y.push(oe),t.push(oe),n.push({type:"api_route",name:T,direction:"consume",line:u+1,snippet:v})}let pe=o.some(T=>T.raw==="staticmethod"),Le=o.some(T=>T.raw==="classmethod"),re=`${k?"async ":""}${U?(pe?"@staticmethod ":Le?"@classmethod ":"")+N.name+".":""}${x}`,L={name:x,kind:k&&U?"AsyncMethodDeclaration":k?"AsyncFunctionDeclaration":U?"MethodDeclaration":"FunctionDeclaration",classification:U?pe||Le?"Static Method":"Method":"Function",signature:re,line:u+1,endLine:u+1,doc:"",capabilities:m({decorators:o,async:k}),members:[]};y.push(L),N.node?(N.node.members||(N.node.members=[]),N.node.members.push(L)):t.push(L),r.push({indent:I,name:x,type:"function",node:L}),o=[];continue}let D=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,j=v.match(D);if(j){let k=j[1].replace(/^\^/,""),x={name:k,kind:"HTTP Route",classification:"Service Boundary",signature:v.trim(),line:u+1,endLine:u+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:k})};y.push(x),t.push(x),n.push({type:"api_route",name:k,direction:"consume",line:u+1,snippet:v});continue}let Q=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,V=v.match(Q);if(V){let k=V[1].toUpperCase(),x=V[2].trim();(x.startsWith("'")&&x.endsWith("'")||x.startsWith('"')&&x.endsWith('"'))&&(x=x.substring(1,x.length-1)),n.push({type:"api_route",name:x,direction:"produce",line:u+1,snippet:v,method:k,url:x})}let F=v.match(a);if(F){let k=F[1]||F[2],x={name:k,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${k}`,line:u+1,endLine:u+1,doc:"",capabilities:JSON.stringify({type:"import",module:k})};y.push(x),t.push(x),o=[];continue}o=[],N.node&&(N.node.endLine=u+1)}return{nodes:y,events:n}}};var Ht=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function",signature:i[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:i=>({name:i[1],kind:"MethodDeclaration",classification:"Method",signature:i[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:i=>({name:i[1],kind:"ImportSpecifier",classification:"Dependency",signature:i[0],meta:{type:"import",path:i[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function",signature:i[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"StructDeclaration",classification:"Class",signature:i[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"EnumDeclaration",classification:"Class",signature:i[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"TraitDeclaration",classification:"Class",signature:i[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:i=>({name:i[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:i[0],meta:{type:"import",path:i[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:i=>({name:i[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:i=>({name:i[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:i[1]}})}]}];function Hn(i,e){let t=[];if(i===".go"&&e.some(n=>n.kind==="TypeDeclaration")&&t.push("Go type"),i===".rs"&&(e.some(n=>n.kind==="TraitDeclaration")&&t.push("Rust trait"),e.some(n=>n.kind==="StructDeclaration")&&t.push("Rust struct"),e.some(n=>n.kind==="EnumDeclaration")&&t.push("Rust enum")),i===".py"){for(let n of e)if(n.capabilities)try{if(JSON.parse(n.capabilities).decoratorNames?.length){t.push("Python decorators");break}}catch{}e.some(n=>n.kind==="AsyncFunctionDeclaration"||n.kind==="AsyncMethodDeclaration")&&t.push("Async")}return t}var Ae=class{phpParser=new Me;pythonParser=new Oe;treeSitterParser=new De;supports(e){return Ht.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=ot.extname(e).toLowerCase(),s=[],r=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let l=this.pythonParser.parse(t);s=l.nodes,r=l.events}else if(n===".php"){let l=e.toLowerCase().endsWith("api.php"),a=this.phpParser.parse(t,l);s=a.nodes,r=a.events}else try{s=await this.treeSitterParser.parse(e,t)}catch{}if(s.length>0){let l=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",a=s.filter(f=>f.classification!=="Dependency"),p=s.filter(f=>f.classification==="Dependency"),d=Hn(n,s),m=ye({classification:l,capabilities:d,exports:a.map(f=>({name:f.name,kind:f.kind,classification:f.classification})),fileName:ot.basename(e)});return{exports:a,imports:p.map(f=>({module:f.name,name:f.name,kind:f.kind,classification:f.classification})),events:r,classification:l,summary:m||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Ht.find(l=>l.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};for(let l of o.rules){l.regex.lastIndex=0;let a;for(;(a=l.regex.exec(t))!==null;){let p=l.onMatch(a),d=t.substring(0,a.index).split(`
36
- `).length;s.push({name:p.name||"anonymous",kind:p.kind||"Unknown",classification:p.classification||"Other",signature:p.signature||a[0],line:d,endLine:d,doc:"",capabilities:JSON.stringify(p.meta||{})})}}let c=ye({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:s.map(l=>({name:l.name,kind:l.kind,classification:l.classification})),fileName:ot.basename(e)});return{exports:s,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:c||"Module",parseStatus:s.length>0?"success":"partial"}}};var ct=new Ae;async function lt(i){let e=$t.extname(i);if(ct.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=at.readFileSync(i,"utf-8");return await ct.parse(i,r)}catch(r){return _.error({filePath:i,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:r.message}}let t;try{t=at.readFileSync(i)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),s=Lt(n);try{let r=i.endsWith(".tsx"),o=$n.parseSync(n,{syntax:"typescript",tsx:r,decorators:!0,comments:!0}),c=o.span.start,l=Ct(n),a=u=>kt(u,c,t),p=Nt(o.body),d=Ot(o.body);d.length>0&&_.debug({filePath:i,count:d.length},"Extracted type references"),d.forEach(u=>{p.push({module:"__type_reference__",name:u})});let m=Dt(o.body,c,t,n,s,l,i,a),f=Mt(o.body,c,t,s,a),g=ve(i,"","Module"),E=l.length>0&&l[0].start===0?l[0].text:m.find(u=>u.doc)?.doc||"",y=vt(E);if(!y&&m.length>0){let u=ge(n);y=ye({classification:g,capabilities:u,exports:m.map(h=>({name:h.name,kind:h.kind,classification:h.classification})),fileName:$t.basename(i)})}return{exports:m,imports:p,events:f,classification:g,summary:y,parseStatus:"success"}}catch(r){_.warn({filePath:i,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=at.readFileSync(i,"utf-8"),c=await ct.parse(i,o);return{...c,classification:c.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return _.error({filePath:i,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}function Un(i,e=500){let t=[],n=[],s=0;return i.forEach(r=>{let o=r.doc?.split(/\s+/).length||0;s+o>e&&(t.push(n),n=[],s=0),n.push(r),s+=o}),n.length&&t.push(n),t}import we from"path";var jn=50;function Ee(i,e,t,n){let s={name:we.basename(e)||e,type:"directory",path:e,children:[]};return i.forEach(r=>{let c=we.relative(e,r.path).split(we.sep),l=s;for(let a=0;a<c.length;a++){let p=c[a];if(n!==void 0&&a>=n)return;let d=a===c.length-1;if(n===1&&a===0&&d)return;let m=n!==void 0&&a===n-1&&!d,f=we.join(e,...c.slice(0,a+1)),g=l.children?.find(E=>E.name===p);if(!g){if(l.children&&l.children.length>=jn){l.children.find(u=>u.type==="truncated")||l.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}g={name:p,type:d?"file":"directory",path:f,children:d||m?void 0:[],summary:d?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},g.summary&&(t==="structure"||t==="signatures")&&(delete g.summary.chunks,delete g.summary.imports),l.children?.push(g)}l=g}}),s}import Sn from"p-limit";var pt=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];searchHistoryFailureCount=0;recordIndexStart(){this.indexRuns+=1}recordIndexCacheHit(){this.indexCacheHits+=1}recordIndexEnd(e){this.lastIndexDurationMs=e,this.lastIndexCompletedAt=Date.now()}recordIndexPhase(e,t){this.lastRunPhases.push({phase:e,durationMs:t})}clearIndexPhases(){this.lastRunPhases=[]}recordQueryStart(){let e=performance.now();return()=>{this.queryCount+=1;let t=performance.now()-e;if(this.lastQueryLatencyMs=t,this.recentLatencies.push(t),this.recentLatencies.length>100){let n=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-n+t}else this.recentLatencySumMs+=t,this.recentLatencyCount=this.recentLatencies.length}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((n,s)=>n+s,0)/e:null;return{index:{runs:this.indexRuns,cacheHits:this.indexCacheHits,lastDurationMs:this.lastIndexDurationMs,lastCompletedAt:this.lastIndexCompletedAt,lastRunPhases:[...this.lastRunPhases]},query:{count:this.queryCount,lastLatencyMs:this.lastQueryLatencyMs,recentLatencySumMs:this.recentLatencySumMs,recentLatencyCount:e,avgLatencyMs:t,searchHistoryFailures:this.searchHistoryFailureCount},uptimeMs:Date.now()-this.startTime}}reset(){this.indexRuns=0,this.indexCacheHits=0,this.lastIndexDurationMs=null,this.lastIndexCompletedAt=null,this.lastRunPhases=[],this.queryCount=0,this.lastQueryLatencyMs=null,this.recentLatencySumMs=0,this.recentLatencyCount=0,this.recentLatencies=[],this.searchHistoryFailureCount=0}},be=new pt;function Ut(){be.recordIndexStart()}function ut(){be.recordIndexCacheHit()}function jt(i){be.recordIndexEnd(i)}function Fe(i,e){be.recordIndexPhase(i,e)}function Bt(){be.clearIndexPhases()}import xi from"path";import Tt from"fs";import Ii from"os";import Qn from"better-sqlite3";import We from"path";import mt from"fs";import Gt from"crypto";import _e from"fs";import dt from"path";import{fileURLToPath as Bn}from"url";var Re=_.child({module:"migrations"}),qn=Bn(import.meta.url),Gn=dt.dirname(qn);function zn(i){i.exec(`
27
+ `;default:return""}}mapKind(e,t){if(e==="import")return"ImportDeclaration";if(t===".php"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration";if(e==="interface")return"InterfaceDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="method")return"MethodDeclaration"}if(t===".py"){if(e==="func")return"FunctionDeclaration";if(e==="class")return"ClassDeclaration"}if(t===".go"){if(e==="func")return"FunctionDeclaration";if(e==="type")return"TypeDeclaration"}if(t===".rs"){if(e==="func")return"FunctionDeclaration";if(e==="struct")return"StructDeclaration";if(e==="enum")return"EnumDeclaration";if(e==="trait")return"TraitDeclaration";if(e==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(e){return e==="import"?"Dependency":e==="func"||e==="method"?"Function":e==="class"||e==="interface"||e==="trait"||e==="struct"||e==="enum"||e==="type"?"Class":"Other"}async parse(e,t){await this.ensureInitialized();let n=Yt.extname(e).toLowerCase(),s=await this.getLanguage(n);if(!s||!this.parser)return[];this.parser.setLanguage(s);let r=this.parser.parse(t),o=t.split(`
28
+ `),l=this.getQueries(n);if(!l)return[];let a=new ue.Query(s,l).matches(r.rootNode),u=[];for(let p of a){let m=p.captures.find(g=>g.name==="name")?.node,d=p.captures[0].node,f=p.captures[0].name;if(m){let g=d.startPosition.row+1,b=d.endPosition.row+1,h=o[d.startPosition.row].trim();u.push({name:m.text,kind:this.mapKind(f,n),classification:this.mapClassification(f),signature:h,line:g,endLine:b,doc:"",capabilities:"{}"})}}return u}};var Be=class{parse(e,t=!1){let n=[],s=[],r=e.split(`
29
+ `),o="",l="",c=0,a=0,u=-1,p=-1,m=[],d=[],f=!1,g=t?"api":"",b="",h=/^namespace\s+([a-zA-Z0-9_\\]+);/,y=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,T=/^interface\s+([a-zA-Z0-9_]+)/,_=/^trait\s+([a-zA-Z0-9_]+)/,x=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,I=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,D=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,z=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,w=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let N=0;N<r.length;N++){let v=r[N].trim();if(!v)continue;let $=(v.match(/{/g)||[]).length,U=(v.match(/}/g)||[]).length,ne=a;if(a+=$-U,l&&a<=p){let L=n.find(k=>k.name===l&&k.line===c);L&&(L.endLine=N+1),l="",p=-1}if(o&&a<=u){let L=n.find(k=>k.name===o&&(k.kind==="ClassDeclaration"||k.kind==="TraitDeclaration"||k.kind==="InterfaceDeclaration"));L&&(L.endLine=N+1),o="",u=-1}let S=v.match(w);if(S&&(g=S[1]),v.includes("});")&&(g=""),v.startsWith("/**")){f=!0,d=[];continue}if(f){v.endsWith("*/")?f=!1:d.push(v.replace(/^\*\s?/,""));continue}let M=v.match(D);if(M){m.push(M[1]);continue}let P=v.match(h);if(P){b=P[1]||"",m=[],d=[];continue}let C=v.match(y);if(C){o=C[1],u=a-$;let L={attributes:m};b&&(L.namespace=b),n.push({name:o,kind:"ClassDeclaration",classification:"Class",signature:`class ${o}`,line:N+1,endLine:N+1,doc:d.join(`
30
+ `).trim(),capabilities:JSON.stringify(L),members:[]}),m=[],d=[];continue}let R=v.match(T);if(R){let L=R[1];o=L,u=a-$,n.push({name:L,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${L}`,line:N+1,endLine:N+1,doc:d.join(`
31
+ `).trim(),capabilities:JSON.stringify({attributes:m}),members:[]}),m=[],d=[];continue}let W=v.match(_);if(W){let L=W[1];o=L,u=a-$,n.push({name:L,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${L}`,line:N+1,endLine:N+1,doc:d.join(`
32
+ `).trim(),capabilities:JSON.stringify({attributes:m}),members:[]}),m=[],d=[];continue}let J=v.match(x);if(J){let L=J[1],k=!!o;l=L,c=N+1,p=a-$;let le=!1,Z={};for(let H of m)H.toLowerCase().includes("route")&&(le=!0,Z={type:"route",method:"GET",path:"/"});let ee=d.join(`
33
+ `).trim();if(le){let H=Z.path||"/";n.push({name:H,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${L}`,line:N+1,endLine:N+1,doc:ee,capabilities:JSON.stringify({type:"route",handler:o?`${o}@${L}`:L,...Z})}),s.push({type:"api_route",name:H,direction:"consume",line:N+1,snippet:v})}n.push({name:L,kind:k?"MethodDeclaration":"FunctionDeclaration",classification:k?"Method":"Function",signature:`${k?o+":: ":""}${L}`,line:N+1,endLine:N+1,doc:ee,capabilities:JSON.stringify({attributes:m})}),m=[],d=[];continue}let Y=v.match(I);if(Y){let L=Y[1]||"",k=Y[2]||L.split("\\").pop()||"";n.push({name:k,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${L}`,line:N+1,endLine:N+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:L})}),m=[],d=[];continue}let B=v.match(z);if(B){let L=B[1].toUpperCase(),k=B[2];if(v.includes("Route::")||v.includes("router->")||v.includes("action")||v.includes(",")&&!v.includes("view(")){if(g){let ie=g.startsWith("/")?g:`/${g}`,pt=k.startsWith("/")?k:`/${k}`;k=(ie+pt).replace(/\/+/g,"/")}let Z=null,ee=v.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(ee)Z=`${ee[1]}@${ee[2]}`;else if(v.includes("::class")){let ie=v.match(/([a-zA-Z0-9_]+)::class/);ie&&(Z=ie[1])}let H=v;!v.endsWith(");")&&N+1<r.length&&(H+=" "+r[N+1].trim(),!H.endsWith(");")&&N+2<r.length&&(H+=" "+r[N+2].trim())),n.push({name:k,kind:"HTTP Route",classification:"Service Boundary",signature:H,line:N+1,endLine:N+1,doc:"",capabilities:JSON.stringify({type:"route",method:L,path:k,handler:Z})}),s.push({type:"api_route",name:k,direction:"consume",line:N+1,snippet:H,method:L,url:k}),d=[];continue}}let Q=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,q=v.match(Q);if(q){let L=(q[1]||q[3]).toUpperCase(),k=(q[2]||q[4]).trim();(k.startsWith("'")&&k.endsWith("'")||k.startsWith('"')&&k.endsWith('"'))&&(k=k.substring(1,k.length-1)),s.push({type:"api_route",name:k,direction:"produce",line:N+1,snippet:v,method:L,url:k})}!v.startsWith("#[")&&!v.startsWith("//")&&!v.startsWith("*")&&!f&&(m=[],d=[])}return{nodes:n,events:s}}};var je=class{currentRoutePrefix="";parse(e){this.currentRoutePrefix="";let t=[],n=[],s=e.split(`
34
+ `),r=[{indent:-1,name:"root",type:"root"}],o=[],l=/^class\s+([a-zA-Z0-9_]+)/,c=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,a=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,u=/^@(.*)/;function p(h){return h.trim().split(/[.(]/)[0]?.trim()||h}function m(h){let y=h.decorators.map(_=>p(_.raw)),T={decorators:h.decorators,decoratorNames:y};return h.async===!0&&(T.async=!0),JSON.stringify(T)}let d=!1,f="",g=[],b=[];for(let h=0;h<s.length;h++){let y=s[h],T=y.trim();if(!T||T.startsWith("#"))continue;let _=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,x=T.match(_);if(x&&(this.currentRoutePrefix=x[2]),d){if(T.endsWith(f)||T.includes(f)){d=!1;let C=T.replace(f,"").trim();C&&g.push(C);let R=r[r.length-1];R.node&&(R.node.doc=g.join(`
35
+ `).trim()),g=[]}else g.push(T);continue}let I=y.search(/\S/),D=y.trim(),z=D.match(/^(['"]{3})/);if(z){let C=z[1],R=r[r.length-1];if(R.node&&!R.node.doc){if(D.substring(3).includes(C)){let W=D.replace(new RegExp(C,"g"),"").trim();R.node.doc=W}else{d=!0,f=C;let W=D.substring(3).trim();W&&g.push(W)}continue}}for(;r.length>1&&r[r.length-1].indent>=I;)r.pop();let w=r[r.length-1],N=D.match(u);if(N){o.push({raw:N[1].trim(),line:h+1});continue}let v=D.match(l);if(v){let C=v[1],R={name:C,kind:"ClassDeclaration",classification:"Class",signature:`class ${C}`,line:h+1,endLine:h+1,doc:"",capabilities:m({decorators:o}),members:[]};b.push(R),w.node?(w.node.members||(w.node.members=[]),w.node.members.push(R)):t.push(R),r.push({indent:I,name:C,type:"class",node:R}),o=[];continue}let $=D.match(c);if($){let C=!!$[1],R=$[1]||$[2],W=w.type==="class",J=!1,Y={};for(let k of o)if(k.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){J=!0;let Z=["get","post","put","delete","patch"].find(ie=>k.raw.toLowerCase().includes(`.${ie}`))?.toUpperCase()||"GET",ee=k.raw.match(/['"]([^'"]+)['"]/),H=ee?ee[1]:"/";if(this.currentRoutePrefix){let ie=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,pt=H.startsWith("/")?H:`/${H}`;H=ie+pt}Y={type:"route",method:Z,path:H}}if(J){let k=Y.path||"",le={name:k||R,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${R}`,line:h+1,endLine:h+1,doc:"",capabilities:JSON.stringify({handler:W?`${w.name}.${R}`:R,async:C,...Y})};b.push(le),t.push(le),n.push({type:"api_route",name:k,direction:"consume",line:h+1,snippet:D})}let B=o.some(k=>k.raw==="staticmethod"),Q=o.some(k=>k.raw==="classmethod"),q=`${C?"async ":""}${W?(B?"@staticmethod ":Q?"@classmethod ":"")+w.name+".":""}${R}`,L={name:R,kind:C&&W?"AsyncMethodDeclaration":C?"AsyncFunctionDeclaration":W?"MethodDeclaration":"FunctionDeclaration",classification:W?B||Q?"Static Method":"Method":"Function",signature:q,line:h+1,endLine:h+1,doc:"",capabilities:m({decorators:o,async:C}),members:[]};b.push(L),w.node?(w.node.members||(w.node.members=[]),w.node.members.push(L)):t.push(L),r.push({indent:I,name:R,type:"function",node:L}),o=[];continue}let U=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,ne=D.match(U);if(ne){let C=ne[1].replace(/^\^/,""),R={name:C,kind:"HTTP Route",classification:"Service Boundary",signature:D.trim(),line:h+1,endLine:h+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:C})};b.push(R),t.push(R),n.push({type:"api_route",name:C,direction:"consume",line:h+1,snippet:D});continue}let S=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,M=D.match(S);if(M){let C=M[1].toUpperCase(),R=M[2].trim();(R.startsWith("'")&&R.endsWith("'")||R.startsWith('"')&&R.endsWith('"'))&&(R=R.substring(1,R.length-1)),n.push({type:"api_route",name:R,direction:"produce",line:h+1,snippet:D,method:C,url:R})}let P=D.match(a);if(P){let C=P[1]||P[2],R={name:C,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${C}`,line:h+1,endLine:h+1,doc:"",capabilities:JSON.stringify({type:"import",module:C})};b.push(R),t.push(R),o=[];continue}o=[],w.node&&(w.node.endLine=h+1)}return{nodes:b,events:n}}};var Qt=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function",signature:i[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:i=>({name:i[1],kind:"MethodDeclaration",classification:"Method",signature:i[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:i=>({name:i[1],kind:"ImportSpecifier",classification:"Dependency",signature:i[0],meta:{type:"import",path:i[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function",signature:i[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"StructDeclaration",classification:"Class",signature:i[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"EnumDeclaration",classification:"Class",signature:i[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"TraitDeclaration",classification:"Class",signature:i[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:i=>({name:i[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:i[0],meta:{type:"import",path:i[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:i=>({name:i[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:i=>({name:i[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:i=>({name:i[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:i=>({name:i[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:i[1]}})}]}];function ii(i,e){let t=[];if(i===".go"&&e.some(n=>n.kind==="TypeDeclaration")&&t.push("Go type"),i===".rs"&&(e.some(n=>n.kind==="TraitDeclaration")&&t.push("Rust trait"),e.some(n=>n.kind==="StructDeclaration")&&t.push("Rust struct"),e.some(n=>n.kind==="EnumDeclaration")&&t.push("Rust enum")),i===".py"){for(let n of e)if(n.capabilities)try{if(JSON.parse(n.capabilities).decoratorNames?.length){t.push("Python decorators");break}}catch{}e.some(n=>n.kind==="AsyncFunctionDeclaration"||n.kind==="AsyncMethodDeclaration")&&t.push("Async")}return t}var ze=class{phpParser=new Be;pythonParser=new je;treeSitterParser=new Ue;supports(e){return Qt.some(t=>t.extension.includes(e.toLowerCase()))}async parse(e,t){let n=ht.extname(e).toLowerCase(),s=[],r=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let c=this.pythonParser.parse(t);s=c.nodes,r=c.events}else if(n===".php"){let c=e.toLowerCase().endsWith("api.php"),a=this.phpParser.parse(t,c);s=a.nodes,r=a.events}else try{s=await this.treeSitterParser.parse(e,t)}catch{}if(s.length>0){let c=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",a=s.filter(d=>d.classification!=="Dependency"),u=s.filter(d=>d.classification==="Dependency"),p=ii(n,s),m=Se({classification:c,capabilities:p,exports:a.map(d=>({name:d.name,kind:d.kind,classification:d.classification})),fileName:ht.basename(e)});return{exports:a,imports:u.map(d=>({module:d.name,name:d.name,kind:d.kind,classification:d.classification})),events:r,classification:c,summary:m||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Qt.find(c=>c.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};for(let c of o.rules){c.regex.lastIndex=0;let a;for(;(a=c.regex.exec(t))!==null;){let u=c.onMatch(a),p=t.substring(0,a.index).split(`
36
+ `).length;s.push({name:u.name||"anonymous",kind:u.kind||"Unknown",classification:u.classification||"Other",signature:u.signature||a[0],line:p,endLine:p,doc:"",capabilities:JSON.stringify(u.meta||{})})}}let l=Se({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:s.map(c=>({name:c.name,kind:c.kind,classification:c.classification})),fileName:ht.basename(e)});return{exports:s,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:l||"Module",parseStatus:s.length>0?"success":"partial"}}};j();var yt=new ze;async function Et(i){let e=Xt.extname(i);if(yt.supports(e)&&e!==".ts"&&e!==".tsx")try{let r=await Vt.promises.readFile(i,"utf-8");return{...await yt.parse(i,r),content:r}}catch(r){return E.error({filePath:i,error:r.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:r.message}}let t;try{t=await Vt.promises.readFile(i)}catch(r){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${r.message}`}}let n=t.toString("utf8"),s=Ft(n);try{let r=i.endsWith(".tsx"),o=i.endsWith(".d.ts")||i.endsWith(".d.tsx"),l,c={syntax:"typescript",tsx:r,decorators:!0,comments:!0};if(o)try{l=gt.parseSync(n,c)}catch{l=gt.parseSync(n,{...c,isModule:!1})}else l=gt.parseSync(n,c);let a=l.span.start,u=Pt(t),p=Ht(n),m=_=>Wt(_,a,t),d=Ut(l.body),f=zt(l.body);f.length>0&&E.debug({filePath:i,count:f.length},"Extracted type references"),f.forEach(_=>{d.push({module:"__type_reference__",name:_})});let g=Bt(l.body,a,t,n,s,p,i,m,u),b=jt(l.body,a,t,s,m,u),h=He(i,"","Module"),y=p.length>0&&p[0].start===0?p[0].text:g.find(_=>_.doc)?.doc||"",T=$t(y);if(!T&&g.length>0){let _=Te(n);T=Se({classification:h,capabilities:_,exports:g.map(x=>({name:x.name,kind:x.kind,classification:x.classification})),fileName:Xt.basename(i)})}return{exports:g,imports:d,events:b,classification:h,summary:T,content:n,parseStatus:"success"}}catch(r){E.warn({filePath:i,error:r.message},"SWC parsing failed, using heuristic fallback");try{let o=await yt.parse(i,n);return{...o,content:n,classification:o.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${r.message}`}}catch(o){return E.error({filePath:i,error:o.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${o.message}`}}}}function si(i,e=500){let t=[],n=[],s=0;return i.forEach(r=>{let o=r.doc?.split(/\s+/).length||0;s+o>e&&(t.push(n),n=[],s=0),n.push(r),s+=o}),n.length&&t.push(n),t}import qe from"path";var ri=50;function ke(i,e,t,n){let s={name:qe.basename(e)||e,type:"directory",path:e,children:[]};return i.forEach(r=>{let l=qe.relative(e,r.path).split(qe.sep),c=s;for(let a=0;a<l.length;a++){let u=l[a];if(n!==void 0&&a>=n)return;let p=a===l.length-1;if(n===1&&a===0&&p)return;let m=n!==void 0&&a===n-1&&!p,d=qe.join(e,...l.slice(0,a+1)),f=c.children?.find(g=>g.name===u);if(!f){if(c.children&&c.children.length>=ri){c.children.find(h=>h.type==="truncated")||c.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}f={name:u,type:p?"file":"directory",path:d,children:p||m?void 0:[],summary:p?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},f.summary&&(t==="structure"||t==="signatures")&&(delete f.summary.chunks,delete f.summary.imports),c.children?.push(f)}c=f}}),s}j();import Nt from"p-limit";var bt=class{startTime=Date.now();indexRuns=0;indexCacheHits=0;lastIndexDurationMs=null;lastIndexCompletedAt=null;lastRunPhases=[];queryCount=0;lastQueryLatencyMs=null;recentLatencySumMs=0;recentLatencyCount=0;recentLatencies=[];searchHistoryFailureCount=0;recordIndexStart(){this.indexRuns+=1}recordIndexCacheHit(){this.indexCacheHits+=1}recordIndexEnd(e){this.lastIndexDurationMs=e,this.lastIndexCompletedAt=Date.now()}recordIndexPhase(e,t){this.lastRunPhases.push({phase:e,durationMs:t})}clearIndexPhases(){this.lastRunPhases=[]}recordQueryStart(){let e=performance.now();return()=>{this.queryCount+=1;let t=performance.now()-e;if(this.lastQueryLatencyMs=t,this.recentLatencies.push(t),this.recentLatencies.length>100){let n=this.recentLatencies.shift();this.recentLatencySumMs=this.recentLatencySumMs-n+t}else this.recentLatencySumMs+=t,this.recentLatencyCount=this.recentLatencies.length}}recordSearchHistoryFailure(){this.searchHistoryFailureCount+=1}getSnapshot(){let e=this.recentLatencies.length,t=e>0?this.recentLatencies.reduce((n,s)=>n+s,0)/e:null;return{index:{runs:this.indexRuns,cacheHits:this.indexCacheHits,lastDurationMs:this.lastIndexDurationMs,lastCompletedAt:this.lastIndexCompletedAt,lastRunPhases:[...this.lastRunPhases]},query:{count:this.queryCount,lastLatencyMs:this.lastQueryLatencyMs,recentLatencySumMs:this.recentLatencySumMs,recentLatencyCount:e,avgLatencyMs:t,searchHistoryFailures:this.searchHistoryFailureCount},uptimeMs:Date.now()-this.startTime}}reset(){this.indexRuns=0,this.indexCacheHits=0,this.lastIndexDurationMs=null,this.lastIndexCompletedAt=null,this.lastRunPhases=[],this.queryCount=0,this.lastQueryLatencyMs=null,this.recentLatencySumMs=0,this.recentLatencyCount=0,this.recentLatencies=[],this.searchHistoryFailureCount=0}},xe=new bt;function Zt(){xe.recordIndexStart()}function _t(){xe.recordIndexCacheHit()}function en(i){xe.recordIndexEnd(i)}function Ie(i,e){xe.recordIndexPhase(i,e)}function tn(){xe.clearIndexPhases()}import Dt from"path";import Xi from"fs";import Zi from"os";j();import mi from"better-sqlite3";import Ge from"path";import Tt from"fs";import sn from"crypto";j();import Le from"fs";import Rt from"path";import{fileURLToPath as oi}from"url";var ve=E.child({module:"migrations"}),ai=oi(import.meta.url),ci=Rt.dirname(ai);function li(i){i.exec(`
37
37
  CREATE TABLE IF NOT EXISTS schema_migrations (
38
38
  version INTEGER PRIMARY KEY,
39
39
  name TEXT NOT NULL,
40
40
  applied_at REAL DEFAULT (unixepoch())
41
41
  );
42
- `)}function Jn(i){zn(i);let e=i.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function Yn(){let i=Gn;if(!_e.readdirSync(i).some(r=>r.match(/^\d{3}_.*\.sql$/))){let r=dt.resolve(i,"../../data/migrations");_e.existsSync(r)&&_e.readdirSync(r).some(c=>c.match(/^\d{3}_.*\.sql$/))&&(i=r)}let n=_e.readdirSync(i).filter(r=>r.match(/^\d{3}_.*\.sql$/)).sort(),s=[];for(let r of n){let o=r.match(/^(\d{3})_(.+)\.sql$/);if(!o)continue;let c=parseInt(o[1],10),l=o[2],p=_e.readFileSync(dt.join(i,r),"utf-8").split(/^-- DOWN$/m),d=p[0].trim(),m=p[1]?.trim();s.push({version:c,name:l,up:d,down:m})}return s}function Kn(i,e){Re.info({version:e.version,name:e.name},"Applying migration"),i.transaction(()=>{i.exec(e.up),i.prepare("INSERT INTO schema_migrations (version, name) VALUES (?, ?)").run(e.version,e.name)})(),Re.info({version:e.version},"Migration applied successfully")}function qt(i){let e=Jn(i),n=Yn().filter(s=>!e.has(s.version));if(n.length===0){Re.debug("No pending migrations");return}Re.info({count:n.length},"Running pending migrations");for(let s of n)Kn(i,s);Re.info("All migrations complete")}import Vn from"os";var K=_.child({module:"db"});function He(i){let e=Vn.homedir(),t=We.join(e,".mcp-liquid-shadow"),n=We.join(t,"dbs");mt.existsSync(n)||mt.mkdirSync(n,{recursive:!0});let s=Gt.createHash("sha256").update(i).digest("hex").substring(0,12),o=`${We.basename(i).replace(/[^a-zA-Z0-9-_]/g,"_")}_${s}.db`;return We.join(n,o)}function Zn(i,e){let t=e||He(i);K.info({repoPath:i,dbPath:t},"Initializing database");let n=new Qn(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),qt(n),Pe.set(i,t),X.set(t,n),K.info({repoPath:i,dbPath:t},"Database initialized successfully"),n}var X=new Map,Pe=new Map;function ft(i){return Gt.createHash("sha256").update(i,"utf8").digest("hex")}function zt(i,e){return e?ft(i)!==e:!0}function ue(i){let e=Pe.get(i)||He(i),t=X.get(e);if(t){if(t.open)return t;X.delete(e)}let n=Zn(i);return X.set(e,n),n}function Jt(i){let e=He(i);if(!mt.existsSync(e))return!1;try{let t=ue(i);return t.prepare(`
42
+ `)}function ui(i){li(i);let e=i.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function pi(){let i=ci;if(!Le.readdirSync(i).some(r=>r.match(/^\d{3}_.*\.sql$/))){let r=Rt.resolve(i,"../../data/migrations");Le.existsSync(r)&&Le.readdirSync(r).some(l=>l.match(/^\d{3}_.*\.sql$/))&&(i=r)}let n=Le.readdirSync(i).filter(r=>r.match(/^\d{3}_.*\.sql$/)).sort(),s=[];for(let r of n){let o=r.match(/^(\d{3})_(.+)\.sql$/);if(!o)continue;let l=parseInt(o[1],10),c=o[2],u=Le.readFileSync(Rt.join(i,r),"utf-8").split(/^-- DOWN$/m),p=u[0].trim(),m=u[1]?.trim();s.push({version:l,name:c,up:p,down:m})}return s}function di(i,e){ve.info({version:e.version,name:e.name},"Applying migration"),i.transaction(()=>{i.exec(e.up),i.prepare("INSERT INTO schema_migrations (version, name) VALUES (?, ?)").run(e.version,e.name)})(),ve.info({version:e.version},"Migration applied successfully")}function nn(i){let e=ui(i),n=pi().filter(s=>!e.has(s.version));if(n.length===0){ve.debug("No pending migrations");return}ve.info({count:n.length},"Running pending migrations");for(let s of n)di(i,s);ve.info("All migrations complete")}import fi from"os";var te=E.child({module:"db"});function Je(i){let e=fi.homedir(),t=Ge.join(e,".mcp-liquid-shadow"),n=Ge.join(t,"dbs");Tt.existsSync(n)||Tt.mkdirSync(n,{recursive:!0});let s=sn.createHash("sha256").update(i).digest("hex").substring(0,12),o=`${Ge.basename(i).replace(/[^a-zA-Z0-9-_]/g,"_")}_${s}.db`;return Ge.join(n,o)}function hi(i,e){let t=e||Je(i);te.debug({repoPath:i,dbPath:t},"Initializing database");let n=new mi(t);return n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),nn(n),Ke.set(i,t),se.set(t,n),te.debug({repoPath:i,dbPath:t},"Database initialized successfully"),n}var se=new Map,Ke=new Map;function he(i){return sn.createHash("sha256").update(i,"utf8").digest("hex")}function rn(i,e){return e?he(i)!==e:!0}function ge(i){let e=Ke.get(i)||Je(i),t=se.get(e);if(t){if(t.open)return t;se.delete(e)}let n=hi(i);return se.set(e,n),n}function on(i){let e=Je(i);if(!Tt.existsSync(e))return!1;try{let t=ge(i);return t.prepare(`
43
43
  SELECT value FROM index_metadata
44
44
  WHERE key = 'index_completed'
45
- `).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return K.debug({repoPath:i,error:t},"Error checking index status"),!1}}function ht(i,e){let t=ue(i);t.prepare(`
46
- INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
47
- VALUES ('index_completed', 'true', unixepoch())
48
- `).run(),t.prepare(`
49
- INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
50
- VALUES ('last_indexed_at', ?, unixepoch())
51
- `).run(Date.now().toString()),e&&t.prepare(`
52
- INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
53
- VALUES ('last_indexed_commit', ?, unixepoch())
54
- `).run(e),K.info({repoPath:i,commitSha:e},"Repository marked as indexed")}function Yt(i){try{return ue(i).prepare(`
45
+ `).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return te.debug({repoPath:i,error:t},"Error checking index status"),!1}}function St(i,e){let t=ge(i),n=t.prepare("INSERT OR REPLACE INTO index_metadata (key, value, updated_at) VALUES (?, ?, unixepoch())");t.transaction(()=>{n.run("index_completed","true"),n.run("last_indexed_at",Date.now().toString()),e&&n.run("last_indexed_commit",e)})(),te.debug({repoPath:i,commitSha:e},"Repository marked as indexed")}function an(i){try{return ge(i).prepare(`
55
46
  SELECT value FROM index_metadata
56
47
  WHERE key = 'last_indexed_commit'
57
- `).get()?.value||null}catch(e){return K.debug({repoPath:i,error:e},"Error getting last indexed commit"),null}}function Kt(i){let e=Pe.get(i)||He(i),t=X.get(e);t&&(t.open&&(K.info({repoPath:i,dbPath:e},"Closing database connection"),t.close()),X.delete(e)),Pe.delete(i)}function Qt(){for(let[i,e]of X.entries())try{e.open&&(K.info({dbPath:i},"Closing database connection"),e.close())}catch(t){K.error({dbPath:i,err:t},"Error closing database execution")}X.clear()}process.on("exit",()=>Qt());var Vt=i=>{K.info({signal:i},"Received termination signal, closing databases"),Qt(),process.exit(0)};process.on("SIGINT",()=>Vt("SIGINT"));process.on("SIGTERM",()=>Vt("SIGTERM"));import q from"path";import me from"fs";import{loadConfig as ei,createMatchPath as ti}from"tsconfig-paths";import ee from"path";import Te from"fs";var te=class extends Error{constructor(t,n,s){super(n);this.code=t;this.cause=s;this.name="FileSystemError"}};function Zt(i){let e;try{e=Te.statSync(i).isDirectory()?i:ee.dirname(i)}catch(t){throw t.code==="ENOENT"?new te("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new te("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new te("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==ee.dirname(e);){let t=ee.join(e,"tsconfig.json");if(Te.existsSync(t))return e;e=ee.dirname(e)}return null}function Xt(i){let e;try{e=Te.statSync(i).isDirectory()?i:ee.dirname(i)}catch(t){throw t.code==="ENOENT"?new te("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new te("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new te("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==ee.dirname(e);){let t=ee.join(e,"package.json");if(Te.existsSync(t))try{if(JSON.parse(Te.readFileSync(t,"utf8")).workspaces)return e}catch{}e=ee.dirname(e)}return null}import de from"path";import ce from"fs";function en(i,e){let t=new Map,n=e.workspaces||[];for(let s of n){let r=s.replace("/*",""),o=de.join(i,r);if(!ce.existsSync(o))continue;let c=ce.readdirSync(o);for(let l of c){let a=de.join(o,l,"package.json");if(ce.existsSync(a))try{let p=JSON.parse(ce.readFileSync(a,"utf8"));p.name&&t.set(p.name,{name:p.name,path:de.dirname(a),main:p.main||"dist/index.js"})}catch{}}}return t}function tn(i){let e=new Map;try{let t=JSON.parse(ce.readFileSync(i,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[s,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),c=de.dirname(i),l=de.resolve(c,o),a=de.join(l,"package.json");if(ce.existsSync(a))try{let p=JSON.parse(ce.readFileSync(a,"utf8"));e.set(s,{name:s,path:l,main:p.main||"dist/index.js"})}catch{}}}catch{}return e}import nn from"path";import B from"fs";var Xn=[".ts",".tsx",".d.ts",".js",".jsx"];function ne(i){let e=nn.extname(i);if(e===".js"||e===".jsx"){let t=i.slice(0,-e.length),n=e===".jsx"?[".tsx",".ts"]:[".ts",".tsx"];for(let s of n){let r=t+s;if(B.existsSync(r)&&B.statSync(r).isFile())return r}if(B.existsSync(i)&&B.statSync(i).isFile())return i}if(B.existsSync(i)&&B.statSync(i).isFile())return i;for(let t of Xn){let n=i+t;if(B.existsSync(n)&&B.statSync(n).isFile())return n}if(B.existsSync(i)&&B.statSync(i).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=nn.join(i,"index"+t);if(B.existsSync(n))return n}return""}var Ue=new Map;function $e(i){let e=Zt(i);if(!e)return null;if(Ue.has(e))return Ue.get(e)||null;let t=ei(e);if(t.resultType==="failed")return Ue.set(e,null),null;let n=t,s=n.absoluteBaseUrl;!s&&n.paths&&Object.keys(n.paths).length>0&&(s=n.configFileAbsolutePath?q.dirname(n.configFileAbsolutePath):e);let r=ti(s,n.paths,n.mainFields,n.addMatchAll),o=Xt(e),c=new Map;if(o){let d=q.join(o,"package.json");if(me.existsSync(d))try{let m=JSON.parse(me.readFileSync(d,"utf8"));c=en(o,m)}catch{}}let l=q.join(e,"package.json");me.existsSync(l)&&tn(l).forEach((m,f)=>c.set(f,m));let a={baseUrl:s||"",paths:n.paths,matchPath:r,workspacePackages:c,imports:new Map},p=q.join(e,"package.json");if(me.existsSync(p))try{let d=JSON.parse(me.readFileSync(p,"utf8"));if(d.imports){for(let[m,f]of Object.entries(d.imports))if(typeof f=="string"||typeof f=="object"&&f!==null){let g=f;Array.isArray(f)&&(g=f[0]),typeof g=="object"&&(g=g.default||g.node),typeof g=="string"&&a.imports.set(m,g)}}}catch{}return Ue.set(e,a),a}function gt(i,e,t){if(!i)return"";if(i.includes(".")&&!i.startsWith(".")&&!i.startsWith("/")&&!i.endsWith(".js")&&!i.endsWith(".ts")&&!i.endsWith(".json")){let s=i.split(".")[0];if(s&&s!==i){let r=gt(s,e,t);if(r)return r}}if(i.startsWith(".")){let s=q.dirname(e),r=q.resolve(s,i);return ne(r)}let n=$e(e);if(n){let s=n.matchPath(i);if(s)return ne(s);if(!i.startsWith("@")||i.startsWith("@/")){let o=q.resolve(n.baseUrl,i),c=ne(o);if(c)return c}for(let[o,c]of n.imports.entries())if(o.includes("*")){let l="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",a=new RegExp(l),p=i.match(a);if(p){let d=p[1],m=c.replace("*",d),f=q.resolve(n.baseUrl,m);return ne(f)}}else if(o===i){let l=q.resolve(n.baseUrl,c);return ne(l)}let r=n.workspacePackages.get(i);if(r){let o=q.join(r.path,"src/index.ts");if(me.existsSync(o))return o;let c=q.join(r.path,r.main),l=ne(c);if(l)return l}}return""}import ni from"fs";import ii from"path";import rn from"js-yaml";function sn(i){let e=ii.basename(i),t=ni.readFileSync(i,"utf8"),n=[];if(e.endsWith(".prisma"))return ai(t,i);if(e.endsWith(".graphql")||e.endsWith(".gql"))return ci(t,i);let s="Configuration";return e==="lerna.json"?pi(t,i):e==="turbo.json"?ui(t,i):e==="pnpm-workspace.yaml"?di(t,i):(e.includes("Dockerfile")?(s="Infrastructure (Docker) ",si(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(s="Infrastructure (YAML) ",ri(t,n)):e.startsWith(".env")?(s="Configuration (Env) ",oi(t,n)):e==="package.json"&&(s="Project Manifest",li(t,n)),{configs:n,classification:s})}function si(i,e){let t=i.split(`
58
- `);for(let n of t){let s=n.trim();if(s.startsWith("FROM "))e.push({key:"base_image",value:s.substring(5).trim(),kind:"Image"});else if(s.startsWith("EXPOSE "))e.push({key:"port",value:s.substring(7).trim(),kind:"Port"});else if(s.startsWith("ENV ")){let r=s.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],c=r.slice(1).join("= ").trim()||"undefined",l="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(l="Service"),e.push({key:o,value:c,kind:l})}}}}function ri(i,e){try{let t=rn.load(i);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[s,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${s}`,value:s,kind:"Service"}),o.image&&e.push({key:`service:${s}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(c=>{e.push({key:`service:${s}:port`,value:String(c),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(c=>{let[l,...a]=c.split("= ");l&&a.length>0&&e.push({key:`service:${s}:env:${l}`,value:a.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[c,l]of Object.entries(o.environment))e.push({key:`service:${s}:env:${c}`,value:String(l),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(c=>{e.push({key:`service:${s}:depends_on`,value:c,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let c of Object.keys(o.depends_on))e.push({key:`service:${s}:depends_on`,value:c,kind:"Dependency"})}let n=(s,r="")=>{if(!(!s||typeof s!="object"||Array.isArray(s)))for(let[o,c]of Object.entries(s)){let l=r?`${r}.${o}`:o;if(t.services&&(l.startsWith("services.")||l==="services")){c&&typeof c=="object"&&!Array.isArray(c)&&n(c,l);continue}if(c&&typeof c=="object"&&!Array.isArray(c))n(c,l);else{let a=String(c),p="Env";o.toLowerCase().includes("image")&&(p="Image"),o.toLowerCase().includes("port")&&(p="Port"),o.toLowerCase().includes("service")&&(p="Service"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(p="Service"),e.push({key:l,value:a.length>100?a.substring(0,97)+"...":a,kind:p})}}};n(t)}catch{let n=i.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(s=>{let r=s.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function oi(i,e){let t=i.split(`
59
- `);for(let n of t){let s=n.trim();if(s&&!s.startsWith("#")){let r=s.split("=");if(r[0]){let o=r[0].trim(),c=r.slice(1).join("=");c=c.trim().replace(/^['"](.*)['"]$/,"$1");let l="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(l="Service"),e.push({key:o,value:c,kind:l})}}}}function ai(i,e){let t=[],n="Contract (Prisma) ",s=/^model\s+(\w+)/gm,r;for(;(r=s.exec(i))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(i))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let c=/provider\s*=\s*"([^"]+)"/,l=i.match(c);return l&&t.push({key:"datasource_provider",value:l[1],kind:"Database Config"}),{classification:n,configs:t}}function ci(i,e){let t=[],n="Contract (GraphQL) ",s=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=s.exec(i))!==null;){let o=r[0],c="GraphQL Type";o.startsWith("input")&&(c="GraphQL Input"),o.startsWith("interface")&&(c="GraphQL Interface"),o.startsWith("enum")&&(c="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:c})}return{classification:n,configs:t}}function li(i,e){try{let t=JSON.parse(i);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"Service"}),t.workspaces){let r=Array.isArray(t.workspaces)?t.workspaces.join("",""):JSON.stringify(t.workspaces);e.push({key:"workspaces",value:r,kind:"Env"})}if(t.scripts){let r=["start","dev","build","test","docker"];for(let o of Object.keys(t.scripts))r.some(c=>o.includes(c))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},s=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(s.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Service"})}}catch{}}function pi(i,e){let t=[],n="Monorepo (Lerna) ";try{let s=JSON.parse(i);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),s.version&&t.push({key:"lerna_version",value:s.version,kind:"Monorepo"}),s.packages&&(Array.isArray(s.packages)?s.packages:[s.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),s.npmClient&&t.push({key:"npm_client",value:s.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n}}function ui(i,e){let t=[],n="Monorepo (Turborepo) ";try{let s=JSON.parse(i);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),s.pipeline)for(let r of Object.keys(s.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=s.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(s.tasks)for(let r of Object.keys(s.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n}}function di(i,e){let t=[],n="Monorepo (pnpm) ";try{let s=rn.load(i);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),s&&s.packages&&(Array.isArray(s.packages)?s.packages:[s.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n}}import on from"fs";import mi from"path";import an from"js-yaml";var cn={ignore:[],include:[],maxDepth:10},fi=[{name:".liquid-shadow.yaml",parse:i=>an.load(i)??{}},{name:".liquid-shadow.yml",parse:i=>an.load(i)??{}},{name:".ls.json",parse:i=>JSON.parse(i)},{name:".liquid-shadow.json",parse:i=>JSON.parse(i)},{name:".ls.rc",parse:i=>JSON.parse(i)},{name:".liquid-shadow.rc",parse:i=>JSON.parse(i)}];function je(i){for(let{name:e,parse:t}of fi){let n=mi.join(i,e);if(on.existsSync(n))try{let s=on.readFileSync(n,"utf8"),r=t(s);return _.info({repoPath:i,configFile:e},"Loaded repository configuration"),{...cn,...r}}catch(s){_.error({repoPath:i,file:e,err:s},"Failed to parse configuration file")}}return cn}import hi from"path";var P=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 Be=class extends P{findByPath(e){return this.get("SELECT * FROM files WHERE path = ?",e)}findAll(e){let t="SELECT * FROM files ORDER BY path ASC";return e&&(t+=` LIMIT ${e}`),this.all(t)}getAllPaths(){return this.all("SELECT path FROM files").map(t=>t.path)}findInSubPath(e,t){let n=hi.resolve(e,t),s=n.endsWith("/")?n:n+"/";return this.all(`
48
+ `).get()?.value||null}catch(e){return te.debug({repoPath:i,error:e},"Error getting last indexed commit"),null}}function cn(i){let e=Ke.get(i)||Je(i),t=se.get(e);t&&(t.open&&(te.debug({repoPath:i,dbPath:e},"Closing database connection"),t.close()),se.delete(e)),Ke.delete(i)}function ln(){for(let[i,e]of se.entries())try{e.open&&(te.debug({dbPath:i},"Closing database connection"),e.close())}catch(t){te.error({dbPath:i,err:t},"Error closing database execution")}se.clear()}process.on("exit",()=>ln());var un=i=>{te.debug({signal:i},"Received termination signal, closing databases"),ln(),process.exit(0)};process.on("SIGINT",()=>un("SIGINT"));process.on("SIGTERM",()=>un("SIGTERM"));import K from"path";import Ee from"fs";import{loadConfig as yi,createMatchPath as Ei}from"tsconfig-paths";import re from"path";import Ce from"fs";var oe=class extends Error{constructor(t,n,s){super(n);this.code=t;this.cause=s;this.name="FileSystemError"}};function pn(i){let e;try{e=Ce.statSync(i).isDirectory()?i:re.dirname(i)}catch(t){throw t.code==="ENOENT"?new oe("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new oe("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new oe("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==re.dirname(e);){let t=re.join(e,"tsconfig.json");if(Ce.existsSync(t))return e;e=re.dirname(e)}return null}function dn(i){let e;try{e=Ce.statSync(i).isDirectory()?i:re.dirname(i)}catch(t){throw t.code==="ENOENT"?new oe("FILE_NOT_FOUND",`Start path does not exist: ${i}`,t):t.code==="EACCES"||t.code==="EPERM"?new oe("PERMISSION_DENIED",`Permission denied accessing: ${i}`,t):new oe("UNKNOWN",`Failed to access path: ${i}`,t)}for(;e!==re.dirname(e);){let t=re.join(e,"package.json");if(Ce.existsSync(t))try{if(JSON.parse(Ce.readFileSync(t,"utf8")).workspaces)return e}catch{}e=re.dirname(e)}return null}import ye from"path";import pe from"fs";function mn(i,e){let t=new Map,n=e.workspaces||[];for(let s of n){let r=s.replace("/*",""),o=ye.join(i,r);if(!pe.existsSync(o))continue;let l=pe.readdirSync(o);for(let c of l){let a=ye.join(o,c,"package.json");if(pe.existsSync(a))try{let u=JSON.parse(pe.readFileSync(a,"utf8"));u.name&&t.set(u.name,{name:u.name,path:ye.dirname(a),main:u.main||"dist/index.js"})}catch{}}}return t}function fn(i){let e=new Map;try{let t=JSON.parse(pe.readFileSync(i,"utf8")),n={...t.dependencies,...t.devDependencies};for(let[s,r]of Object.entries(n))if(typeof r=="string"&&r.startsWith("file:")){let o=r.substring(5),l=ye.dirname(i),c=ye.resolve(l,o),a=ye.join(c,"package.json");if(pe.existsSync(a))try{let u=JSON.parse(pe.readFileSync(a,"utf8"));e.set(s,{name:s,path:c,main:u.main||"dist/index.js"})}catch{}}}catch{}return e}import hn from"path";import G from"fs";var gi=[".ts",".tsx",".d.ts",".js",".jsx"];function ae(i){let e=hn.extname(i);if(e===".js"||e===".jsx"){let t=i.slice(0,-e.length),n=e===".jsx"?[".tsx",".ts"]:[".ts",".tsx"];for(let s of n){let r=t+s;if(G.existsSync(r)&&G.statSync(r).isFile())return r}if(G.existsSync(i)&&G.statSync(i).isFile())return i}if(G.existsSync(i)&&G.statSync(i).isFile())return i;for(let t of gi){let n=i+t;if(G.existsSync(n)&&G.statSync(n).isFile())return n}if(G.existsSync(i)&&G.statSync(i).isDirectory())for(let t of[".ts",".tsx",".js",".jsx"]){let n=hn.join(i,"index"+t);if(G.existsSync(n))return n}return""}var Qe=new Map;function Ye(i){let e=pn(i);if(!e)return null;if(Qe.has(e))return Qe.get(e)||null;let t=yi(e);if(t.resultType==="failed")return Qe.set(e,null),null;let n=t,s=n.absoluteBaseUrl;!s&&n.paths&&Object.keys(n.paths).length>0&&(s=n.configFileAbsolutePath?K.dirname(n.configFileAbsolutePath):e);let r=Ei(s,n.paths,n.mainFields,n.addMatchAll),o=dn(e),l=new Map;if(o){let p=K.join(o,"package.json");if(Ee.existsSync(p))try{let m=JSON.parse(Ee.readFileSync(p,"utf8"));l=mn(o,m)}catch{}}let c=K.join(e,"package.json");Ee.existsSync(c)&&fn(c).forEach((m,d)=>l.set(d,m));let a={baseUrl:s||"",paths:n.paths,matchPath:r,workspacePackages:l,imports:new Map},u=K.join(e,"package.json");if(Ee.existsSync(u))try{let p=JSON.parse(Ee.readFileSync(u,"utf8"));if(p.imports){for(let[m,d]of Object.entries(p.imports))if(typeof d=="string"||typeof d=="object"&&d!==null){let f=d;Array.isArray(d)&&(f=d[0]),typeof f=="object"&&(f=f.default||f.node),typeof f=="string"&&a.imports.set(m,f)}}}catch{}return Qe.set(e,a),a}function Ne(i,e,t){if(!i)return"";if(i.includes(".")&&!i.startsWith(".")&&!i.startsWith("/")&&!i.endsWith(".js")&&!i.endsWith(".ts")&&!i.endsWith(".json")){let s=i.split(".")[0];if(s&&s!==i){let r=Ne(s,e,t);if(r)return r}}if(i.startsWith(".")){let s=K.dirname(e),r=K.resolve(s,i);return ae(r)}let n=Ye(e);if(n){let s=n.matchPath(i);if(s)return ae(s);if(!i.startsWith("@")||i.startsWith("@/")){let o=K.resolve(n.baseUrl,i),l=ae(o);if(l)return l}for(let[o,l]of n.imports.entries())if(o.includes("*")){let c="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",a=new RegExp(c),u=i.match(a);if(u){let p=u[1],m=l.replace("*",p),d=K.resolve(n.baseUrl,m);return ae(d)}}else if(o===i){let c=K.resolve(n.baseUrl,l);return ae(c)}let r=n.workspacePackages.get(i);if(r){let o=K.join(r.path,"src/index.ts");if(Ee.existsSync(o))return o;let l=K.join(r.path,r.main),c=ae(l);if(c)return c}}return""}import bi from"fs";import _i from"path";import yn from"js-yaml";function gn(i){let e=_i.basename(i),t=bi.readFileSync(i,"utf8"),n=[];if(e.endsWith(".prisma"))return{...ki(t,i),content:t};if(e.endsWith(".graphql")||e.endsWith(".gql"))return{...xi(t,i),content:t};let s="Configuration";return e==="lerna.json"?{...Li(t,i),content:t}:e==="turbo.json"?{...vi(t,i),content:t}:e==="pnpm-workspace.yaml"?{...Ci(t,i),content:t}:(e.includes("Dockerfile")?(s="Infrastructure (Docker) ",Ri(t,n)):e.endsWith(".yaml")||e.endsWith(".yml")?(s="Infrastructure (YAML) ",Ti(t,n)):e.startsWith(".env")?(s="Configuration (Env) ",Si(t,n)):e==="package.json"&&(s="Project Manifest",Ii(t,n)),{configs:n,classification:s,content:t})}function Ri(i,e){let t=i.split(`
49
+ `);for(let n of t){let s=n.trim();if(s.startsWith("FROM "))e.push({key:"base_image",value:s.substring(5).trim(),kind:"Image"});else if(s.startsWith("EXPOSE "))e.push({key:"port",value:s.substring(7).trim(),kind:"Port"});else if(s.startsWith("ENV ")){let r=s.substring(4).trim().split(/\s+|=/);if(r[0]){let o=r[0],l=r.slice(1).join("= ").trim()||"undefined",c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function Ti(i,e){try{let t=yn.load(i);if(!t||typeof t!="object")return;if(t.services&&typeof t.services=="object")for(let[s,r]of Object.entries(t.services)){if(!r||typeof r!="object")continue;let o=r;if(e.push({key:`service:${s}`,value:s,kind:"Service"}),o.image&&e.push({key:`service:${s}:image`,value:String(o.image),kind:"Image"}),Array.isArray(o.ports)&&o.ports.forEach(l=>{e.push({key:`service:${s}:port`,value:String(l),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(l=>{let[c,...a]=l.split("= ");c&&a.length>0&&e.push({key:`service:${s}:env:${c}`,value:a.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[l,c]of Object.entries(o.environment))e.push({key:`service:${s}:env:${l}`,value:String(c),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(l=>{e.push({key:`service:${s}:depends_on`,value:l,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let l of Object.keys(o.depends_on))e.push({key:`service:${s}:depends_on`,value:l,kind:"Dependency"})}let n=(s,r="")=>{if(!(!s||typeof s!="object"||Array.isArray(s)))for(let[o,l]of Object.entries(s)){let c=r?`${r}.${o}`:o;if(t.services&&(c.startsWith("services.")||c==="services")){l&&typeof l=="object"&&!Array.isArray(l)&&n(l,c);continue}if(l&&typeof l=="object"&&!Array.isArray(l))n(l,c);else{let a=String(l),u="Env";o.toLowerCase().includes("image")&&(u="Image"),o.toLowerCase().includes("port")&&(u="Port"),o.toLowerCase().includes("service")&&(u="Service"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(u="Service"),e.push({key:c,value:a.length>100?a.substring(0,97)+"...":a,kind:u})}}};n(t)}catch{let n=i.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(s=>{let r=s.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function Si(i,e){let t=i.split(`
50
+ `);for(let n of t){let s=n.trim();if(s&&!s.startsWith("#")){let r=s.split("=");if(r[0]){let o=r[0].trim(),l=r.slice(1).join("=");l=l.trim().replace(/^['"](.*)['"]$/,"$1");let c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function ki(i,e){let t=[],n="Contract (Prisma) ",s=/^model\s+(\w+)/gm,r;for(;(r=s.exec(i))!==null;)t.push({key:"model",value:r[1],kind:"Database Model"});let o=/^enum\s+(\w+)/gm;for(;(r=o.exec(i))!==null;)t.push({key:"enum",value:r[1],kind:"Database Enum"});let l=/provider\s*=\s*"([^"]+)"/,c=i.match(l);return c&&t.push({key:"datasource_provider",value:c[1],kind:"Database Config"}),{classification:n,configs:t,content:i}}function xi(i,e){let t=[],n="Contract (GraphQL) ",s=/^(?:type|input|interface|enum)\s+(\w+)/gm,r;for(;(r=s.exec(i))!==null;){let o=r[0],l="GraphQL Type";o.startsWith("input")&&(l="GraphQL Input"),o.startsWith("interface")&&(l="GraphQL Interface"),o.startsWith("enum")&&(l="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:l})}return{classification:n,configs:t,content:i}}function Ii(i,e){try{let t=JSON.parse(i);if(t.name&&e.push({key:"name",value:t.name,kind:"Service"}),t.description&&e.push({key:"description",value:t.description,kind:"Service"}),t.workspaces){let r=Array.isArray(t.workspaces)?t.workspaces.join("",""):JSON.stringify(t.workspaces);e.push({key:"workspaces",value:r,kind:"Env"})}if(t.scripts){let r=["start","dev","build","test","docker"];for(let o of Object.keys(t.scripts))r.some(l=>o.includes(l))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},s=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(s.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Service"})}}catch{}}function Li(i,e){let t=[],n="Monorepo (Lerna) ";try{let s=JSON.parse(i);t.push({key:"monorepo_type",value:"lerna",kind:"Monorepo"}),s.version&&t.push({key:"lerna_version",value:s.version,kind:"Monorepo"}),s.packages&&(Array.isArray(s.packages)?s.packages:[s.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})}),s.npmClient&&t.push({key:"npm_client",value:s.npmClient,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:i}}function vi(i,e){let t=[],n="Monorepo (Turborepo) ";try{let s=JSON.parse(i);if(t.push({key:"monorepo_type",value:"turborepo",kind:"Monorepo"}),s.pipeline)for(let r of Object.keys(s.pipeline)){t.push({key:`pipeline:${r}`,value:r,kind:"Monorepo"});let o=s.pipeline[r];o.dependsOn&&t.push({key:`pipeline:${r}:depends_on`,value:o.dependsOn.join("",""),kind:"Dependency"})}if(s.tasks)for(let r of Object.keys(s.tasks))t.push({key:`task:${r}`,value:r,kind:"Monorepo"})}catch{}return{configs:t,classification:n,content:i}}function Ci(i,e){let t=[],n="Monorepo (pnpm) ";try{let s=yn.load(i);t.push({key:"monorepo_type",value:"pnpm",kind:"Monorepo"}),s&&s.packages&&(Array.isArray(s.packages)?s.packages:[s.packages]).forEach(o=>{t.push({key:"package_glob",value:o,kind:"Monorepo"})})}catch{}return{configs:t,classification:n,content:i}}j();import En from"fs";import Ni from"path";import bn from"js-yaml";var _n={ignore:[],include:[],maxDepth:10},Di=[{name:".liquid-shadow.yaml",parse:i=>bn.load(i)??{}},{name:".liquid-shadow.yml",parse:i=>bn.load(i)??{}},{name:".ls.json",parse:i=>JSON.parse(i)},{name:".liquid-shadow.json",parse:i=>JSON.parse(i)},{name:".ls.rc",parse:i=>JSON.parse(i)},{name:".liquid-shadow.rc",parse:i=>JSON.parse(i)}];function Ve(i){for(let{name:e,parse:t}of Di){let n=Ni.join(i,e);if(En.existsSync(n))try{let s=En.readFileSync(n,"utf8"),r=t(s);return E.debug({repoPath:i,configFile:e},"Loaded repository configuration"),{..._n,...r}}catch(s){E.error({repoPath:i,file:e,err:s},"Failed to parse configuration file")}}return _n}import Mi from"path";var F=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 Xe=class extends F{findByPath(e){return this.get("SELECT * FROM files WHERE path = ?",e)}findAll(e){let t="SELECT * FROM files ORDER BY path ASC";return e&&(t+=` LIMIT ${e}`),this.all(t)}getAllPaths(){return this.all("SELECT path FROM files").map(t=>t.path)}findInSubPath(e,t){let n=Mi.resolve(e,t),s=n.endsWith("/")?n:n+"/";return this.all(`
60
51
  SELECT * FROM files
61
52
  WHERE (path LIKE ? OR path = ?)
62
53
  ORDER BY path ASC
@@ -80,7 +71,7 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
80
71
  AND file_path NOT LIKE '%.spec.%'
81
72
  LIMIT ?
82
73
  `,`"${e.replace(/[^a-zA-Z0-9_\/]/g," ")}"`,t).map(s=>s.file_path)}findSynapses(e){let t="SELECT * FROM event_synapses WHERE 1=1",n=[];if(e.type&&(t+=" AND type = ?",n.push(e.type)),e.name){let s=e.name;s.startsWith("/")&&(s=s.substring(1)),s.endsWith("/")&&(s=s.substring(0,s.length-1)),s.length>0&&(t+=" AND (name LIKE ? OR name LIKE ? OR name = ?)",n.push(`${s}%`),n.push(`%/${s}%`),n.push(e.name))}return e.direction&&(t+=" AND direction = ?",n.push(e.direction)),t+=` LIMIT ${e.limit||50}`,this.all(t,...n)}exists(e){return!!this.get("SELECT 1 FROM files WHERE path = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let s=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE files SET ${s} WHERE path = ?`,...r)}getStats(){let e=this.get(`
83
- SELECT
74
+ SELECT
84
75
  COUNT(*) as total,
85
76
  SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
86
77
  FROM files
@@ -93,14 +84,14 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
93
84
  OR m.id IN (${e.length>0?e.join(","):"-1"})
94
85
  )
95
86
  AND ws.file_path IS NOT NULL
96
- `,r=[];t&&r.push(t);let o=this.all(s,...r);for(let a of o){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let p=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.file_path].score+=p;let d=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.file_path].reasons.push(`${d}: ${a.mission_name}`)}let c=Math.floor(Date.now()/1e3)-86400,l=this.all(`
87
+ `,r=[];t&&r.push(t);let o=this.all(s,...r);for(let a of o){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let u=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.file_path].score+=u;let p=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.file_path].reasons.push(`${p}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
97
88
  SELECT file_path, type, mission_id
98
89
  FROM intent_logs
99
90
  WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
100
91
  AND file_path IS NOT NULL
101
92
  ORDER BY created_at DESC
102
93
  LIMIT 100
103
- `,c);for(let a of l){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let p=a.mission_id?e.includes(a.mission_id):!1,d=p?.1:.2;n[a.file_path].score<5&&(n[a.file_path].score+=d);let m=p?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.file_path].reasons.includes(m)&&n[a.file_path].reasons.length<5&&n[a.file_path].reasons.push(m)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
94
+ `,l);for(let a of c){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let u=a.mission_id?e.includes(a.mission_id):!1,p=u?.1:.2;n[a.file_path].score<5&&(n[a.file_path].score+=p);let m=u?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.file_path].reasons.includes(m)&&n[a.file_path].reasons.length<5&&n[a.file_path].reasons.push(m)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
104
95
  SELECT
105
96
  SUBSTR(path, LENGTH(?) + 2,
106
97
  INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
@@ -118,13 +109,13 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
118
109
  ORDER BY total_files DESC
119
110
  LIMIT ?
120
111
  `,e,e,e,t)}hasFilesPattern(e){return!!this.get("SELECT 1 FROM files WHERE path LIKE ? LIMIT 1",e)}findPackageJsonChildren(e){return this.all(`
121
- SELECT
112
+ SELECT
122
113
  path,
123
114
  SUBSTR(path, LENGTH(?) + 2) as relPath
124
- FROM files
115
+ FROM files
125
116
  WHERE path LIKE ? || '/%/package.json'
126
- `,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(s=>{for(let r of s)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,s){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),c=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),l=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),a=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),p=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),f=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),g=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),E=this.db.prepare(`
127
- INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
117
+ `,e,e)}deletePaths(e){if(e.length===0)return;let t=this.db.prepare("DELETE FROM files WHERE path = ?");this.db.transaction(s=>{for(let r of s)t.run(r)})(e)}updateMtime(e,t){this.run("UPDATE files SET mtime = ? WHERE path = ?",t,e)}batchSaveIndexResults(e,t,n,s){let r=this.db.prepare("DELETE FROM exports WHERE file_path = ?"),o=this.db.prepare("DELETE FROM imports WHERE file_path = ?"),l=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),a=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),u=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 (?, ?, ?, ?)"),m=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),f=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),g=this.db.prepare(`
118
+ INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
128
119
  VALUES (?, ?, ?, ?, ?, ?, ?)
129
120
  ON CONFLICT(path) DO UPDATE SET
130
121
  mtime=excluded.mtime,
@@ -133,7 +124,7 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
133
124
  summary=excluded.summary,
134
125
  embedding=excluded.embedding,
135
126
  content_hash=excluded.content_hash
136
- `);this.db.transaction(u=>{for(let h of u){let{meta:b,exports:M,imports:C,configs:I,events:v,content:$,classification:N,summary:R,embedding:S}=h;r.run(b.path),o.run(b.path),c.run(b.path),l.run(b.path),a.run(b.path);let w=$?n($):null;if(E.run(b.path,b.mtime,Date.now(),N||"Unknown",R||"",S?JSON.stringify(S):null,w),M){let D=(j,Q,V)=>{for(let F of Q){let k=F.embedding?JSON.stringify(F.embedding):null,x=p.run(j,F.name,F.kind,F.signature,F.doc||"",F.line,F.endLine||F.line,F.classification||"Other",F.capabilities||"[]",V,k);F.members&&F.members.length>0&&D(j,F.members,x.lastInsertRowid)}};D(b.path,M,null)}if(C)for(let D of C){let j=s(D.module,b.path,t);d.run(b.path,D.module,D.name,j)}if(I)for(let D of I)m.run(b.path,D.key,D.value,D.kind);if($!==void 0&&f.run(b.path,$),v)for(let D of v)g.run(b.path,D.type,D.name,D.direction,D.line,D.snippet)}})(e)}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}};var qe=class extends P{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(`
127
+ `),b=this.db.transaction(y=>{for(let T of y){let{meta:_,exports:x,imports:I,configs:D,events:z,content:w,classification:N,summary:v,embedding:$,contentHash:U}=T;r.run(_.path),o.run(_.path),l.run(_.path),c.run(_.path),a.run(_.path);let ne=U??(w&&n?n(w):null);if(g.run(_.path,_.mtime,Date.now(),N||"Unknown",v||"",$?JSON.stringify($):null,ne),x){let S=(M,P,C)=>{for(let R of P){let W=R.embedding?JSON.stringify(R.embedding):null,J=u.run(M,R.name,R.kind,R.signature,R.doc||"",R.line,R.endLine||R.line,R.classification||"Other",R.capabilities||"[]",C,W);R.members&&R.members.length>0&&S(M,R.members,J.lastInsertRowid)}};S(_.path,x,null)}if(I)for(let S of I){let M=S.resolved_path!==void 0?S.resolved_path:s?.(S.module,_.path,t)??"";p.run(_.path,S.module,S.name,M)}if(D)for(let S of D)m.run(_.path,S.key,S.value,S.kind);if(w!==void 0&&d.run(_.path,w),z)for(let S of z)f.run(_.path,S.type,S.name,S.direction,S.line,S.snippet)}}),h=500;for(let y=0;y<e.length;y+=h)b(e.slice(y,y+h))}getLatestScanTime(){return this.get("SELECT MAX(last_scanned_at) as t FROM files")?.t||null}};var Ze=class extends F{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(`
137
128
  SELECT * FROM exports
138
129
  WHERE file_path = ? AND start_line <= ? AND end_line >= ?
139
130
  ORDER BY (end_line - start_line) ASC -- Get innermost symbol
@@ -215,16 +206,16 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
215
206
  WHERE file_path = ? AND parent_id IS NULL
216
207
  ORDER BY start_line ASC
217
208
  `,e)}findFts(e,t=20){return this.all(`
218
- SELECT e.*
209
+ SELECT e.*
219
210
  FROM exports e
220
- JOIN exports_fts ef ON e.id = ef.rowid
221
- WHERE ef MATCH ?
211
+ JOIN exports_fts ON e.id = exports_fts.rowid
212
+ WHERE exports_fts MATCH ?
222
213
  LIMIT ?
223
214
  `,e,t)}findByPartialName(e,t=20){return this.all(`
224
215
  SELECT * FROM exports
225
216
  WHERE lower(name) LIKE ?
226
217
  LIMIT ?
227
- `,`%${e.toLowerCase()}%`,t)}getAllNames(e=5e3){return this.all("SELECT DISTINCT name FROM exports WHERE parent_id IS NULL LIMIT ?",e).map(n=>n.name)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM exports WHERE file_path = ?",e)?.count||0}findDeadExports(e=50,t=!1){let n=t?"":"AND e.file_path NOT LIKE '%/test/%' AND e.file_path NOT LIKE '%/__tests__/%' AND e.file_path NOT LIKE '%.spec.%' AND e.file_path NOT LIKE '%.test.%'";return this.all(`
218
+ `,`%${e.toLowerCase()}%`,t)}getAllNames(e=5e3){return this.all("SELECT DISTINCT name FROM exports WHERE parent_id IS NULL LIMIT ?",e).map(n=>n.name)}countByFile(e){return this.get("SELECT COUNT(*) as count FROM exports WHERE file_path = ?",e)?.count||0}findDeadExports(e={}){let{limit:t=50,includeTests:n=!1,includeMigrations:s=!1,includeFixtures:r=!1,excludePatterns:o=[],confidenceThreshold:l="all"}=e,c=[];n||(c.push("e.file_path NOT LIKE '%/test/%'"),c.push("e.file_path NOT LIKE '%/tests/%'"),c.push("e.file_path NOT LIKE '%/__tests__/%'"),c.push("e.file_path NOT LIKE '%.spec.%'"),c.push("e.file_path NOT LIKE '%.test.%'")),s||(c.push("e.file_path NOT LIKE '%/migrations/%'"),c.push("e.file_path NOT LIKE '%/migration/%'"),c.push("e.file_path NOT LIKE '%Migration.%'")),r||(c.push("e.file_path NOT LIKE '%/__fixtures__/%'"),c.push("e.file_path NOT LIKE '%/__mocks__/%'"),c.push("e.file_path NOT LIKE '%/fixtures/%'"),c.push("e.file_path NOT LIKE '%/mocks/%'"),c.push("e.file_path NOT LIKE '%.fixture.%'"),c.push("e.file_path NOT LIKE '%.mock.%'"));for(let d of o){let f=d.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");c.push(`e.file_path NOT LIKE '${f}'`)}let a=c.length>0?`AND ${c.join(" AND ")}`:"",p=this.all(`
228
219
  SELECT e.name, e.kind, e.file_path, e.start_line
229
220
  FROM exports e
230
221
  WHERE e.kind IN (
@@ -233,12 +224,12 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
233
224
  'ArrowFunctionExpression', 'FunctionExpression'
234
225
  )
235
226
  AND e.parent_id IS NULL
236
- ${n}
227
+ ${a}
237
228
  AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.imported_symbols LIKE '%' || e.name || '%')
238
229
  AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
239
230
  ORDER BY e.file_path, e.start_line
240
231
  LIMIT ?
241
- `,e)}getGravityMap(e=[],t){let n={},s=`
232
+ `,t*2).map(d=>{let{confidence:f,reason:g}=this.scoreDeadExportConfidence(d);return{...d,confidence:f,reason:g}}),m=p;return l==="high"?m=p.filter(d=>d.confidence==="high"):l==="medium"&&(m=p.filter(d=>d.confidence==="high"||d.confidence==="medium")),m.slice(0,t)}scoreDeadExportConfidence(e){let t=e.file_path.toLowerCase(),n=e.name;return t.includes("/index.")||t.endsWith("index.ts")||t.endsWith("index.js")?{confidence:"low",reason:"Barrel/index file - likely re-export"}:e.kind==="TsInterfaceDeclaration"||e.kind==="TsTypeAliasDeclaration"?{confidence:"medium",reason:"Type definition - may be used externally"}:t.includes("/entry/")||t.includes("/bin/")||t.includes("main.")||t.includes("server.")||t.includes("cli.")?{confidence:"medium",reason:"Entry point - may be invoked externally"}:n.startsWith("create")||n.endsWith("Factory")||n.endsWith("Builder")?{confidence:"medium",reason:"Factory/builder pattern - may be used dynamically"}:n.startsWith("use")&&n.length>3?{confidence:"medium",reason:"Hook pattern - may be used in components"}:{confidence:"high",reason:"No detected usage"}}getGravityMap(e=[],t){let n={},s=`
242
233
  SELECT ws.symbol_id, m.name as mission_name, m.status
243
234
  FROM working_set ws
244
235
  JOIN missions m ON ws.mission_id = m.id
@@ -247,14 +238,14 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
247
238
  OR m.id IN (${e.length>0?e.join(","):"-1"})
248
239
  )
249
240
  AND ws.symbol_id IS NOT NULL
250
- `,r=[];t&&r.push(t);let o=this.all(s,...r);for(let a of o){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let p=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.symbol_id].score+=p;let d=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.symbol_id].reasons.push(`${d}: ${a.mission_name}`)}let c=Math.floor(Date.now()/1e3)-86400,l=this.all(`
241
+ `,r=[];t&&r.push(t);let o=this.all(s,...r);for(let a of o){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let u=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.symbol_id].score+=u;let p=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.symbol_id].reasons.push(`${p}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
251
242
  SELECT symbol_id, type, mission_id
252
243
  FROM intent_logs
253
244
  WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
254
245
  AND symbol_id IS NOT NULL
255
246
  ORDER BY created_at DESC
256
247
  LIMIT 200
257
- `,c);for(let a of l){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let p=a.mission_id?e.includes(a.mission_id):!1,d=p?.1:.2;n[a.symbol_id].score<5&&(n[a.symbol_id].score+=d);let m=p?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.symbol_id].reasons.includes(m)&&n[a.symbol_id].reasons.length<5&&n[a.symbol_id].reasons.push(m)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
248
+ `,l);for(let a of c){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let u=a.mission_id?e.includes(a.mission_id):!1,p=u?.1:.2;n[a.symbol_id].score<5&&(n[a.symbol_id].score+=p);let m=u?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.symbol_id].reasons.includes(m)&&n[a.symbol_id].reasons.length<5&&n[a.symbol_id].reasons.push(m)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
258
249
  SELECT kind, COUNT(*) as c
259
250
  FROM exports
260
251
  WHERE kind IS NOT NULL AND kind != ''
@@ -267,7 +258,7 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
267
258
  OR name LIKE ?
268
259
  OR name LIKE ?
269
260
  LIMIT 10
270
- `,e,`%.${e}`,`%::${e}`)}};var ln=`
261
+ `,e,`%.${e}`,`%::${e}`)}};var Rn=`
271
262
  WITH RECURSIVE dependency_chain AS (
272
263
  -- Base case: Direct dependents of the target symbol
273
264
  -- Meaning: Files that import the file where the symbol is defined
@@ -302,7 +293,14 @@ WITH RECURSIVE dependency_chain AS (
302
293
  FROM imports i
303
294
  JOIN dependency_chain dc ON i.resolved_path = dc.consumer_path
304
295
  WHERE dc.depth < ? -- Max depth limit
305
- AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection: ensure we haven't visited this file in this chain
296
+ AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection
297
+ AND (
298
+ -- If the intermediate file is a re-exporter (barrel),
299
+ -- the next consumer must still be looking for the symbol
300
+ i.imported_symbols LIKE ?
301
+ OR i.imported_symbols = '*'
302
+ OR i.imported_symbols = ''
303
+ )
306
304
  )
307
305
  SELECT DISTINCT
308
306
  dc.consumer_path,
@@ -311,7 +309,7 @@ SELECT DISTINCT
311
309
  dc.imported_symbols
312
310
  FROM dependency_chain dc
313
311
  ORDER BY dc.depth, dc.consumer_path;
314
- `;var Ge=class extends P{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(`
312
+ `;var et=class extends F{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(`
315
313
  SELECT * FROM imports
316
314
  WHERE resolved_path IS NOT NULL AND resolved_path != ''
317
315
  `)}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(`
@@ -337,7 +335,7 @@ ORDER BY dc.depth, dc.consumer_path;
337
335
  SELECT COUNT(*) as count FROM imports
338
336
  WHERE resolved_path IN (${n})
339
337
  AND (imported_symbols LIKE ? OR imported_symbols = '' OR imported_symbols = '*')
340
- `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(ln,e,t,n)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}};var ze=class extends P{findById(e){return this.get("SELECT * FROM missions WHERE id = ?",e)}findByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM missions WHERE id IN (${t})`,...e)}findActive(e){let t="SELECT * FROM missions WHERE status IN ('in-progress', 'planned', 'verifying')",n=[];return e&&(t+=" AND git_branch = ?",n.push(e)),t+=` ORDER BY
338
+ `,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(Rn,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}};var tt=class extends F{findById(e){return this.get("SELECT * FROM missions WHERE id = ?",e)}findByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM missions WHERE id IN (${t})`,...e)}findActive(e){let t="SELECT * FROM missions WHERE status IN ('in-progress', 'planned', 'verifying')",n=[];return e&&(t+=" AND git_branch = ?",n.push(e)),t+=` ORDER BY
341
339
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
342
340
  created_at ASC`,this.all(t,...n)}findAll(e){let t="SELECT * FROM missions",n=[];return e&&(t+=" WHERE status = ?",n.push(e)),t+=` ORDER BY
343
341
  CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
@@ -358,7 +356,7 @@ ORDER BY dc.depth, dc.consumer_path;
358
356
  GROUP BY m.id
359
357
  HAVING log_count > ?
360
358
  `,e,t).map(s=>s.id)}getStats(){let e=this.get(`
361
- SELECT
359
+ SELECT
362
360
  COUNT(*) as total,
363
361
  SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
364
362
  SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
@@ -367,7 +365,7 @@ ORDER BY dc.depth, dc.consumer_path;
367
365
  SELECT AVG(updated_at - created_at) AS avg_duration
368
366
  FROM missions
369
367
  WHERE status = 'completed' AND updated_at > created_at
370
- `),s=n?.avg_duration!=null?Math.round(n.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,o=Math.floor(Date.now()/1e3)-720*3600,c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),l=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),a=c?.n??0,p=l?.n??0,d=`${a} completed in last 7 days, ${p} in last 30 days.`;if(s!=null){let m=Math.round(s/60);d+=` Avg mission duration: ${m} min.`}return{completionRate:t,averageDurationSeconds:s,completedLast7Days:a,completedLast30Days:p,velocityNote:d}}suspendByBranch(e){this.run(`UPDATE missions
368
+ `),s=n?.avg_duration!=null?Math.round(n.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,o=Math.floor(Date.now()/1e3)-720*3600,l=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),a=l?.n??0,u=c?.n??0,p=`${a} completed in last 7 days, ${u} in last 30 days.`;if(s!=null){let m=Math.round(s/60);p+=` Avg mission duration: ${m} min.`}return{completionRate:t,averageDurationSeconds:s,completedLast7Days:a,completedLast30Days:u,velocityNote:p}}suspendByBranch(e){this.run(`UPDATE missions
371
369
  SET status = 'suspended', updated_at = unixepoch()
372
370
  WHERE git_branch = ? AND status IN ('in-progress', 'planned', 'verifying')`,e)}resumeByBranch(e){this.run(`UPDATE missions
373
371
  SET status = 'in-progress', updated_at = unixepoch()
@@ -392,7 +390,7 @@ ORDER BY dc.depth, dc.consumer_path;
392
390
  SELECT linked_repo_path, linked_mission_id, relationship, direction
393
391
  FROM cross_repo_links
394
392
  WHERE mission_id = ?
395
- `,e)}catch{return[]}}findLastMission(){return this.get("SELECT * FROM missions ORDER BY updated_at DESC, id DESC LIMIT 1")}findActiveByPriority(){return this.get("SELECT * FROM missions WHERE status IN ('in-progress', 'active', 'verifying') ORDER BY CASE WHEN status = 'in-progress' THEN 0 ELSE 1 END, created_at ASC LIMIT 1")}};var Je=class extends P{findByMission(e,t=50){return this.all(`
393
+ `,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")}};j();var st=class i extends F{findByMission(e,t=50){return this.all(`
396
394
  SELECT * FROM intent_logs
397
395
  WHERE mission_id = ?
398
396
  ORDER BY created_at DESC
@@ -402,10 +400,10 @@ ORDER BY dc.depth, dc.consumer_path;
402
400
  WHERE type IN ('decision', 'system', 'fix', 'heritage', 'adr')
403
401
  ORDER BY created_at DESC
404
402
  LIMIT ?
405
- `,e)}create(e){return this.insert(`
403
+ `,e)}create(e){let t=this.insert(`
406
404
  INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
407
405
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
408
- `,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha)}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let s=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${s} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
406
+ `,e.mission_id,e.symbol_id,e.file_path,e.type,e.content,e.confidence,e.symbol_name,e.signature,e.commit_sha);return i.EMBEDDABLE_TYPES.has(e.type)&&this.generateAndStoreEmbedding(Number(t),e).catch(n=>{E.debug({err:n,intentLogId:t},"Failed to generate intent log embedding")}),t}static EMBEDDABLE_TYPES=new Set(["decision","discovery","fix","blocker","heritage","crystal"]);static buildEmbeddingText(e){let t=[`[${e.type}]`];return e.symbol_name&&t.push(`symbol: ${e.symbol_name}`),e.file_path&&t.push(`file: ${e.file_path.split("/").pop()}`),t.push(e.content),t.join(" ")}async generateAndStoreEmbedding(e,t){let{generateEmbedding:n}=await Promise.resolve().then(()=>(we(),Lt)),s=i.buildEmbeddingText(t),r=await n(s);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')")}delete(e){this.run("DELETE FROM intent_logs WHERE id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let s=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE intent_logs SET ${s} WHERE id = ?`,...r)}findRepairableOrphans(){return this.all(`
409
407
  SELECT id, file_path, symbol_name, signature
410
408
  FROM intent_logs
411
409
  WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
@@ -430,24 +428,45 @@ ORDER BY dc.depth, dc.consumer_path;
430
428
  `,e)}importHeritage(e,t,n,s){this.run(`
431
429
  INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
432
430
  VALUES ('heritage', ?, ?, ?, ?, 0)
433
- `,e,t,n,s)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}};var Ye=class extends P{findByKey(e,t=20){return this.all(`
431
+ `,e,t,n,s)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}findRawByMission(e){return this.all(`SELECT * FROM intent_logs
432
+ WHERE mission_id = ? AND is_crystallized = 0
433
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
434
+ ORDER BY created_at ASC`,e)}findCrystalByMission(e){return this.get(`SELECT * FROM intent_logs
435
+ WHERE mission_id = ? AND type = 'crystal'
436
+ ORDER BY created_at DESC LIMIT 1`,e)}crystallize(e,t){return this.transaction(()=>{let n=this.insert(`INSERT INTO intent_logs (mission_id, type, content, confidence, is_crystallized, symbol_id, file_path, symbol_name, signature, commit_sha)
437
+ VALUES (?, 'crystal', ?, 1.0, 0, NULL, NULL, NULL, NULL, NULL)`,e,t);return this.run(`UPDATE intent_logs
438
+ SET is_crystallized = 1, crystal_id = ?
439
+ WHERE mission_id = ? AND is_crystallized = 0 AND id != ?
440
+ AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')`,n,e,n),n})}countByMissions(e){if(e.length===0)return{};let t=e.map(()=>"?").join(","),n=this.all(`SELECT mission_id, COUNT(*) as cnt
441
+ FROM intent_logs
442
+ WHERE mission_id IN (${t})
443
+ AND type NOT IN ('system', 'adr', 'lapsed')
444
+ GROUP BY mission_id`,...e),s={};for(let r of n)s[r.mission_id]=r.cnt;return s}findMissionsWithBlockers(e){if(e.length===0)return new Set;let t=e.map(()=>"?").join(","),n=this.all(`SELECT DISTINCT mission_id
445
+ FROM intent_logs
446
+ WHERE mission_id IN (${t})
447
+ AND type = 'blocker'`,...e);return new Set(n.map(s=>s.mission_id))}findByMissionPreferCrystal(e,t=50){let n=this.findCrystalByMission(e);if(n){let s=this.all(`SELECT * FROM intent_logs
448
+ WHERE mission_id = ? AND is_crystallized = 0 AND type NOT IN ('adr', 'system', 'crystal', 'lapsed')
449
+ AND created_at > ?
450
+ ORDER BY created_at DESC LIMIT ?`,e,n.created_at,t-1);return[n,...s]}return this.findByMission(e,t)}async backfillEmbeddings(e=64,t){let{generateEmbeddingsBatch:n}=await Promise.resolve().then(()=>(we(),Lt)),s=[...i.EMBEDDABLE_TYPES].map(u=>`'${u}'`).join(","),r=this.all(`SELECT * FROM intent_logs WHERE embedding IS NULL AND type IN (${s})`);if(r.length===0)return 0;let o=r.map(u=>i.buildEmbeddingText(u)),l=await n(o,e,t),c=this.db.prepare("UPDATE intent_logs SET embedding = ? WHERE id = ?"),a=0;return this.transaction(()=>{for(let u=0;u<r.length;u++)l[u]&&(c.run(JSON.stringify(l[u]),r[u].id),a++)}),E.info({total:r.length,embedded:a},"Intent log embedding backfill complete"),a}};var rt=class extends F{findByKey(e,t=20){return this.all(`
434
451
  SELECT file_path, key, value, kind
435
452
  FROM configs
436
453
  WHERE key LIKE ? OR value LIKE ?
437
454
  LIMIT ?
438
- `,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",s=[];return e&&(n+=" WHERE kind = ?",s.push(e)),n+=" LIMIT ?",s.push(t),this.all(n,...s)}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 Ke=class extends P{search(e,t=10){return this.all(`
455
+ `,`%${e}%`,`%${e}%`,t)}findByKind(e,t=50){let n="SELECT key, value, kind, file_path FROM configs",s=[];return e&&(n+=" WHERE kind = ?",s.push(e)),n+=" LIMIT ?",s.push(t),this.all(n,...s)}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 ot=class extends F{search(e,t=10){return this.all(`
439
456
  SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
440
457
  FROM content_fts
441
458
  WHERE content_fts MATCH ?
442
459
  LIMIT ?
443
- `,e,t)}};var pn=500,Qe=class extends P{record(e,t,n=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,n),this.pruneIfNeeded()}findRecent(e=20){return this.all("SELECT id, query, mode, branch, created_at FROM search_history ORDER BY created_at DESC LIMIT ?",e)}findRecentByQueryPrefix(e,t=10){return e.trim()?this.all(`SELECT id, query, mode, branch, created_at FROM search_history
444
- 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)<=pn||this.run(`DELETE FROM search_history WHERE id NOT IN (
460
+ `,e,t)}};var Mn=500,at=class extends F{record(e,t,n=null){this.run("INSERT INTO search_history (query, mode, branch) VALUES (?, ?, ?)",e,t,n),this.pruneIfNeeded()}findRecent(e=20){return this.all("SELECT id, query, mode, branch, created_at FROM search_history ORDER BY created_at DESC LIMIT ?",e)}findRecentByQueryPrefix(e,t=10){return e.trim()?this.all(`SELECT id, query, mode, branch, created_at FROM search_history
461
+ 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)<=Mn||this.run(`DELETE FROM search_history WHERE id NOT IN (
445
462
  SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
446
- )`,pn)}};var Ve=class extends P{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(`
463
+ )`,Mn)}};var ct=class extends F{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(`
447
464
  INSERT INTO hologram_snapshot (section, data, updated_at)
448
465
  VALUES (?, ?, unixepoch())
449
466
  ON CONFLICT(section) DO UPDATE SET
450
467
  data = excluded.data,
451
468
  updated_at = excluded.updated_at
452
- `,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 ie=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=ue(e),o=t.files?.database,c=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!c)return t;this.repositoryCache.delete(e)}let n=ue(e),s={files:new Be(n),exports:new qe(n),imports:new Ge(n),missions:new ze(n),intentLogs:new Je(n),configs:new Ye(n),content:new Ke(n),searchHistory:new Qe(n),hologram:new Ve(n)};return this.repositoryCache.set(e,s),s}static closeInstance(e){this.repositoryCache.delete(e),Kt(e)}static clearCache(e){this.repositoryCache.delete(e)}};import{Worker as gi}from"node:worker_threads";import{cpus as yi}from"node:os";import{fileURLToPath as Ei}from"node:url";import{dirname as bi,join as un}from"node:path";import{existsSync as dn}from"node:fs";var fn=Ei(import.meta.url),mn=bi(fn);function _i(){if(fn.endsWith(".ts")){let e=un(mn,"worker.ts");if(dn(e))return e}let i=un(mn,"worker.js");return dn(i)?i:Ne("dist/logic/domain/embeddings/worker.js")}var Se=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,yi().length-1),this.cacheDir=e.cacheDir??"./.cache",this.initTimeout=e.initTimeout??6e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{_.info({numWorkers:this.numWorkers},"Initializing embedding worker pool");let t=new Promise((n,s)=>{e=setTimeout(()=>s(new Error(`Worker pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0,_.debug("Initialization completed but shutdown was requested");return}this.initialized=!0,_.info({numWorkers:this.workers.length},"Embedding worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=_i();_.debug({workerPath:e},"Resolved worker path");for(let t=0;t<this.numWorkers;t++)await this.createWorker(e,t),await new Promise(n=>setTimeout(n,50))}async createWorker(e,t){return new Promise((n,s)=>{let r=setTimeout(()=>{s(new Error(`Worker ${t} initialization timed out`))},this.initTimeout),o=new gi(e,{workerData:{cacheDir:this.cacheDir},execArgv:process.execArgv}),c={worker:o,busy:!1,currentTaskId:null};o.on("message",l=>{if(l.type==="ready"){if(clearTimeout(r),this.shutdownRequested){_.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(c),_.debug({workerIndex:t},"Worker ready"),n()}else l.type==="result"&&l.id?this.handleTaskComplete(c,l.id,l.embeddings||[]):l.type==="error"&&l.id&&this.handleTaskError(c,l.id,new Error(l.error||"Unknown error"))}),o.on("error",l=>{if(clearTimeout(r),_.error({err:l,workerIndex:t},"Worker error"),c.currentTaskId&&this.handleTaskError(c,c.currentTaskId,l),!this.initialized){s(l);return}let a=this.workers.indexOf(c);a!==-1&&this.workers.splice(a,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(p=>{_.error({err:p},"Failed to replace crashed worker")})}),o.on("exit",l=>{l!==0&&!this.shutdownRequested&&_.warn({workerIndex:t,code:l},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=32,n){if(this.initialized||await this.initialize(),e.length===0)return[];let s=[];for(let a=0;a<e.length;a+=t)s.push(e.slice(a,a+t));let r=new Array(s.length),o=0,c=s.map((a,p)=>new Promise((d,m)=>{let g={id:`task_${++this.taskIdCounter}`,texts:a,resolve:E=>{if(r[p]=E,o++,n){let y=Math.min(o*t,e.length);n(y,e.length)}d()},reject:E=>{if(r[p]=new Array(a.length).fill(null),o++,_.warn({err:E,chunkIndex:p},"Chunk embedding failed"),n){let y=Math.min(o*t,e.length);n(y,e.length)}d()}};this.taskQueue.push(g),this.processQueue()}));await Promise.all(c);let l=[];for(let a of r)l.push(...a);return _.info({total:e.length,successful:l.filter(a=>a!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),l}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}_.info({numWorkers:this.workers.length},"Shutting down embedding worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,_.info("Embedding worker pool shutdown complete")}},fe=null;function Ze(i){return fe||(fe=new Se(i)),fe}async function hn(){fe&&(await fe.shutdown(),fe=null)}var xe=null;async function Ri(){return xe||(xe=await import("@xenova/transformers"),xe.env.cacheDir="./.cache",xe.env.allowLocalModels=!1),xe}var gn=128,bt=!1;function Xe(i){bt=i,_.info({useWorkerThreads:i},"Worker thread mode updated")}var yt=null;async function yn(){return yt||(yt=(async()=>{_.info("Loading embedding model (all-MiniLM-L6-v2)...");let{pipeline:i}=await Ri();return await i("feature-extraction","Xenova/all-MiniLM-L6-v2")})()),yt}async function Ti(i){try{let t=await(await yn())(i,{pooling:"mean",normalize:!0});return Array.from(t.data)}catch(e){return _.error({err:e},"Failed to generate embedding"),null}}async function _t(i,e=gn,t){return i.length===0?[]:bt?Ze().generateEmbeddings(i,e,t):En(i,e,t)}async function En(i,e,t){let n=new Array(i.length).fill(null),s=await yn();for(let r=0;r<i.length;r+=e){let o=Math.min(r+e,i.length),c=i.slice(r,o);try{let l=await s(c,{pooling:"mean",normalize:!0}),[a,p]=l.dims;for(let d=0;d<a;d++){let m=d*p,f=m+p;n[r+d]=Array.from(l.data.slice(m,f))}}catch(l){_.error({err:l,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let a=0;a<c.length;a++)try{let p=c[a];if(!p||p.trim().length===0)continue;let d=await s(p,{pooling:"mean",normalize:!0});n[r+a]=Array.from(d.data)}catch{n[r+a]=null}}t&&t(o,i.length)}return _.debug({total:i.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function Si(i,e){let t=0,n=0,s=0;for(let r=0;r<i.length;r++)t+=i[r]*e[r],n+=i[r]*i[r],s+=e[r]*e[r];return t/(Math.sqrt(n)*Math.sqrt(s))}var Et=class{queue=[];processing=!1;results=new Map;enqueue(e){this.queue.push(e),this.queue.sort((t,n)=>n.priority-t.priority)}enqueueMany(e){this.queue.push(...e),this.queue.sort((t,n)=>n.priority-t.priority)}get size(){return this.queue.length}get isProcessing(){return this.processing}getResult(e){return this.results.get(e)}async processQueue(e=gn,t){if(this.processing)return _.warn("Queue processing already in progress"),this.results;this.processing=!0;let n=this.queue.length;try{bt?await this.processQueueParallel(e,n,t):await this.processQueueSequential(e,n,t)}finally{this.processing=!1}return this.results}async processQueueSequential(e,t,n){for(;this.queue.length>0;){let s=this.queue.splice(0,e),r=s.map(c=>c.text),o=await En(r,r.length);if(s.forEach((c,l)=>{this.results.set(c.id,o[l])}),n){let c=t-this.queue.length;n(c,t)}}}async processQueueParallel(e,t,n){let s=this.queue.splice(0),r=s.map(l=>l.text),c=await Ze().generateEmbeddings(r,e,(l,a)=>{n&&n(l,a)});s.forEach((l,a)=>{this.results.set(l.id,c[a])})}clear(){this.queue=[],this.results.clear()}};import{execSync as Rt}from"child_process";import bn from"path";import _n from"fs";function Ie(i){try{return _n.existsSync(bn.join(i,".git"))?Rt("git rev-parse HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}function Rn(i,e){try{if(!_n.existsSync(bn.join(i,".git")))return!0;let t=Ie(i);return!t||e&&e!==t&&Rt(`git diff --name-only ${e} ${t}`,{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()?!0:Rt("git status --porcelain",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim().length>0}catch{return!0}}import{execSync as Tn}from"child_process";var le=_.child({module:"nano-repair"}),et=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:s}=ie.getInstance(e);this.intentLogs=t,this.exports=n,this.missions=s,this.repoPath=e}detectAndRepairShifts(){let e=this.intentLogs.findRepairableOrphans();if(e.length===0)return{repaired:0,failed:0};le.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let s of e){let r=this.exports.findByNameAndFile(s.symbol_name,s.file_path);if(r.length>0){let c=r.find(l=>l.signature===s.signature)||r[0];this.intentLogs.update(s.id,{symbol_id:c.id}),le.info({logId:s.id,symbol:s.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(s.symbol_name);if(o.length>0){let c=o.filter(l=>l.file_path!==s.file_path);if(c.length>0){let l=c.find(a=>a.signature===s.signature)||c[0];this.intentLogs.update(s.id,{symbol_id:l.id,file_path:l.file_path}),le.info({logId:s.id,symbol:s.symbol_name,oldPath:s.file_path,newPath:l.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&le.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(){let e="HEAD";try{e=Tn("git rev-parse --abbrev-ref HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return{suspended:0,resumed:0,completed:0}}if(!e)return{suspended:0,resumed:0,completed:0};let t=this.missions.findActive(),n=0;for(let o of t)o.git_branch&&o.git_branch!==e&&(this.missions.updateStatus(o.id,"suspended"),le.info({missionId:o.id,branch:o.git_branch,current:e},"Context Pivot: Suspended mission"),n++);this.missions.resumeByBranch(e);let s=[];try{s=Tn(`git branch --merged "${e}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
453
- `).map(c=>c.trim().replace(/^\* /,"")).filter(c=>c&&c!==e)}catch{}let r=0;if(s.length>0){let o=this.missions.findMergedMissions(e,s);for(let c of o)this.missions.updateStatus(c.id,"completed"),le.info({missionId:c.id,branch:c.git_branch},"Merge Sentinel: Auto-completed mission"),r++}return(n>0||r>0)&&le.info({suspended:n,completed:r},"Git-Native Lifecycle Sync complete"),{suspended:n,resumed:-1,completed:r}}};var Bo=Ii.cpus().length||4,Li=Ce.DEFAULT_CONCURRENCY;async function St(i,e=Li,t=!1,n=!0,s){let r=ie.getInstance(i),o=r.files.database,c=je(i),l=c.concurrency??e;if(Ut(),!t&&Jt(i)){let u=Yt(i),h=Ie(i);if(u&&!Rn(i,u))return ut(),_.debug({repoPath:i,commit:h},"Index is current, skipping re-index (fast-path)"),o}$e(i);let a=r.files.findAll(),p=new Map(a.map(u=>[u.path,{mtime:u.mtime,hash:u.content_hash}])),d=Date.now();s?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let m=await it(i,c.ignore),f=new Map(m.map(u=>[u.path,u.mtime])),g=a.filter(u=>!f.has(u.path)).map(u=>u.path),E=a.length===0,y=[];if(t||E)y.push(...m);else{let u=m.filter(C=>{let I=p.get(C.path);return!I||I.mtime!==C.mtime}),h=Sn(l*4),b=u.map(C=>h(async()=>{let I=p.get(C.path);if(!I||!I.hash)return C;try{let v=await Tt.promises.readFile(C.path,"utf8");return zt(v,I.hash)?C:(r.files.updateMtime(C.path,C.mtime),null)}catch{return null}})),M=await Promise.all(b);y.push(...M.filter(C=>C!==null))}if(g.length===0&&y.length===0){if(ut(),E){let u=Ie(i);ht(i,u||void 0)}return o}if(E?_.info({totalFiles:m.length},"Starting initial repository indexing..."):_.info({toDelete:g.length,toProcess:y.length},"Syncing repository updates..."),g.length>0&&r.files.deletePaths(g),y.length>0){Bt(),n?Xe(!0):Xe(!1);let u=Sn(l),h=0,b=y.length,M=y.map(N=>u(async()=>{try{let R=xi.basename(N.path);if(/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/.test(R)){let w=await lt(N.path),D=Tt.readFileSync(N.path,"utf8");return h++,(h%50===0||h===b)&&_.info({completed:h,total:b},"Parsing files..."),s?.({phase:"parse",current:h,total:b,message:`Parsing ${R}`}),{meta:N,...w,content:D,embedding:null,kind:"code"}}else{let w=sn(N.path),D=Tt.readFileSync(N.path,"utf8");return h++,(h%50===0||h===b)&&_.info({completed:h,total:b},"Parsing configs..."),s?.({phase:"parse",current:h,total:b,message:`Parsing config ${R}`}),{meta:N,...w,content:D,embedding:null,kind:"config"}}}catch(R){return h++,_.error({path:N.path,error:R},"Failed to parse file"),{meta:N,exports:[],imports:[],content:"",kind:"error"}}}));_.info({total:b},"Phase 1: Parsing all files...");let C=Date.now(),I=(await Promise.all(M)).filter(Boolean),v=Date.now()-C;if(Fe("parse",v),_.info({count:I.length,time:`${(v/1e3).toFixed(1)}s`},"Phase 1 complete"),n){_.info("Phase 2: Generating file semantic embeddings..."),s?.({phase:"embed",current:0,total:I.length,message:"Generating embeddings..."});let N=Date.now(),R=[];if(I.forEach((w,D)=>{"summary"in w&&w.summary&&R.push({fileIdx:D,text:w.summary})}),R.length>0){_.info({count:R.length}," \u2192 Generating file summary embeddings...");let w=R.map(j=>j.text),D=await _t(w,128);R.forEach((j,Q)=>{I[j.fileIdx].embedding=D[Q]}),_.info({count:R.length}," \u2713 File summaries complete")}let S=Date.now()-N;Fe("embed",S),_.info({time:`${(S/1e3).toFixed(1)}s`},"Phase 2 complete")}s?.({phase:"persist",current:0,total:I.length,message:"Saving to database..."});let $=Date.now();r.files.batchSaveIndexResults(I,i,ft,gt),Fe("persist",Date.now()-$)}if(E||y.length>0){let u=Ie(i);ht(i,u||void 0)}return(y.length>0||g.length>0)&&new et(i).detectAndRepairShifts(),jt(Date.now()-d),s?.({phase:"complete",current:y.length,total:y.length,message:"Indexing complete"}),o}import xn from"path";import ki from"ignore";import In from"fs";async function Ci(i,e=Ce.DEFAULT_CONCURRENCY,t="detailed",n,s){_.info({repo:i,level:t,subPath:n},"Ensuring cache is up-to-date..."),await St(i,e);let{files:r,exports:o,imports:c}=ie.getInstance(i),l=n?r.findInSubPath(i,n):r.findAll(),a=je(i),p=ki(),d=xn.join(i,".gitignore");if(In.existsSync(d)&&p.add(In.readFileSync(d,"utf8")),a.ignore&&a.ignore.length>0&&p.add(a.ignore),p.add(ke),l=l.filter(h=>{let b=xn.relative(i,h.path);return!p.ignores(b)}),_.info({count:l.length},"Fetching data from DB..."),t==="lite"){let h=l.map(b=>({path:b.path,mtime:b.mtime}));return Ee(h,i,t,s)}if(t==="summaries"){let h=l.map(b=>({path:b.path,mtime:b.mtime,classification:b.classification||void 0,summary:b.summary||void 0}));return Ee(h,i,t,s)}let m=l.map(h=>h.path),f=o.findByFiles(m),g=t==="detailed"?c.findByFiles(m):[],E=new Map;for(let h of f){let b=E.get(h.file_path)||[];b.push(h),E.set(h.file_path,b)}let y=new Map;for(let h of g){let b=y.get(h.file_path)||[];b.push(h),y.set(h.file_path,b)}let u=l.map(h=>{let M=(E.get(h.path)||[]).map(I=>({name:I.name,kind:I.kind,signature:I.signature,line:I.start_line}));t==="structure"?M=M.map(I=>({name:I.name,kind:I.kind,line:I.line})):t==="signatures"&&(M=M.map(I=>({name:I.name,kind:I.kind,signature:I.signature,line:I.line})));let C=[];return t==="detailed"&&(C=(y.get(h.path)||[]).map(v=>({module:v.module_specifier,resolved_path:v.resolved_path}))),{path:h.path,mtime:h.mtime,classification:h.classification||void 0,summary:h.summary||void 0,exports:M,imports:C.length>0?C:void 0,chunks:[]}});return _.info({count:u.length},"Building hierarchical project tree..."),Ee(u,i,t,s)}export{Et as EmbeddingPriorityQueue,Se as EmbeddingWorkerPool,Ee as buildTree,Un as chunkFile,Si as cosineSimilarity,St as ensureCacheUpToDate,Ti as generateEmbedding,_t as generateEmbeddingsBatch,Ze as getDefaultPool,lt as parseFile,Ci as processRepo,it as scanRepo,Xe as setUseWorkerThreads,hn as shutdownDefaultPool};
469
+ `,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 ce=class{static repositoryCache=new Map;static getInstance(e){let t=this.repositoryCache.get(e);if(t){let r=ge(e),o=t.files?.database,l=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!l)return t;this.repositoryCache.delete(e)}let n=ge(e),s={files:new Xe(n),exports:new Ze(n),imports:new et(n),missions:new tt(n),intentLogs:new st(n),configs:new rt(n),content:new ot(n),searchHistory:new at(n),hologram:new ct(n)};return this.repositoryCache.set(e,s),s}static closeInstance(e){this.repositoryCache.delete(e),cn(e)}static clearCache(e){this.repositoryCache.delete(e)}};we();import{execSync as vt}from"child_process";import lt from"path";import On from"fs";function Oe(i){try{return On.existsSync(lt.join(i,".git"))?vt("git rev-parse HEAD",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim():null}catch{return null}}var Hi=new Set([".ts",".tsx",".yaml",".yml",".php",".py",".go",".prisma",".graphql",".gql"]),$i=new Set(["package.json","lerna.json","turbo.json","pnpm-workspace.yaml"]),Ui=new Set(["node_modules",".git","dist","build","vendor",".next",".cache","coverage"]);function wn(i){let e=i.split("/");for(let s of e)if(Ui.has(s))return!1;if(i.endsWith(".min.js"))return!1;let t=lt.basename(i);if(t.startsWith("Dockerfile")||t.startsWith(".env")||$i.has(t))return!0;let n=lt.extname(t).toLowerCase();return Hi.has(n)}function Bi(i){let e=i.trim(),t=e.indexOf(" -> ");if(t!==-1)return e.substring(t+4);let n=e.split(/\s+/);return n.length>=2?n[n.length-1]:e}function An(i,e){try{if(!On.existsSync(lt.join(i,".git")))return!0;let t=Oe(i);if(!t)return!0;if(e&&e!==t){let s=vt(`git diff --name-only ${e} ${t}`,{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();if(s&&s.split(`
470
+ `).some(r=>r&&wn(r)))return!0}let n=vt("git status --porcelain",{cwd:i,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim();return n?n.split(`
471
+ `).some(s=>s?wn(Bi(s)):!1):!1}catch{return!0}}import{execSync as Fn}from"child_process";j();var me=E.child({module:"nano-repair"}),ut=class{intentLogs;exports;missions;repoPath;constructor(e){let{intentLogs:t,exports:n,missions:s}=ce.getInstance(e);this.intentLogs=t,this.exports=n,this.missions=s,this.repoPath=e}detectAndRepairShifts(){let e=this.intentLogs.findRepairableOrphans();if(e.length===0)return{repaired:0,failed:0};me.info({count:e.length},"Detected orphaned intent logs. Attempting recovery...");let t=0,n=0;for(let s of e){let r=this.exports.findByNameAndFile(s.symbol_name,s.file_path);if(r.length>0){let l=r.find(c=>c.signature===s.signature)||r[0];this.intentLogs.update(s.id,{symbol_id:l.id}),me.info({logId:s.id,symbol:s.symbol_name},"Relinked symbol in same file"),t++;continue}let o=this.exports.findByNameGlobal(s.symbol_name);if(o.length>0){let l=o.filter(c=>c.file_path!==s.file_path);if(l.length>0){let c=l.find(a=>a.signature===s.signature)||l[0];this.intentLogs.update(s.id,{symbol_id:c.id,file_path:c.file_path}),me.info({logId:s.id,symbol:s.symbol_name,oldPath:s.file_path,newPath:c.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&me.info({repaired:t,failed:n},"Nano-Repair recovery complete"),{repaired:t,failed:n}}syncLifecycle(){let e="HEAD";try{e=Fn("git rev-parse --abbrev-ref HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return{suspended:0,resumed:0,completed:0}}if(!e)return{suspended:0,resumed:0,completed:0};let t=this.missions.findActive(),n=0;for(let o of t)o.git_branch&&o.git_branch!==e&&(this.missions.updateStatus(o.id,"suspended"),me.info({missionId:o.id,branch:o.git_branch,current:e},"Context Pivot: Suspended mission"),n++);this.missions.resumeByBranch(e);let s=[];try{s=Fn(`git branch --merged "${e}"`,{cwd:this.repoPath,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
472
+ `).map(l=>l.trim().replace(/^\* /,"")).filter(l=>l&&l!==e)}catch{}let r=0;if(s.length>0){let o=this.missions.findMergedMissions(e,s);for(let l of o)this.missions.updateStatus(l.id,"completed"),me.info({missionId:l.id,branch:l.git_branch},"Merge Sentinel: Auto-completed mission"),r++}return(n>0||r>0)&&me.info({suspended:n,completed:r},"Git-Native Lifecycle Sync complete"),{suspended:n,resumed:-1,completed:r}}};j();$e();import{Worker as ji}from"node:worker_threads";import{cpus as zi}from"node:os";import{fileURLToPath as qi}from"node:url";import{dirname as Gi,join as Ki}from"node:path";import{existsSync as Ji}from"node:fs";var Pn=qi(import.meta.url),Yi=Gi(Pn),Qi=Pn.endsWith(".ts");function Vi(){if(Qi)return null;let i=Ki(Yi,"worker.js");return Ji(i)?i:fe("dist/logic/parser/worker.js")}var Ct=class{workers=[];taskQueue=[];pendingTasks=new Map;taskIdCounter=0;initialized=!1;initPromise;shutdownRequested=!1;numWorkers;initTimeout;constructor(e={}){this.numWorkers=e.numWorkers??Math.max(1,Math.min(4,zi().length-1)),this.initTimeout=e.initTimeout??3e4}async initialize(){if(!this.initialized)return this.initPromise?this.initPromise:(this.initPromise=this._doInitialize(),this.initPromise)}async _doInitialize(){let e;try{E.info({numWorkers:this.numWorkers},"Initializing parser worker pool");let t=new Promise((n,s)=>{e=setTimeout(()=>s(new Error(`Parser pool initialization timed out after ${this.initTimeout}ms`)),this.initTimeout)});if(await Promise.race([this._initializeWorkers(),t]),e&&clearTimeout(e),this.shutdownRequested){this.initialized=!1,this.initPromise=void 0;return}this.initialized=!0,E.info({numWorkers:this.workers.length},"Parser worker pool ready")}catch(t){throw e&&clearTimeout(e),this.initPromise=void 0,this.initialized=!1,await this.shutdown(),t}}async _initializeWorkers(){let e=Vi();if(!e)throw new Error("Parser worker pool not available in development mode (tsx). Use main-thread fallback.");E.debug({workerPath:e},"Resolved parser worker path");let t=[];for(let n=0;n<this.numWorkers;n++)t.push(this.createWorker(e,n));await Promise.all(t)}async createWorker(e,t){return new Promise((n,s)=>{let r=setTimeout(()=>{s(new Error(`Parser worker ${t} initialization timed out`))},this.initTimeout),o=new ji(e,{execArgv:process.execArgv}),l={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){o.terminate().catch(()=>{}),n();return}this.workers.push(l),E.debug({workerIndex:t},"Parser worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(l,c.id,c.result):c.type==="error"&&c.id&&this.handleTaskError(l,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),E.error({err:c,workerIndex:t},"Parser worker error"),l.currentTaskId&&this.handleTaskError(l,l.currentTaskId,c),!this.initialized){s(c);return}let a=this.workers.indexOf(l);a!==-1&&this.workers.splice(a,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(u=>{E.error({err:u},"Failed to replace crashed parser worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&E.warn({workerIndex:t,code:c},"Parser worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"parse",id:t.id,filePath:t.filePath}))}async parseFile(e){return this.initialized||await this.initialize(),new Promise((t,n)=>{let r={id:`parse_${++this.taskIdCounter}`,filePath:e,resolve:t,reject:n};this.taskQueue.push(r),this.processQueue()})}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}E.info({numWorkers:this.workers.length},"Shutting down parser worker pool");let e=this.workers.map(t=>new Promise(n=>{t.worker.postMessage({type:"shutdown"}),t.worker.once("exit",()=>n()),setTimeout(()=>{t.worker.terminate().then(()=>n())},5e3)}));await Promise.all(e),this.workers=[],this.taskQueue=[],this.pendingTasks.clear(),this.initialized=!1,this.shutdownRequested=!1,this.initPromise=void 0,E.info("Parser worker pool shutdown complete")}},Re=null;function Wn(i){return Re||(Re=new Ct(i)),Re}async function Hn(){Re&&(await Re.shutdown(),Re=null)}var es=Zi.cpus().length||4,ts=Pe.DEFAULT_CONCURRENCY;async function Mt(i,e=ts,t=!1,n=!0,s){let r=ce.getInstance(i),o=r.files.database,l=Ve(i),c=l.concurrency??e;if(Zt(),!t&&on(i)){let h=an(i),y=Oe(i);if(h&&!An(i,h))return _t(),E.debug({repoPath:i,commit:y},"Index is current, skipping re-index (fast-path)"),o}Ye(i);let a=r.files.findAll(),u=new Map(a.map(h=>[h.path,{mtime:h.mtime,hash:h.content_hash}])),p=Date.now();s?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let m=await dt(i,l.ignore),d=new Map(m.map(h=>[h.path,h.mtime])),f=a.filter(h=>!d.has(h.path)).map(h=>h.path),g=a.length===0,b=[];if(t||g)b.push(...m);else{let h=m.filter(x=>{let I=u.get(x.path);return!I||I.mtime!==x.mtime}),y=Nt(c*4),T=h.map(x=>y(async()=>{let I=u.get(x.path);if(!I||!I.hash)return x;try{let D=await Xi.promises.readFile(x.path,"utf8");return rn(D,I.hash)?x:(r.files.updateMtime(x.path,x.mtime),null)}catch{return null}})),_=await Promise.all(T);b.push(..._.filter(x=>x!==null))}if(f.length===0&&b.length===0){_t();let h=Oe(i);return St(i,h||void 0),o}if(g?E.info({totalFiles:m.length},"Starting initial repository indexing..."):E.info({toDelete:f.length,toProcess:b.length},"Syncing repository updates..."),f.length>0&&r.files.deletePaths(f),b.length>0){tn(),n?(Me(!0),de().initialize().catch(()=>{})):Me(!1);let h=/\.(ts|tsx|php|py|go|js|jsx|mjs|cjs)$/,y=[],T=[];for(let S of b)h.test(Dt.basename(S.path))?y.push(S):T.push(S);let _=0,x=b.length,I=!1,D=Wn();try{await D.initialize(),I=!0,E.info({workers:D.workerCount},"Parser worker pool active")}catch(S){E.warn({err:S},"Parser worker pool failed to initialize, falling back to main-thread parsing"),I=!1}let z=(S,M)=>{let P=M.imports?.map(R=>({...R,resolved_path:Ne(R.module,S.path,i)})),C=M.content?he(M.content):null;return _++,(_%50===0||_===x)&&E.info({completed:_,total:x},"Parsing files..."),s?.({phase:"parse",current:_,total:x,message:`Parsing ${Dt.basename(S.path)}`}),{meta:S,...M,imports:P,embedding:null,kind:"code",contentHash:C}},w;if(I)w=y.map(S=>D.parseFile(S.path).then(M=>z(S,M),M=>(_++,E.error({path:S.path,error:M},"Worker parse failed"),{meta:S,exports:[],imports:[],content:"",kind:"error"})));else{let S=g?Math.max(c,Math.min(es-1,16)):c,M=Nt(S);w=y.map(P=>M(async()=>{try{let C=await Et(P.path);return z(P,C)}catch(C){return _++,E.error({path:P.path,error:C},"Failed to parse file"),{meta:P,exports:[],imports:[],content:"",kind:"error"}}}))}let N=Nt(c),v=T.map(S=>N(async()=>{try{let M=gn(S.path),P=M.content?he(M.content):null;return _++,(_%50===0||_===x)&&E.info({completed:_,total:x},"Parsing configs..."),s?.({phase:"parse",current:_,total:x,message:`Parsing config ${Dt.basename(S.path)}`}),{meta:S,...M,embedding:null,kind:"config",contentHash:P}}catch(M){return _++,E.error({path:S.path,error:M},"Failed to parse config"),{meta:S,exports:[],imports:[],content:"",kind:"error"}}}));E.info({total:x,codeFiles:y.length,configFiles:T.length,useParserPool:I},"Phase 1: Parsing all files...");let $=Date.now(),U=(await Promise.all([...w,...v])).filter(Boolean),ne=Date.now()-$;if(Ie("parse",ne),E.info({count:U.length,time:`${(ne/1e3).toFixed(1)}s`},"Phase 1 complete"),I&&Hn().catch(()=>{}),o.pragma("synchronous = NORMAL"),o.pragma("cache_size = -64000"),n){let S=[];U.forEach((B,Q)=>{"summary"in B&&B.summary&&S.push({fileIdx:Q,text:B.summary})}),E.info("Phase 2+3: Generating embeddings + persisting in parallel..."),s?.({phase:"embed",current:0,total:U.length,message:"Generating embeddings..."});let M=Date.now(),P=(async()=>{if(S.length>0){E.info({count:S.length}," \u2192 Generating file summary embeddings...");let B=S.map(q=>q.text),Q=await it(B,256);return E.info({count:S.length}," \u2713 File summaries complete"),Q}return[]})();s?.({phase:"persist",current:0,total:U.length,message:"Saving to database..."});let C=Date.now();r.files.batchSaveIndexResults(U,i,he,Ne);let R=Date.now()-C;Ie("persist",R),E.info({time:`${(R/1e3).toFixed(1)}s`},"Structural persist complete");let W=await P,J=Date.now()-M;if(Ie("embed",J),E.info({time:`${(J/1e3).toFixed(1)}s`},"Embeddings complete"),W.length>0){let B=o.prepare("UPDATE files SET embedding = ? WHERE path = ?"),Q=o.transaction(L=>{for(let k of L)B.run(k.embedding?JSON.stringify(k.embedding):null,k.path)}),q=S.map((L,k)=>({path:U[L.fileIdx].meta.path,embedding:W[k]}));Q(q),E.info({count:q.length},"Embedding column updated")}let Y=await r.intentLogs.backfillEmbeddings(64);Y>0&&E.info({count:Y}," \u2713 Intent log embeddings backfilled")}else{s?.({phase:"persist",current:0,total:U.length,message:"Saving to database..."});let S=Date.now();r.files.batchSaveIndexResults(U,i,he,Ne),Ie("persist",Date.now()-S)}o.pragma("synchronous = FULL"),o.pragma("cache_size = -2000")}if(g||b.length>0){let h=Oe(i);St(i,h||void 0)}return(b.length>0||f.length>0)&&new ut(i).detectAndRepairShifts(),en(Date.now()-p),s?.({phase:"complete",current:b.length,total:b.length,message:"Indexing complete"}),o}j();import $n from"path";import ns from"ignore";import Un from"fs";async function is(i,e=Pe.DEFAULT_CONCURRENCY,t="detailed",n,s){E.info({repo:i,level:t,subPath:n},"Ensuring cache is up-to-date..."),await Mt(i,e);let{files:r,exports:o,imports:l}=ce.getInstance(i),c=n?r.findInSubPath(i,n):r.findAll(),a=Ve(i),u=ns(),p=$n.join(i,".gitignore");if(Un.existsSync(p)&&u.add(Un.readFileSync(p,"utf8")),a.ignore&&a.ignore.length>0&&u.add(a.ignore),u.add(Fe),c=c.filter(y=>{let T=$n.relative(i,y.path);return!u.ignores(T)}),E.info({count:c.length},"Fetching data from DB..."),t==="lite"){let y=c.map(T=>({path:T.path,mtime:T.mtime}));return ke(y,i,t,s)}if(t==="summaries"){let y=c.map(T=>({path:T.path,mtime:T.mtime,classification:T.classification||void 0,summary:T.summary||void 0}));return ke(y,i,t,s)}let m=c.map(y=>y.path),d=o.findByFiles(m),f=t==="detailed"?l.findByFiles(m):[],g=new Map;for(let y of d){let T=g.get(y.file_path)||[];T.push(y),g.set(y.file_path,T)}let b=new Map;for(let y of f){let T=b.get(y.file_path)||[];T.push(y),b.set(y.file_path,T)}let h=c.map(y=>{let _=(g.get(y.path)||[]).map(I=>({name:I.name,kind:I.kind,signature:I.signature,line:I.start_line}));t==="structure"?_=_.map(I=>({name:I.name,kind:I.kind,line:I.line})):t==="signatures"&&(_=_.map(I=>({name:I.name,kind:I.kind,signature:I.signature,line:I.line})));let x=[];return t==="detailed"&&(x=(b.get(y.path)||[]).map(D=>({module:D.module_specifier,resolved_path:D.resolved_path}))),{path:y.path,mtime:y.mtime,classification:y.classification||void 0,summary:y.summary||void 0,exports:_,imports:x.length>0?x:void 0,chunks:[]}});return E.info({count:h.length},"Building hierarchical project tree..."),ke(h,i,t,s)}we();export{nt as EmbeddingPriorityQueue,_e as EmbeddingWorkerPool,ke as buildTree,si as chunkFile,Dn as cosineSimilarity,Mt as ensureCacheUpToDate,Cn as generateEmbedding,it as generateEmbeddingsBatch,de as getDefaultPool,Et as parseFile,is as processRepo,dt as scanRepo,Me as setUseWorkerThreads,kt as shutdownDefaultPool};