@precisionutilityguild/liquid-shadow 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,453 @@
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`
4
+ (function_definition name: (name) @name) @func
5
+ (class_declaration name: (name) @name) @class
6
+ (interface_declaration name: (name) @name) @interface
7
+ (trait_declaration name: (name) @name) @trait
8
+ (method_declaration name: (name) @name) @method
9
+ (namespace_use_declaration (namespace_use_clause (qualified_name) @name)) @import
10
+ `;case".py":return`
11
+ (function_definition name: (identifier) @name) @func
12
+ (class_definition name: (identifier) @name) @class
13
+ (import_statement name: (dotted_name) @name) @import
14
+ (import_from_statement module_name: (dotted_name) @name) @import
15
+ `;case".go":return`
16
+ (function_declaration name: (identifier) @name) @func
17
+ (method_declaration name: (identifier) @name) @func
18
+ (type_declaration (type_spec name: (identifier) @name)) @type
19
+ (import_spec path: (interpreted_string_literal) @name) @import
20
+ `;case".rs":return`
21
+ (function_item name: (identifier) @name) @func
22
+ (struct_item name: (_type_identifier) @name) @struct
23
+ (enum_item name: (_type_identifier) @name) @enum
24
+ (trait_item name: (_type_identifier) @name) @trait
25
+ (type_item name: (_type_identifier) @name) @type
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(`
37
+ CREATE TABLE IF NOT EXISTS schema_migrations (
38
+ version INTEGER PRIMARY KEY,
39
+ name TEXT NOT NULL,
40
+ applied_at REAL DEFAULT (unixepoch())
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(`
43
+ SELECT value FROM index_metadata
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(`
55
+ SELECT value FROM index_metadata
56
+ 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(`
60
+ SELECT * FROM files
61
+ WHERE (path LIKE ? OR path = ?)
62
+ ORDER BY path ASC
63
+ `,`${s}%`,n)}findWithEmbeddings(){return this.all("SELECT * FROM files WHERE embedding IS NOT NULL")}findFts(e,t=10){return this.all(`
64
+ SELECT files.*, files_fts.rank
65
+ FROM files_fts
66
+ JOIN files ON files.rowid = files_fts.rowid
67
+ WHERE files_fts MATCH ?
68
+ ORDER BY rank
69
+ LIMIT ?
70
+ `,e,t)}findByPathKeywords(e,t=10){let n=e.map(()=>"LOWER(path) LIKE ?").join(" OR ");return this.all(`
71
+ SELECT * FROM files
72
+ WHERE ${n}
73
+ LIMIT ?
74
+ `,...e.map(s=>`%${s}%`),t)}getContent(e){return this.get("SELECT content FROM file_content WHERE file_path = ?",e)?.content}findContentByToken(e,t=10){return this.all(`
75
+ SELECT file_path
76
+ FROM content_fts
77
+ WHERE content_fts MATCH ?
78
+ AND (file_path LIKE '%.ts' OR file_path LIKE '%.tsx' OR file_path LIKE '%.js' OR file_path LIKE '%.py' OR file_path LIKE '%.php')
79
+ AND file_path NOT LIKE '%/test/%'
80
+ AND file_path NOT LIKE '%.spec.%'
81
+ LIMIT ?
82
+ `,`"${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
84
+ COUNT(*) as total,
85
+ SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
86
+ FROM files
87
+ `);return{total:e?.total||0,withSummary:e?.withSummary||0}}getGravityMap(e=[],t){let n={},s=`
88
+ SELECT ws.file_path, m.name as mission_name, m.status
89
+ FROM working_set ws
90
+ JOIN missions m ON ws.mission_id = m.id
91
+ WHERE (
92
+ (m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
93
+ OR m.id IN (${e.length>0?e.join(","):"-1"})
94
+ )
95
+ 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(`
97
+ SELECT file_path, type, mission_id
98
+ FROM intent_logs
99
+ WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
100
+ AND file_path IS NOT NULL
101
+ ORDER BY created_at DESC
102
+ 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(`
104
+ SELECT
105
+ SUBSTR(path, LENGTH(?) + 2,
106
+ INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
107
+ ) as root,
108
+ COUNT(*) as total_files,
109
+ SUM(CASE
110
+ WHEN path LIKE '%.ts' OR path LIKE '%.tsx'
111
+ OR path LIKE '%.js' OR path LIKE '%.jsx'
112
+ OR path LIKE '%.mjs' OR path LIKE '%.cjs'
113
+ THEN 1 ELSE 0
114
+ END) as ts_files
115
+ FROM files
116
+ WHERE path LIKE ? || '/%/%'
117
+ GROUP BY root
118
+ ORDER BY total_files DESC
119
+ LIMIT ?
120
+ `,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
122
+ path,
123
+ SUBSTR(path, LENGTH(?) + 2) as relPath
124
+ FROM files
125
+ 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)
128
+ VALUES (?, ?, ?, ?, ?, ?, ?)
129
+ ON CONFLICT(path) DO UPDATE SET
130
+ mtime=excluded.mtime,
131
+ last_scanned_at=excluded.last_scanned_at,
132
+ classification=excluded.classification,
133
+ summary=excluded.summary,
134
+ embedding=excluded.embedding,
135
+ 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(`
137
+ SELECT * FROM exports
138
+ WHERE file_path = ? AND start_line <= ? AND end_line >= ?
139
+ ORDER BY (end_line - start_line) ASC -- Get innermost symbol
140
+ LIMIT 1
141
+ `,e,t,t)}findById(e){return this.get("SELECT * FROM exports WHERE id = ?",e)}findHydratedById(e){let t=this.findById(e);if(!t)return;let n=this.all(`
142
+ SELECT id, mission_id, type, content, created_at, confidence
143
+ FROM intent_logs
144
+ WHERE symbol_id = ?
145
+ ORDER BY created_at DESC
146
+ LIMIT 5
147
+ `,e),r=this.get("SELECT COUNT(*) as count FROM intent_logs WHERE symbol_id = ?",e)?.count||0,o=this.all(`
148
+ SELECT m.id, m.name, m.status
149
+ FROM missions m
150
+ JOIN working_set ws ON ws.mission_id = m.id
151
+ WHERE ws.symbol_id = ?
152
+ AND m.status IN ('in-progress', 'planned', 'verifying')
153
+ GROUP BY m.id
154
+ `,e);return{...t,recent_intents:n,intent_log_count:r,active_missions:o}}findRoutesByCapability(e){return this.all(`
155
+ SELECT name, file_path, signature
156
+ FROM exports
157
+ WHERE kind = 'HTTP Route'
158
+ AND capabilities LIKE ?
159
+ `,`%${e}%`)}findRoutesByToken(e,t=5){return this.all(`
160
+ SELECT *
161
+ FROM exports
162
+ WHERE (kind = 'HTTP Route' OR classification = 'Service Boundary')
163
+ AND (name LIKE ? OR signature LIKE ?)
164
+ LIMIT ?
165
+ `,`%${e}%`,`%${e}%`,t)}findByFile(e){return this.all("SELECT * FROM exports WHERE file_path = ? ORDER BY start_line ASC",e)}findByFiles(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.all(`SELECT * FROM exports WHERE file_path IN (${t}) ORDER BY file_path, start_line ASC`,...e)}findSiblings(e){return this.all(`
166
+ SELECT name, kind, signature, start_line, end_line,
167
+ parent_id, id,
168
+ (SELECT name FROM exports WHERE id = e.parent_id) as parent_name
169
+ FROM exports e
170
+ WHERE file_path = ?
171
+ AND parent_id IS NULL
172
+ ORDER BY start_line ASC
173
+ `,e)}findByName(e,t=20){return this.all("SELECT * FROM exports WHERE name = ? LIMIT ?",e,t)}findClassByName(e){return this.get("SELECT * FROM exports WHERE name = ? AND kind = 'ClassDeclaration' LIMIT 1",e)}findDefinitionCandidates(e,t){let n=[e],s=`
174
+ SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
175
+ f.path as file_path, e.classification, e.capabilities,
176
+ p.name as parent_name, p.kind as parent_kind
177
+ FROM exports e
178
+ JOIN files f ON e.file_path = f.path
179
+ LEFT JOIN exports p ON e.parent_id = p.id
180
+ WHERE e.name = ?
181
+ `;return t&&(s+=" AND f.path = ?",n.push(t)),s+=`
182
+ ORDER BY
183
+ CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
184
+ CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
185
+ LIMIT 10
186
+ `,this.all(s,...n)}findMemberCandidates(e,t,n){let s=[e,t],r=`
187
+ SELECT e.id, e.name, e.kind, e.start_line, e.end_line, e.signature, e.doc,
188
+ f.path as file_path, e.classification, e.capabilities,
189
+ p.name as parent_name, p.kind as parent_kind
190
+ FROM exports e
191
+ JOIN files f ON e.file_path = f.path
192
+ LEFT JOIN exports p ON e.parent_id = p.id
193
+ WHERE p.name = ? AND e.name = ?
194
+ `;return n&&(r+=" AND f.path = ?",s.push(n)),r+=`
195
+ ORDER BY
196
+ CASE WHEN e.parent_id IS NULL THEN 0 ELSE 1 END,
197
+ CASE WHEN e.kind = 'ExportSpecifier' THEN 2 ELSE 0 END
198
+ LIMIT 10
199
+ `,this.all(r,...s)}findPotentialParents(e){return this.all(`
200
+ SELECT name, kind, file_path
201
+ FROM exports
202
+ WHERE kind IN ('ClassDeclaration', 'ClassExpression', 'TsInterfaceDeclaration')
203
+ AND id IN (
204
+ SELECT rowid FROM content_fts WHERE content MATCH ?
205
+ )
206
+ LIMIT 3
207
+ `,`"${e}"`)}findFuzzyCandidates(e){let t=e.charAt(0).toLowerCase();return this.all(`
208
+ SELECT DISTINCT name FROM exports
209
+ WHERE parent_id IS NULL
210
+ AND (name LIKE ? OR name LIKE ? OR ABS(LENGTH(name) - LENGTH(?)) <= 5)
211
+ ORDER BY ABS(LENGTH(name) - LENGTH(?)) ASC
212
+ LIMIT 1000
213
+ `,t+"%","%"+t+"%",e,e)}findTopLevelByFile(e){return this.all(`
214
+ SELECT * FROM exports
215
+ WHERE file_path = ? AND parent_id IS NULL
216
+ ORDER BY start_line ASC
217
+ `,e)}findFts(e,t=20){return this.all(`
218
+ SELECT e.*
219
+ FROM exports e
220
+ JOIN exports_fts ef ON e.id = ef.rowid
221
+ WHERE ef MATCH ?
222
+ LIMIT ?
223
+ `,e,t)}findByPartialName(e,t=20){return this.all(`
224
+ SELECT * FROM exports
225
+ WHERE lower(name) LIKE ?
226
+ 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(`
228
+ SELECT e.name, e.kind, e.file_path, e.start_line
229
+ FROM exports e
230
+ WHERE e.kind IN (
231
+ 'FunctionDeclaration', 'ClassDeclaration',
232
+ 'TsInterfaceDeclaration', 'TsTypeAliasDeclaration', 'TsEnumDeclaration',
233
+ 'ArrowFunctionExpression', 'FunctionExpression'
234
+ )
235
+ AND e.parent_id IS NULL
236
+ ${n}
237
+ AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.imported_symbols LIKE '%' || e.name || '%')
238
+ AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
239
+ ORDER BY e.file_path, e.start_line
240
+ LIMIT ?
241
+ `,e)}getGravityMap(e=[],t){let n={},s=`
242
+ SELECT ws.symbol_id, m.name as mission_name, m.status
243
+ FROM working_set ws
244
+ JOIN missions m ON ws.mission_id = m.id
245
+ WHERE (
246
+ (m.status IN ('in-progress', 'verifying') ${t?"AND m.git_branch = ?":""})
247
+ OR m.id IN (${e.length>0?e.join(","):"-1"})
248
+ )
249
+ 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(`
251
+ SELECT symbol_id, type, mission_id
252
+ FROM intent_logs
253
+ WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
254
+ AND symbol_id IS NOT NULL
255
+ ORDER BY created_at DESC
256
+ 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(`
258
+ SELECT kind, COUNT(*) as c
259
+ FROM exports
260
+ WHERE kind IS NOT NULL AND kind != ''
261
+ GROUP BY kind
262
+ ORDER BY c DESC
263
+ LIMIT ?
264
+ `,e)}getWithEmbeddingsCount(){return this.get("SELECT COUNT(*) as count FROM exports WHERE embedding IS NOT NULL")?.count||0}findByMethodName(e){return this.all(`
265
+ SELECT * FROM exports
266
+ WHERE name = ?
267
+ OR name LIKE ?
268
+ OR name LIKE ?
269
+ LIMIT 10
270
+ `,e,`%.${e}`,`%::${e}`)}};var ln=`
271
+ WITH RECURSIVE dependency_chain AS (
272
+ -- Base case: Direct dependents of the target symbol
273
+ -- Meaning: Files that import the file where the symbol is defined
274
+ SELECT
275
+ i.file_path as consumer_path,
276
+ i.module_specifier,
277
+ i.imported_symbols,
278
+ f.path as source_path,
279
+ 1 as depth,
280
+ i.file_path || '<-' || f.path as path_chain
281
+ FROM imports i
282
+ JOIN files f ON i.resolved_path = f.path
283
+ WHERE f.path = ? -- The file where our changed symbol lives
284
+ AND (
285
+ -- Exact symbol match or wildcard import
286
+ i.imported_symbols LIKE ?
287
+ OR i.imported_symbols = '*'
288
+ OR i.imported_symbols = 'default'
289
+ OR i.imported_symbols = ''
290
+ )
291
+
292
+ UNION ALL
293
+
294
+ -- Recursive step: Find consumers of the consumers
295
+ SELECT
296
+ i.file_path as consumer_path,
297
+ i.module_specifier,
298
+ i.imported_symbols,
299
+ dc.consumer_path as source_path,
300
+ dc.depth + 1,
301
+ i.file_path || '<-' || dc.path_chain
302
+ FROM imports i
303
+ JOIN dependency_chain dc ON i.resolved_path = dc.consumer_path
304
+ 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
306
+ )
307
+ SELECT DISTINCT
308
+ dc.consumer_path,
309
+ dc.depth,
310
+ dc.source_path,
311
+ dc.imported_symbols
312
+ FROM dependency_chain dc
313
+ 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(`
315
+ SELECT * FROM imports
316
+ WHERE resolved_path IS NOT NULL AND resolved_path != ''
317
+ `)}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(`
318
+ SELECT *
319
+ FROM imports
320
+ WHERE file_path = ?
321
+ AND (imported_symbols LIKE ? OR imported_symbols = '*')
322
+ LIMIT 1
323
+ `,e,`%${t}%`)}findProxies(e){return this.all(`
324
+ SELECT i.file_path
325
+ FROM imports i
326
+ JOIN exports e ON i.file_path = e.file_path
327
+ WHERE i.resolved_path = ?
328
+ AND (e.kind = 'ExportAllDeclaration' OR e.kind = 'ExportMapping')
329
+ `,e)}findVerifiedDependents(e,t){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.all(`
330
+ SELECT i.file_path, i.imported_symbols, f.classification, f.summary
331
+ FROM imports i
332
+ JOIN files f ON i.file_path = f.path
333
+ WHERE i.resolved_path IN (${n})
334
+ AND (i.imported_symbols LIKE ? OR i.imported_symbols = '' OR i.imported_symbols = '*')
335
+ LIMIT 10
336
+ `,...e,`%${t}%`)}countVerifiedDependents(e,t){if(e.length===0)return 0;let n=e.map(()=>"?").join(", ");return this.get(`
337
+ SELECT COUNT(*) as count FROM imports
338
+ WHERE resolved_path IN (${n})
339
+ 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
341
+ CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
342
+ 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
+ CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
344
+ created_at ASC`,this.all(t,...n)}findRecentCompleted(e=3){return this.all(`
345
+ SELECT * FROM missions
346
+ WHERE status = 'completed'
347
+ ORDER BY updated_at DESC, id DESC
348
+ LIMIT ?
349
+ `,e)}create(e){return this.insert(`
350
+ INSERT INTO missions (name, goal, strategy_graph, status, git_branch, commit_sha, parent_id, verification_context, outcome_contract)
351
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
352
+ `,e.name,e.goal,e.strategy_graph,e.status,e.git_branch,e.commit_sha,e.parent_id,e.verification_context,e.outcome_contract)}addArtifact(e,t,n,s){this.run("INSERT INTO mission_artifacts (mission_id, type, identifier, metadata) VALUES (?, ?, ?, ?)",e,t,n,s?JSON.stringify(s):null)}getArtifacts(e){return this.all("SELECT * FROM mission_artifacts WHERE mission_id = ?",e)}update(e,t){let n=Object.keys(t);if(n.length===0)return;let s=n.map(o=>`${o} = ?`).join(", "),r=Object.values(t);r.push(e),this.run(`UPDATE missions SET ${s}, updated_at = unixepoch() WHERE id = ?`,...r)}updateStatus(e,t,n){n?this.run("UPDATE missions SET status = ?, updated_at = unixepoch(), commit_sha = ? WHERE id = ?",t,n,e):this.run("UPDATE missions SET status = ?, updated_at = unixepoch() WHERE id = ?",t,e)}getWorkingSet(e){return this.all("SELECT file_path, type FROM working_set WHERE mission_id = ?",e)}clearWorkingSet(e){this.run("DELETE FROM working_set WHERE mission_id = ?",e)}addToWorkingSet(e,t,n="file"){this.run("INSERT OR IGNORE INTO files (path, mtime, last_scanned_at) VALUES (?, unixepoch(), unixepoch())",t),this.run("INSERT INTO working_set (mission_id, file_path, type) VALUES (?, ?, ?)",e,t,n)}findColdMissions(e,t=10){return this.all(`
353
+ SELECT m.id, COUNT(il.id) as log_count
354
+ FROM missions m
355
+ LEFT JOIN intent_logs il ON il.mission_id = m.id
356
+ WHERE m.updated_at < ?
357
+ AND m.status != 'distilled'
358
+ GROUP BY m.id
359
+ HAVING log_count > ?
360
+ `,e,t).map(s=>s.id)}getStats(){let e=this.get(`
361
+ SELECT
362
+ COUNT(*) as total,
363
+ SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
364
+ SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
365
+ FROM missions
366
+ `);return{total:e?.total||0,completed:e?.completed||0,active:e?.active||0}}getAnalytics(){let e=this.getStats(),t=e.total>0?Math.round(e.completed/e.total*100):0,n=this.get(`
367
+ SELECT AVG(updated_at - created_at) AS avg_duration
368
+ FROM missions
369
+ 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
371
+ SET status = 'suspended', updated_at = unixepoch()
372
+ WHERE git_branch = ? AND status IN ('in-progress', 'planned', 'verifying')`,e)}resumeByBranch(e){this.run(`UPDATE missions
373
+ SET status = 'in-progress', updated_at = unixepoch()
374
+ WHERE git_branch = ? AND status = 'suspended'`,e)}findMergedMissions(e,t){if(t.length===0)return[];let n=t.filter(r=>r!==e);if(n.length===0)return[];let s=n.map(()=>"?").join(",");return this.all(`SELECT * FROM missions
375
+ WHERE status IN ('in-progress', 'planned', 'verifying', 'suspended')
376
+ AND git_branch IN (${s})`,...n)}findByCommitShas(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.all(`SELECT * FROM missions WHERE commit_sha IN (${t})`,...e)}findByParentId(e){return this.all("SELECT * FROM missions WHERE parent_id = ?",e)}hasChildren(e){return!!this.get("SELECT 1 FROM missions WHERE parent_id = ? LIMIT 1",e)}hasNoSteps(e){if(!e.strategy_graph)return!0;try{let t=JSON.parse(e.strategy_graph),n=t?.steps??t;return!Array.isArray(n)||n.length===0}catch{return!0}}findParentOnlyIds(e){return e.filter(t=>t.parent_id!=null||!this.hasChildren(t.id)?!1:this.hasNoSteps(t)).map(t=>t.id)}createLink(e,t,n,s,r){this.db.exec(`
377
+ CREATE TABLE IF NOT EXISTS cross_repo_links (
378
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
379
+ mission_id INTEGER NOT NULL,
380
+ linked_repo_path TEXT NOT NULL,
381
+ linked_mission_id INTEGER NOT NULL,
382
+ relationship TEXT,
383
+ direction TEXT,
384
+ created_at REAL DEFAULT (unixepoch()),
385
+ FOREIGN KEY(mission_id) REFERENCES missions(id) ON DELETE CASCADE
386
+ );
387
+ CREATE INDEX IF NOT EXISTS idx_cross_repo_mission ON cross_repo_links(mission_id);
388
+ `),this.run(`
389
+ INSERT INTO cross_repo_links (mission_id, linked_repo_path, linked_mission_id, relationship, direction)
390
+ VALUES (?, ?, ?, ?, ?)
391
+ `,e,t,n,s,r)}getLinks(e){try{return this.all(`
392
+ SELECT linked_repo_path, linked_mission_id, relationship, direction
393
+ FROM cross_repo_links
394
+ 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(`
396
+ SELECT * FROM intent_logs
397
+ WHERE mission_id = ?
398
+ ORDER BY created_at DESC
399
+ LIMIT ?
400
+ `,e,t)}findRecentDecisionActivity(e=10){return this.all(`
401
+ SELECT * FROM intent_logs
402
+ WHERE type IN ('decision', 'system', 'fix', 'heritage', 'adr')
403
+ ORDER BY created_at DESC
404
+ LIMIT ?
405
+ `,e)}create(e){return this.insert(`
406
+ INSERT INTO intent_logs (mission_id, symbol_id, file_path, type, content, confidence, symbol_name, signature, commit_sha)
407
+ 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(`
409
+ SELECT id, file_path, symbol_name, signature
410
+ FROM intent_logs
411
+ WHERE symbol_id IS NULL AND symbol_name IS NOT NULL
412
+ `)}findOrphans(){return this.all(`
413
+ SELECT il.id, il.symbol_id, il.file_path, il.symbol_name
414
+ FROM intent_logs il
415
+ WHERE (il.symbol_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM exports e WHERE e.id = il.symbol_id))
416
+ OR (il.symbol_id IS NULL AND il.type != 'lapsed' AND il.type != 'system' AND il.type != 'adr')
417
+ `)}findLogsForMissingFiles(){return this.all(`
418
+ SELECT il.id
419
+ FROM intent_logs il
420
+ WHERE il.file_path IS NOT NULL
421
+ AND NOT EXISTS (
422
+ SELECT 1 FROM files f WHERE f.path = il.file_path
423
+ )
424
+ `)}markAsLapsed(e){this.run(`
425
+ UPDATE intent_logs
426
+ SET symbol_id = NULL,
427
+ type = 'lapsed',
428
+ content = 'Lapsed: ' || content
429
+ WHERE id = ?
430
+ `,e)}importHeritage(e,t,n,s){this.run(`
431
+ INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
432
+ 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(`
434
+ SELECT file_path, key, value, kind
435
+ FROM configs
436
+ WHERE key LIKE ? OR value LIKE ?
437
+ 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(`
439
+ SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
440
+ FROM content_fts
441
+ WHERE content_fts MATCH ?
442
+ 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 (
445
+ 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(`
447
+ INSERT INTO hologram_snapshot (section, data, updated_at)
448
+ VALUES (?, ?, unixepoch())
449
+ ON CONFLICT(section) DO UPDATE SET
450
+ data = excluded.data,
451
+ 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};