@precisionutilityguild/liquid-shadow 1.0.0 → 1.0.2
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/entry/cli/index.js +271 -225
- package/dist/entry/mcp/server.js +354 -304
- package/dist/index.js +52 -45
- package/dist/web-manifest.json +135 -0
- package/package.json +5 -4
- package/skills/audit/SKILL.md +0 -29
- package/skills/chronicle/SKILL.md +0 -33
- package/skills/continue/SKILL.md +0 -44
- package/skills/mission/SKILL.md +0 -35
- package/skills/onboard/SKILL.md +0 -27
- package/skills/understand/SKILL.md +0 -35
- package/skills/workspace/SKILL.md +0 -25
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It from"path";var ke=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/vendor/**","**/.next/**","**/.cache/**","**/coverage/**","**/*.min.js"],
|
|
2
|
-
`),t=[],n=0;for(let s of e)t.push(n),n+=s.length+1;return t}function
|
|
3
|
-
`)[0].trim();return t.length>200?t.substring(0,197)+"...":t}function ve(i,e,t){let n=i.toLowerCase(),s=e.toLowerCase();return n.includes("components/")||n.endsWith(".tsx")?"Component":n.startsWith("use")||s.startsWith("use")?"Hook":n.includes("models/")||s.endsWith("model")?"Model":n.includes("services/")||n.includes("controllers/")||n.includes("handlers/")||n.includes("mcp/")||n.endsWith("service.ts")||n.endsWith("controller.ts")||n.endsWith("handler.ts")||s.endsWith("service")||s.endsWith("controller")||s.endsWith("handler")?"Service":n.includes("repositories/")||n.includes("repos/")||n.endsWith("repository.ts")||n.endsWith("repo.ts")||s.endsWith("repository")||s.endsWith("repo")?"Repository":t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function ge(i){let e=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(i)&&e.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(i)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(i)||/\.query\s*\(|\.execute\s*\(/i.test(i)&&/db|database|client|pool/i.test(i))&&e.push("Database"),(/\bfs\./i.test(i)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(i)||/import\s+.*\bfs\b/.test(i))&&e.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(i)||/\bdocument\.cookie\b/.test(i))&&e.push("Browser Storage"),e}function Y(i,e){if(!i)return"";let t=i.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,s=0,r=t.length;for(let o=0;o<t.length;o++){let c=t[o];if(c==="(")n++;else if(c===")")n--;else if(c==="<")s++;else if(c===">")s--;else if(c==="{"){if(n===0&&s===0){r=o;break}}else if(c==="; "&&n===0&&s===0){r=o;break}else if(c==="="&&t[o+1]===">"&&n===0&&s===0){r=o+2;break}}return t.substring(0,r).trim()}function Nt(i){let e=[];for(let t of i)t.type==="ImportDeclaration"&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join("","")}),t.type==="ExportAllDeclaration"&&e.push({module:t.source.value,name:"*"}),t.type==="ExportNamedDeclaration"&&t.source&&e.push({module:t.source.value,name:t.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return e}function Dt(i,e,t,n,s,r,o,c){let l=[];for(let a of i){if(a.type==="ExportDeclaration"){let p=a.declaration,d=p.type,m="";d==="VariableDeclaration"?m=p.declarations.map(h=>h.id.value).join("",""):m=p.id?.value||p.identifier?.value||"anonymous";let f=A(a.span.start-e,t),g=A(a.span.end-e,t),E=G(f,r,n),y=c(a.span),u=[];if(a.type==="ExportDeclaration"&&(d==="ClassDeclaration"||d==="ClassExpression")){let h=p.body||[];for(let b of h)if(b.type==="ClassMethod"||b.type==="ClassProperty"){let M=b.key.value;if(!M)continue;let C=A(b.span.start-e,t),I=A(b.span.end-e,t),v=c(b.span),$=G(C,r,n);u.push({name:M,kind:b.type,signature:Y(v,b.type),line:O(C,s),endLine:O(I,s),doc:$,classification:b.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(d==="FunctionDeclaration"&&p.body?.type==="BlockStatement")u=st(p.body.stmts,e,t,n,s,r,c);else if(d==="VariableDeclaration"){for(let h of p.declarations)if(h.init&&(h.init.type==="ArrowFunctionExpression"||h.init.type==="FunctionExpression")&&h.init.body?.type==="BlockStatement"){u=st(h.init.body.stmts,e,t,n,s,r,c);break}}l.push({name:m,kind:d,signature:Y(y,d),line:O(f,s),endLine:O(g,s),doc:E,classification:ve(o,m,d),capabilities:JSON.stringify(ge(y)),members:u})}if(a.type==="ExportNamedDeclaration"){for(let p of a.specifiers)if(p.type==="ExportSpecifier"){let d=A(a.span.start-e,t),m=A(a.span.end-e,t),f=G(d,r,n);l.push({name:p.exported?.value||p.orig.value,kind:"ExportSpecifier",signature:`export { ${p.orig.value} }`,line:O(d,s),endLine:O(m,s),doc:f,classification:"Export mapping",capabilities:"[]"})}}if(a.type==="ExportDefaultDeclaration"){let p=A(a.span.start-e,t),d=A(a.span.end-e,t),m=G(p,r,n),f=c(a.span),g=[];if(a.decl.type==="ClassExpression"||a.decl.type==="ClassDeclaration"){let E=a.decl.body||[];for(let y of E)if(y.type==="ClassMethod"||y.type==="ClassProperty"){let u=y.key.value;if(!u)continue;let h=A(y.span.start-e,t),b=A(y.span.end-e,t),M=c(y.span),C=G(h,r,n);g.push({name:u,kind:y.type,signature:Y(M,y.type),line:O(h,s),endLine:O(b,s),doc:C,classification:y.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(a.decl.type==="FunctionExpression"||a.decl.type==="FunctionDeclaration"||a.decl.type==="ArrowFunctionExpression")&&a.decl.body?.type==="BlockStatement"&&(g=st(a.decl.body.stmts,e,t,n,s,r,c));l.push({name:"default",kind:"DefaultExport",signature:Y(f,"DefaultExport"),line:O(p,s),endLine:O(d,s),doc:m,classification:"Default Export",capabilities:JSON.stringify(ge(f)),members:g})}if(a.type==="ExportAllDeclaration"){let p=A(a.span.start-e,t),d=A(a.span.end-e,t),m=a.source.value,f=G(p,r,n);l.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${m}"`,line:O(p,s),endLine:O(d,s),doc:f,classification:"Re-export",capabilities:"[]"})}}return l}function st(i,e,t,n,s,r,o){let c=[];for(let l of i){if(l.type==="VariableDeclaration")for(let a of l.declarations){let p=[],d=m=>{if(m.type==="Identifier")p.push({name:m.value,span:m.span});else if(m.type==="ArrayPattern")for(let f of m.elements)f&&d(f);else if(m.type==="ObjectPattern")for(let f of m.properties)f.type==="AssignmentPatternProperty"?p.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&d(f.value)};d(a.id);for(let m of p){let f=A(m.span.start-e,t),g=A(m.span.end-e,t),E=o(m.span),y=G(f,r,n);c.push({name:m.name,kind:"VariableDeclaration",signature:Y(E,"VariableDeclaration"),line:O(f,s),endLine:O(g,s),doc:y,classification:"Internal Variable",capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let a=l.identifier?.value||l.ident?.value||"anonymous",p=A(l.span.start-e,t),d=A(l.span.end-e,t),m=o(l.span),f=G(p,r,n);c.push({name:a,kind:"FunctionDeclaration",signature:Y(m,"FunctionDeclaration"),line:O(p,s),endLine:O(d,s),doc:f,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let a of l.argument.properties){let p="",d=a.span||a.key?.span||a.ident?.span;if(a.type==="KeyValueProperty"){let m=a.key;p=m?.value||m?.raw||(m?.type==="Identifier"?m.value:"")}else a.type==="MethodProperty"?p=a.key?.value||a.key?.raw||"":a.type==="ShorthandProperty"?p=a.ident?.value||"":a.type==="Identifier"&&(p=a.value||"");if(p&&d){let m=A(d.start-e,t),f=A(d.end-e,t),g=o(d),E=G(m,r,n);c.push({name:p,kind:"ReturnProperty",signature:Y(g,"ReturnProperty"),line:O(m,s),endLine:O(f,s),doc:E,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let a=l.expression;if(a.callee.type==="MemberExpression"&&(a.callee.property?.value==="on"||a.callee.property?.value==="once")){let p=a.arguments[0]?.expression?.value,d=a.arguments[1]?.expression;if(p&&d&&(d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")){let m=A(d.span.start-e,t),f=A(d.span.end-e,t),g=o(d.span);c.push({name:`on:${p}`,kind:d.type,signature:Y(g,d.type),line:O(m,s),endLine:O(f,s),doc:"",classification:"Event Handler",capabilities:"[]"})}}}}return c}function Mt(i,e,t,n,s){let r=[];function o(c){if(!(!c||typeof c!="object")){if(c.type==="CallExpression"){let l=Cn(c);if(l){let a=A(c.span.start-e,t);r.push({...l,line:O(a,n),snippet:s(c.span)})}}for(let l of Object.keys(c)){if(l==="span")continue;let a=c[l];Array.isArray(a)?a.forEach(o):typeof a=="object"&&o(a)}}}return i.forEach(o),r}function Cn(i){let{callee:e,arguments:t}=i;if(!t||t.length===0)return null;if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};let s=["get","post","put","delete","patch"];if(s.includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value;if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}if(s.includes(n)&&t[0].expression.type==="StringLiteral"&&e.object.type==="Identifier"&&["axios","http","request"].includes(e.object.value))return{type:"api_route",name:t[0].expression.value,direction:"produce"}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function ye(i){let{classification:e,capabilities:t,exports:n,fileName:s}=i,r={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},o=t.map(g=>r[g]).filter(Boolean).join(" and "),l={Component:(g,E)=>{let y=E.find(h=>h.kind==="FunctionDeclaration"||h.kind==="ClassDeclaration")?.name,u=y?`React component: ${y}`:"React UI component";return g?`${u} with ${g}`:u},Hook:(g,E)=>{let y=E.find(h=>h.name.startsWith("use"))?.name,u=y?`Custom React hook: ${y}`:"Custom React hook";return g?`${u} for ${g}`:u},Service:(g,E)=>{let u=`Service layer: ${E[0]?.name||"Service"}`;return g?`${u} handling ${g}`:u},Repository:(g,E)=>`Data repository: ${E[0]?.name||"Repository"} for ${g||"data access"}`,"Type Definition":(g,E)=>`Type definitions: ${E.slice(0,3).map(u=>u.name).join("")}${E.length>3?"...":""}`,Model:(g,E)=>`Data model: ${E[0]?.name||"Model"}`,"HTTP Route":(g,E)=>{let y=E.filter(u=>u.classification==="Service Boundary");return y.length>0?`API endpoints: ${y.slice(0,3).map(u=>u.name).join("")}`:"API route handler"},"Micro IR (PHP)":(g,E)=>{let y=E.some(h=>h.classification==="Service Boundary"),u=E.find(h=>h.kind==="ClassDeclaration")?.name;return y?"PHP controller with API routes":u?`PHP class: ${u}`:"PHP module"},"Micro IR (Python)":(g,E)=>{let y=E.some(h=>h.classification==="Service Boundary"),u=E.find(h=>h.kind==="ClassDeclaration")?.name;return y?"Python API handler with routes":u?`Python class: ${u}`:"Python module"},"Micro IR (Go/TS) ":(g,E)=>{let y=E.some(h=>h.kind==="TypeDeclaration"),u=E.filter(h=>h.kind==="FunctionDeclaration");return y&&u.length>0?`Go package: types and ${u.length} function(s)`:y?"Go package: type definitions":u.length>0?`Go package: ${u[0].name} and ${u.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(g,E)=>{let y=E.find(b=>b.kind==="TraitDeclaration")?.name,u=E.find(b=>b.kind==="StructDeclaration")?.name,h=E.filter(b=>b.kind==="FunctionDeclaration");return y?g.includes("Rust trait")?`Rust module: trait ${y}`:`Rust module: ${y}`:u?`Rust module: struct ${u}`:h.length>0?`Rust module: ${h.length} function(s)`:"Rust module"}}[e];if(l)return l(o,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let a=n.filter(g=>g.kind==="FunctionDeclaration"),p=n.filter(g=>g.kind==="ClassDeclaration"),d=n.filter(g=>g.kind==="TsInterfaceDeclaration"||g.kind==="TsTypeAliasDeclaration"),m=[];if(p.length>0&&m.push(`Class: ${p[0].name}`),a.length>0){let g=a.slice(0,2).map(E=>E.name).join("");m.push(`Functions: ${g}`)}d.length>0&&m.push(`Types: ${d.length}`);let f=m.length>0?m.join(" | "):`Module with ${n.length} export(s)`;return o?`${f} \u2014 ${o}`:f}function Ot(i){let e=new Set;function t(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&W(n.typeAnnotation,e),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&W(n,e);for(let s in n){if(s==="span"||s==="comments"||s==="interpreter")continue;let r=n[s];r&&typeof r=="object"&&(Array.isArray(r)?r.forEach(t):t(r))}}}return i.forEach(n=>t(n)),Array.from(e)}function W(i,e){if(i){if(i.type==="TsTypeAnnotation"){W(i.typeAnnotation,e);return}i.type==="TsTypeReference"&&(i.typeName?.type==="Identifier"&&e.add(i.typeName.value),i.typeName?.type==="TsQualifiedName"&&At(i.typeName,e),i.typeParams&&W(i.typeParams,e)),i.type==="TsArrayType"&&W(i.elementType,e),i.type==="TsUnionType"&&i.types?.forEach(t=>W(t,e)),i.type==="TsIntersectionType"&&i.types?.forEach(t=>W(t,e)),i.type==="TsTupleType"&&i.elemTypes?.forEach(t=>W(t.ty,e)),(i.type==="TsFunctionType"||i.type==="TsConstructorType")&&(i.params?.forEach(t=>W(t.typeAnnotation,e)),i.typeAnnotation&&W(i.typeAnnotation,e)),i.type==="TsTypeParameterDeclaration"&&i.params?.forEach(t=>{t.constraint&&W(t.constraint,e),t.default&&W(t.default,e)}),i.type==="TsTypeParameterInstantiation"&&i.params?.forEach(t=>W(t,e)),i.type==="TsMappedType"&&i.typeAnnotation&&W(i.typeAnnotation,e),i.type==="TsIndexedAccessType"&&(W(i.objectType,e),W(i.indexType,e)),i.type==="TsConditionalType"&&(W(i.checkType,e),W(i.extendsType,e),W(i.trueType,e),W(i.falseType,e)),i.type==="TsTypeLiteral"&&i.members?.forEach(t=>{t.typeAnnotation&&W(t.typeAnnotation,e)})}}function At(i,e){i.type==="TsQualifiedName"?(i.left&&At(i.left,e),i.right?.value&&e.add(i.right.value)):i.type==="Identifier"&&e.add(i.value)}import $t from"path";import ot from"path";import Pt from"path";import Wn from"fs";import{fileURLToPath as Pn}from"url";import*as ae from"web-tree-sitter";import vn from"pino";var Nn={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},Dn=vn({level:process.env.LOG_LEVEL||"info",base:{service:"liquid-shadow"},formatters:{level(i,e){return{level:i,severity:Nn[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),_=Dn;import{fileURLToPath as Mn}from"node:url";import{dirname as rt,join as Ft,resolve as On}from"node:path";import{existsSync as An}from"node:fs";var wn=Mn(import.meta.url),wt=rt(wn);function Fn(){let i=wt;for(;i!==rt(i);){if(An(Ft(i,"package.json")))return i;i=rt(i)}return On(wt,"..","..")}function Ne(...i){return Ft(Fn(),...i)}var as=Pt.dirname(Pn(import.meta.url)),Wt=_.child({module:"parser:tree-sitter"}),De=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let e=ae.Parser||ae;await e.init(),this.parser=new e}async getLanguage(e){if(this.languages.has(e))return this.languages.get(e);let t=Ne("resources","grammars",`tree-sitter-${this.getLangName(e)}.wasm`);if(!Wn.existsSync(t))return Wt.warn({grammarPath:t},"Grammar WASM not found"),null;try{let n=await ae.Language.load(t);return this.languages.set(e,n),n}catch(n){return Wt.error({err:n,ext:e},"Failed to load language grammar"),null}}getLangName(e){switch(e.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(e){switch(e.toLowerCase()){case".php":return`
|
|
1
|
+
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"],St=["**/*.{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(St,{cwd:i,absolute:!0,ignore:ke})).filter(o=>{let l=It.relative(i,o);return!t.ignores(l)}).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 M(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 O(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 K(i,e){if(!i)return"";let t=i.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(e==="TsInterfaceDeclaration"||e==="TsTypeAliasDeclaration")return t;let n=0,s=0,r=t.length;for(let o=0;o<t.length;o++){let l=t[o];if(l==="(")n++;else if(l===")")n--;else if(l==="<")s++;else if(l===">")s--;else if(l==="{"){if(n===0&&s===0){r=o;break}}else if(l==="; "&&n===0&&s===0){r=o;break}else if(l==="="&&t[o+1]===">"&&n===0&&s===0){r=o+2;break}}return t.substring(0,r).trim()}function 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,l){let c=[];for(let a of i){if(a.type==="ExportDeclaration"){let u=a.declaration,p=u.type,d="";p==="VariableDeclaration"?d=u.declarations.map(g=>g.id.value).join("",""):d=u.id?.value||u.identifier?.value||"anonymous";let f=O(a.span.start-e,t),h=O(a.span.end-e,t),E=G(f,r,n),y=l(a.span),m=[];if(a.type==="ExportDeclaration"&&(p==="ClassDeclaration"||p==="ClassExpression")){let g=u.body||[];for(let b of g)if(b.type==="ClassMethod"||b.type==="ClassProperty"){let A=b.key.value;if(!A)continue;let C=O(b.span.start-e,t),I=O(b.span.end-e,t),v=l(b.span),$=G(C,r,n);m.push({name:A,kind:b.type,signature:K(v,b.type),line:M(C,s),endLine:M(I,s),doc:$,classification:b.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(p==="FunctionDeclaration"&&u.body?.type==="BlockStatement")m=st(u.body.stmts,e,t,n,s,r,l);else if(p==="VariableDeclaration"){for(let g of u.declarations)if(g.init&&(g.init.type==="ArrowFunctionExpression"||g.init.type==="FunctionExpression")&&g.init.body?.type==="BlockStatement"){m=st(g.init.body.stmts,e,t,n,s,r,l);break}}c.push({name:d,kind:p,signature:K(y,p),line:M(f,s),endLine:M(h,s),doc:E,classification:ve(o,d,p),capabilities:JSON.stringify(ge(y)),members:m})}if(a.type==="ExportNamedDeclaration"){for(let u of a.specifiers)if(u.type==="ExportSpecifier"){let p=O(a.span.start-e,t),d=O(a.span.end-e,t),f=G(p,r,n);c.push({name:u.exported?.value||u.orig.value,kind:"ExportSpecifier",signature:`export { ${u.orig.value} }`,line:M(p,s),endLine:M(d,s),doc:f,classification:"Export mapping",capabilities:"[]"})}}if(a.type==="ExportDefaultDeclaration"){let u=O(a.span.start-e,t),p=O(a.span.end-e,t),d=G(u,r,n),f=l(a.span),h=[];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 m=y.key.value;if(!m)continue;let g=O(y.span.start-e,t),b=O(y.span.end-e,t),A=l(y.span),C=G(g,r,n);h.push({name:m,kind:y.type,signature:K(A,y.type),line:M(g,s),endLine:M(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"&&(h=st(a.decl.body.stmts,e,t,n,s,r,l));c.push({name:"default",kind:"DefaultExport",signature:K(f,"DefaultExport"),line:M(u,s),endLine:M(p,s),doc:d,classification:"Default Export",capabilities:JSON.stringify(ge(f)),members:h})}if(a.type==="ExportAllDeclaration"){let u=O(a.span.start-e,t),p=O(a.span.end-e,t),d=a.source.value,f=G(u,r,n);c.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${d}"`,line:M(u,s),endLine:M(p,s),doc:f,classification:"Re-export",capabilities:"[]"})}}return c}function st(i,e,t,n,s,r,o){let l=[];for(let c of i){if(c.type==="VariableDeclaration")for(let a of c.declarations){let u=[],p=d=>{if(d.type==="Identifier")u.push({name:d.value,span:d.span});else if(d.type==="ArrayPattern")for(let f of d.elements)f&&p(f);else if(d.type==="ObjectPattern")for(let f of d.properties)f.type==="AssignmentPatternProperty"?u.push({name:f.key.value,span:f.span}):f.type==="KeyValuePatternProperty"&&p(f.value)};p(a.id);for(let d of u){let f=O(d.span.start-e,t),h=O(d.span.end-e,t),E=o(d.span),y=G(f,r,n);l.push({name:d.name,kind:"VariableDeclaration",signature:K(E,"VariableDeclaration"),line:M(f,s),endLine:M(h,s),doc:y,classification:"Internal Variable",capabilities:"[]"})}}if(c.type==="FunctionDeclaration"){let a=c.identifier?.value||c.ident?.value||"anonymous",u=O(c.span.start-e,t),p=O(c.span.end-e,t),d=o(c.span),f=G(u,r,n);l.push({name:a,kind:"FunctionDeclaration",signature:K(d,"FunctionDeclaration"),line:M(u,s),endLine:M(p,s),doc:f,classification:"Internal Function",capabilities:"[]"})}if(c.type==="ReturnStatement"&&c.argument?.type==="ObjectExpression")for(let a of c.argument.properties){let u="",p=a.span||a.key?.span||a.ident?.span;if(a.type==="KeyValueProperty"){let d=a.key;u=d?.value||d?.raw||(d?.type==="Identifier"?d.value:"")}else a.type==="MethodProperty"?u=a.key?.value||a.key?.raw||"":a.type==="ShorthandProperty"?u=a.ident?.value||"":a.type==="Identifier"&&(u=a.value||"");if(u&&p){let d=O(p.start-e,t),f=O(p.end-e,t),h=o(p),E=G(d,r,n);l.push({name:u,kind:"ReturnProperty",signature:K(h,"ReturnProperty"),line:M(d,s),endLine:M(f,s),doc:E,classification:"Return Member",capabilities:"[]"})}}if(c.type==="ExpressionStatement"&&c.expression.type==="CallExpression"){let a=c.expression;if(a.callee.type==="MemberExpression"&&(a.callee.property?.value==="on"||a.callee.property?.value==="once")){let u=a.arguments[0]?.expression?.value,p=a.arguments[1]?.expression;if(u&&p&&(p.type==="ArrowFunctionExpression"||p.type==="FunctionExpression")){let d=O(p.span.start-e,t),f=O(p.span.end-e,t),h=o(p.span);l.push({name:`on:${u}`,kind:p.type,signature:K(h,p.type),line:M(d,s),endLine:M(f,s),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(a.callee.type==="Identifier"&&a.callee.value==="addRoute"&&a.arguments.length>=3){let u=a.arguments[2].expression;if(u.type==="StringLiteral"){let p=u.value,d=O(a.span.start-e,t),f=O(a.span.end-e,t),h=o(a.span);l.push({name:p,kind:"HTTP Route",signature:K(h,"HTTP Route"),line:M(d,s),endLine:M(f,s),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:p})})}}}}return l}function Mt(i,e,t,n,s){let r=[];function o(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let c=Cn(l);if(c){let a=O(l.span.start-e,t);r.push({...c,line:M(a,n),snippet:s(l.span)})}}for(let c of Object.keys(l)){if(c==="span")continue;let a=l[c];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==="Identifier"&&e.value,e.type==="Identifier"&&e.value==="addRoute"&&t.length>=3){let n=t[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(e.type==="MemberExpression"&&e.property?.type==="Identifier"){let n=e.property.value;if(n==="emit"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"produce"};if(n==="on"&&t[0].expression.type==="StringLiteral")return{type:"socket_event",name:t[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&t[0].expression.type==="StringLiteral"){let r=t[0].expression.value,o=e.object.type==="Identifier"?e.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(o))return{type:"api_route",name:r,direction:"produce"};if(r.startsWith("/"))return{type:"api_route",name:r,direction:"consume"}}}return e.type==="Identifier"&&e.value==="fetch"&&t[0].expression.type==="StringLiteral"?{type:"api_route",name:t[0].expression.value,direction:"produce"}:null}function 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(h=>r[h]).filter(Boolean).join(" and "),c={Component:(h,E)=>{let y=E.find(g=>g.kind==="FunctionDeclaration"||g.kind==="ClassDeclaration")?.name,m=y?`React component: ${y}`:"React UI component";return h?`${m} with ${h}`:m},Hook:(h,E)=>{let y=E.find(g=>g.name.startsWith("use"))?.name,m=y?`Custom React hook: ${y}`:"Custom React hook";return h?`${m} for ${h}`:m},Service:(h,E)=>{let m=`Service layer: ${E[0]?.name||"Service"}`;return h?`${m} handling ${h}`:m},Repository:(h,E)=>`Data repository: ${E[0]?.name||"Repository"} for ${h||"data access"}`,"Type Definition":(h,E)=>`Type definitions: ${E.slice(0,3).map(m=>m.name).join("")}${E.length>3?"...":""}`,Model:(h,E)=>`Data model: ${E[0]?.name||"Model"}`,"HTTP Route":(h,E)=>{let y=E.filter(m=>m.classification==="Service Boundary");return y.length>0?`API endpoints: ${y.slice(0,3).map(m=>m.name).join("")}`:"API route handler"},"Micro IR (PHP)":(h,E)=>{let y=E.some(g=>g.classification==="Service Boundary"),m=E.find(g=>g.kind==="ClassDeclaration")?.name;return y?"PHP controller with API routes":m?`PHP class: ${m}`:"PHP module"},"Micro IR (Python)":(h,E)=>{let y=E.some(g=>g.classification==="Service Boundary"),m=E.find(g=>g.kind==="ClassDeclaration")?.name;return y?"Python API handler with routes":m?`Python class: ${m}`:"Python module"},"Micro IR (Go/TS) ":(h,E)=>{let y=E.some(g=>g.kind==="TypeDeclaration"),m=E.filter(g=>g.kind==="FunctionDeclaration");return y&&m.length>0?`Go package: types and ${m.length} function(s)`:y?"Go package: type definitions":m.length>0?`Go package: ${m[0].name} and ${m.length} function(s)`:"Go module"},"Micro IR (Rust/TS) ":(h,E)=>{let y=E.find(b=>b.kind==="TraitDeclaration")?.name,m=E.find(b=>b.kind==="StructDeclaration")?.name,g=E.filter(b=>b.kind==="FunctionDeclaration");return y?h.includes("Rust trait")?`Rust module: trait ${y}`:`Rust module: ${y}`:m?`Rust module: struct ${m}`:g.length>0?`Rust module: ${g.length} function(s)`:"Rust module"}}[e];if(c)return c(o,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let a=n.filter(h=>h.kind==="FunctionDeclaration"),u=n.filter(h=>h.kind==="ClassDeclaration"),p=n.filter(h=>h.kind==="TsInterfaceDeclaration"||h.kind==="TsTypeAliasDeclaration"),d=[];if(u.length>0&&d.push(`Class: ${u[0].name}`),a.length>0){let h=a.slice(0,2).map(E=>E.name).join("");d.push(`Functions: ${h}`)}p.length>0&&d.push(`Types: ${p.length}`);let f=d.length>0?d.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
4
|
(function_definition name: (name) @name) @func
|
|
5
5
|
(class_declaration name: (name) @name) @class
|
|
6
6
|
(interface_declaration name: (name) @name) @interface
|
|
@@ -25,24 +25,24 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
25
25
|
(type_item name: (_type_identifier) @name) @type
|
|
26
26
|
(use_declaration argument: (_) @name) @import
|
|
27
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
|
-
`),
|
|
29
|
-
`),o="",
|
|
30
|
-
`).trim(),capabilities:JSON.stringify(L),members:[]}),
|
|
31
|
-
`).trim(),capabilities:JSON.stringify({attributes:
|
|
32
|
-
`).trim(),capabilities:JSON.stringify({attributes:
|
|
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:
|
|
34
|
-
`),r=[{indent:-1,name:"root",type:"root"}],o=[],
|
|
35
|
-
`).trim()),E=[]}else E.push(b);continue}let I=
|
|
36
|
-
`).length;s.push({name:
|
|
28
|
+
`),l=this.getQueries(n);if(!l)return[];let a=new ae.Query(s,l).matches(r.rootNode),u=[];for(let p of a){let d=p.captures.find(E=>E.name==="name")?.node,f=p.captures[0].node,h=p.captures[0].name;if(d){let E=f.startPosition.row+1,y=f.endPosition.row+1,m=o[f.startPosition.row].trim();u.push({name:d.text,kind:this.mapKind(h,n),classification:this.mapClassification(h),signature:m,line:E,endLine:y,doc:"",capabilities:"{}"})}}return u}};var Me=class{parse(e,t=!1){let n=[],s=[],r=e.split(`
|
|
29
|
+
`),o="",l="",c=0,a=0,u=-1,p=-1,d=[],f=[],h=!1,E=t?"api":"",y="",m=/^namespace\s+([a-zA-Z0-9_\\]+);/,g=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,b=/^interface\s+([a-zA-Z0-9_]+)/,A=/^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 x=r[R].trim();if(!x)continue;let w=(x.match(/{/g)||[]).length,D=(x.match(/}/g)||[]).length,j=a;if(a+=w-D,l&&a<=p){let L=n.find(T=>T.name===l&&T.line===c);L&&(L.endLine=R+1),l="",p=-1}if(o&&a<=u){let L=n.find(T=>T.name===o&&(T.kind==="ClassDeclaration"||T.kind==="TraitDeclaration"||T.kind==="InterfaceDeclaration"));L&&(L.endLine=R+1),o="",u=-1}let Q=x.match(N);if(Q&&(E=Q[1]),x.includes("});")&&(E=""),x.startsWith("/**")){h=!0,f=[];continue}if(h){x.endsWith("*/")?h=!1:f.push(x.replace(/^\*\s?/,""));continue}let V=x.match(v);if(V){d.push(V[1]);continue}let F=x.match(m);if(F){y=F[1]||"",d=[],f=[];continue}let k=x.match(g);if(k){o=k[1],u=a-w;let L={attributes:d};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:[]}),d=[],f=[];continue}let S=x.match(b);if(S){let L=S[1];o=L,u=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:d}),members:[]}),d=[],f=[];continue}let U=x.match(A);if(U){let L=U[1];o=L,u=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:d}),members:[]}),d=[],f=[];continue}let he=x.match(C);if(he){let L=he[1],T=!!o;l=L,c=R+1,p=a-w;let oe=!1,z={};for(let H of d)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:x})}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:d})}),d=[],f=[];continue}let se=x.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})}),d=[],f=[];continue}let ue=x.match($);if(ue){let L=ue[1].toUpperCase(),T=ue[2];if(x.includes("Route::")||x.includes("router->")||x.includes("action")||x.includes(",")&&!x.includes("view(")){if(E){let Z=E.startsWith("/")?E:`/${E}`,tt=T.startsWith("/")?T:`/${T}`;T=(Z+tt).replace(/\/+/g,"/")}let z=null,J=x.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(J)z=`${J[1]}@${J[2]}`;else if(x.includes("::class")){let Z=x.match(/([a-zA-Z0-9_]+)::class/);Z&&(z=Z[1])}let H=x;!x.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=x.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:x,method:L,url:T})}!x.startsWith("#[")&&!x.startsWith("//")&&!x.startsWith("*")&&!h&&(d=[],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=[],l=/^class\s+([a-zA-Z0-9_]+)/,c=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,a=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,u=/^@(.*)/;function p(m){return m.trim().split(/[.(]/)[0]?.trim()||m}function d(m){let g=m.decorators.map(A=>p(A.raw)),b={decorators:m.decorators,decoratorNames:g};return m.async===!0&&(b.async=!0),JSON.stringify(b)}let f=!1,h="",E=[],y=[];for(let m=0;m<s.length;m++){let g=s[m],b=g.trim();if(!b||b.startsWith("#"))continue;let A=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,C=b.match(A);if(C&&(this.currentRoutePrefix=C[2]),f){if(b.endsWith(h)||b.includes(h)){f=!1;let k=b.replace(h,"").trim();k&&E.push(k);let S=r[r.length-1];S.node&&(S.node.doc=E.join(`
|
|
35
|
+
`).trim()),E=[]}else E.push(b);continue}let I=g.search(/\S/),v=g.trim(),$=v.match(/^(['"]{3})/);if($){let k=$[1],S=r[r.length-1];if(S.node&&!S.node.doc){if(v.substring(3).includes(k)){let U=v.replace(new RegExp(k,"g"),"").trim();S.node.doc=U}else{f=!0,h=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(u);if(R){o.push({raw:R[1].trim(),line:m+1});continue}let x=v.match(l);if(x){let k=x[1],S={name:k,kind:"ClassDeclaration",classification:"Class",signature:`class ${k}`,line:m+1,endLine:m+1,doc:"",capabilities:d({decorators:o}),members:[]};y.push(S),N.node?(N.node.members||(N.node.members=[]),N.node.members.push(S)):t.push(S),r.push({indent:I,name:k,type:"class",node:S}),o=[];continue}let w=v.match(c);if(w){let k=!!w[1],S=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||S,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${S}`,line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({handler:U?`${N.name}.${S}`:S,async:k,...se})};y.push(oe),t.push(oe),n.push({type:"api_route",name:T,direction:"consume",line:m+1,snippet:v})}let ue=o.some(T=>T.raw==="staticmethod"),Le=o.some(T=>T.raw==="classmethod"),re=`${k?"async ":""}${U?(ue?"@staticmethod ":Le?"@classmethod ":"")+N.name+".":""}${S}`,L={name:S,kind:k&&U?"AsyncMethodDeclaration":k?"AsyncFunctionDeclaration":U?"MethodDeclaration":"FunctionDeclaration",classification:U?ue||Le?"Static Method":"Method":"Function",signature:re,line:m+1,endLine:m+1,doc:"",capabilities:d({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:S,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(/^\^/,""),S={name:k,kind:"HTTP Route",classification:"Service Boundary",signature:v.trim(),line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:k})};y.push(S),t.push(S),n.push({type:"api_route",name:k,direction:"consume",line:m+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(),S=V[2].trim();(S.startsWith("'")&&S.endsWith("'")||S.startsWith('"')&&S.endsWith('"'))&&(S=S.substring(1,S.length-1)),n.push({type:"api_route",name:S,direction:"produce",line:m+1,snippet:v,method:k,url:S})}let F=v.match(a);if(F){let k=F[1]||F[2],S={name:k,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${k}`,line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({type:"import",module:k})};y.push(S),t.push(S),o=[];continue}o=[],N.node&&(N.node.endLine=m+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 c=this.pythonParser.parse(t);s=c.nodes,r=c.events}else if(n===".php"){let c=e.toLowerCase().endsWith("api.php"),a=this.phpParser.parse(t,c);s=a.nodes,r=a.events}else try{s=await this.treeSitterParser.parse(e,t)}catch{}if(s.length>0){let c=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",a=s.filter(f=>f.classification!=="Dependency"),u=s.filter(f=>f.classification==="Dependency"),p=Hn(n,s),d=ye({classification:c,capabilities:p,exports:a.map(f=>({name:f.name,kind:f.kind,classification:f.classification})),fileName:ot.basename(e)});return{exports:a,imports:u.map(f=>({module:f.name,name:f.name,kind:f.kind,classification:f.classification})),events:r,classification:c,summary:d||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let o=Ht.find(c=>c.extension.includes(n));if(!o)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};for(let c of o.rules){c.regex.lastIndex=0;let a;for(;(a=c.regex.exec(t))!==null;){let u=c.onMatch(a),p=t.substring(0,a.index).split(`
|
|
36
|
+
`).length;s.push({name:u.name||"anonymous",kind:u.kind||"Unknown",classification:u.classification||"Other",signature:u.signature||a[0],line:p,endLine:p,doc:"",capabilities:JSON.stringify(u.meta||{})})}}let l=ye({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:s.map(c=>({name:c.name,kind:c.kind,classification:c.classification})),fileName:ot.basename(e)});return{exports:s,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:l||"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}),l=o.span.start,c=Ct(n),a=m=>kt(m,l,t),u=Nt(o.body),p=Ot(o.body);p.length>0&&_.debug({filePath:i,count:p.length},"Extracted type references"),p.forEach(m=>{u.push({module:"__type_reference__",name:m})});let d=Dt(o.body,l,t,n,s,c,i,a),f=Mt(o.body,l,t,s,a),h=ve(i,"","Module"),E=c.length>0&&c[0].start===0?c[0].text:d.find(m=>m.doc)?.doc||"",y=vt(E);if(!y&&d.length>0){let m=ge(n);y=ye({classification:h,capabilities:m,exports:d.map(g=>({name:g.name,kind:g.kind,classification:g.classification})),fileName:$t.basename(i)})}return{exports:d,imports:u,events:f,classification:h,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"),l=await ct.parse(i,o);return{...l,classification:l.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 l=we.relative(e,r.path).split(we.sep),c=s;for(let a=0;a<l.length;a++){let u=l[a];if(n!==void 0&&a>=n)return;let p=a===l.length-1;if(n===1&&a===0&&p)return;let d=n!==void 0&&a===n-1&&!p,f=we.join(e,...l.slice(0,a+1)),h=c.children?.find(E=>E.name===u);if(!h){if(c.children&&c.children.length>=jn){c.children.find(m=>m.type==="truncated")||c.children.push({name:"... (truncated) ",type:"truncated",path:"",children:void 0});return}h={name:u,type:p?"file":"directory",path:f,children:p||d?void 0:[],summary:p?{classification:r.classification,summaryText:r.summary,exports:r.exports,imports:r.imports,chunks:r.chunks}:void 0},h.summary&&(t==="structure"||t==="signatures")&&(delete h.summary.chunks,delete h.summary.imports),c.children?.push(h)}c=h}}),s}import xn from"p-limit";var ut=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 ut;function Ut(){be.recordIndexStart()}function pt(){be.recordIndexCacheHit()}function jt(i){be.recordIndexEnd(i)}function Fe(i,e){be.recordIndexPhase(i,e)}function Bt(){be.clearIndexPhases()}import Si 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 Kn(i){i.exec(`
|
|
37
37
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
38
38
|
version INTEGER PRIMARY KEY,
|
|
39
39
|
name TEXT NOT NULL,
|
|
40
40
|
applied_at REAL DEFAULT (unixepoch())
|
|
41
41
|
);
|
|
42
|
-
`)}function
|
|
42
|
+
`)}function zn(i){Kn(i);let e=i.prepare("SELECT version FROM schema_migrations ORDER BY version").all();return new Set(e.map(t=>t.version))}function Jn(){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(l=>l.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 l=parseInt(o[1],10),c=o[2],u=_e.readFileSync(dt.join(i,r),"utf-8").split(/^-- DOWN$/m),p=u[0].trim(),d=u[1]?.trim();s.push({version:l,name:c,up:p,down:d})}return s}function Yn(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=zn(i),n=Jn().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)Yn(i,s);Re.info("All migrations complete")}import Vn from"os";var Y=_.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);Y.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),Y.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 Kt(i,e){return e?ft(i)!==e:!0}function pe(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 zt(i){let e=He(i);if(!mt.existsSync(e))return!1;try{let t=pe(i);return t.prepare(`
|
|
43
43
|
SELECT value FROM index_metadata
|
|
44
44
|
WHERE key = 'index_completed'
|
|
45
|
-
`).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return
|
|
45
|
+
`).get()?.value==="true"?!0:t.prepare("SELECT COUNT(*) as count FROM files").get().count>0}catch(t){return Y.debug({repoPath:i,error:t},"Error checking index status"),!1}}function ht(i,e){let t=pe(i);t.prepare(`
|
|
46
46
|
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
47
47
|
VALUES ('index_completed', 'true', unixepoch())
|
|
48
48
|
`).run(),t.prepare(`
|
|
@@ -51,12 +51,12 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
51
51
|
`).run(Date.now().toString()),e&&t.prepare(`
|
|
52
52
|
INSERT OR REPLACE INTO index_metadata (key, value, updated_at)
|
|
53
53
|
VALUES ('last_indexed_commit', ?, unixepoch())
|
|
54
|
-
`).run(e),
|
|
54
|
+
`).run(e),Y.info({repoPath:i,commitSha:e},"Repository marked as indexed")}function Jt(i){try{return pe(i).prepare(`
|
|
55
55
|
SELECT value FROM index_metadata
|
|
56
56
|
WHERE key = 'last_indexed_commit'
|
|
57
|
-
`).get()?.value||null}catch(e){return
|
|
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],
|
|
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(),
|
|
57
|
+
`).get()?.value||null}catch(e){return Y.debug({repoPath:i,error:e},"Error getting last indexed commit"),null}}function Yt(i){let e=Pe.get(i)||He(i),t=X.get(e);t&&(t.open&&(Y.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&&(Y.info({dbPath:i},"Closing database connection"),e.close())}catch(t){Y.error({dbPath:i,err:t},"Error closing database execution")}X.clear()}process.on("exit",()=>Qt());var Vt=i=>{Y.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 l=ce.readdirSync(o);for(let c of l){let a=de.join(o,c,"package.json");if(ce.existsSync(a))try{let u=JSON.parse(ce.readFileSync(a,"utf8"));u.name&&t.set(u.name,{name:u.name,path:de.dirname(a),main:u.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),l=de.dirname(i),c=de.resolve(l,o),a=de.join(c,"package.json");if(ce.existsSync(a))try{let u=JSON.parse(ce.readFileSync(a,"utf8"));e.set(s,{name:s,path:c,main:u.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),l=new Map;if(o){let p=q.join(o,"package.json");if(me.existsSync(p))try{let d=JSON.parse(me.readFileSync(p,"utf8"));l=en(o,d)}catch{}}let c=q.join(e,"package.json");me.existsSync(c)&&tn(c).forEach((d,f)=>l.set(f,d));let a={baseUrl:s||"",paths:n.paths,matchPath:r,workspacePackages:l,imports:new Map},u=q.join(e,"package.json");if(me.existsSync(u))try{let p=JSON.parse(me.readFileSync(u,"utf8"));if(p.imports){for(let[d,f]of Object.entries(p.imports))if(typeof f=="string"||typeof f=="object"&&f!==null){let h=f;Array.isArray(f)&&(h=f[0]),typeof h=="object"&&(h=h.default||h.node),typeof h=="string"&&a.imports.set(d,h)}}}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),l=ne(o);if(l)return l}for(let[o,l]of n.imports.entries())if(o.includes("*")){let c="^"+o.replace(/[\\^$+.()|[\]{}]/g,"\\$&").replace(/\*/g,"(.*)")+"$",a=new RegExp(c),u=i.match(a);if(u){let p=u[1],d=l.replace("*",p),f=q.resolve(n.baseUrl,d);return ne(f)}}else if(o===i){let c=q.resolve(n.baseUrl,l);return ne(c)}let r=n.workspacePackages.get(i);if(r){let o=q.join(r.path,"src/index.ts");if(me.existsSync(o))return o;let l=q.join(r.path,r.main),c=ne(l);if(c)return c}}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"?ui(t,i):e==="turbo.json"?pi(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],l=r.slice(1).join("= ").trim()||"undefined",c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function 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(l=>{e.push({key:`service:${s}:port`,value:String(l),kind:"Port"})}),o.environment){if(Array.isArray(o.environment))o.environment.forEach(l=>{let[c,...a]=l.split("= ");c&&a.length>0&&e.push({key:`service:${s}:env:${c}`,value:a.join("= "),kind:"Env"})});else if(typeof o.environment=="object")for(let[l,c]of Object.entries(o.environment))e.push({key:`service:${s}:env:${l}`,value:String(c),kind:"Env"})}if(Array.isArray(o.depends_on))o.depends_on.forEach(l=>{e.push({key:`service:${s}:depends_on`,value:l,kind:"Dependency"})});else if(o.depends_on&&typeof o.depends_on=="object")for(let l of Object.keys(o.depends_on))e.push({key:`service:${s}:depends_on`,value:l,kind:"Dependency"})}let n=(s,r="")=>{if(!(!s||typeof s!="object"||Array.isArray(s)))for(let[o,l]of Object.entries(s)){let c=r?`${r}.${o}`:o;if(t.services&&(c.startsWith("services.")||c==="services")){l&&typeof l=="object"&&!Array.isArray(l)&&n(l,c);continue}if(l&&typeof l=="object"&&!Array.isArray(l))n(l,c);else{let a=String(l),u="Env";o.toLowerCase().includes("image")&&(u="Image"),o.toLowerCase().includes("port")&&(u="Port"),o.toLowerCase().includes("service")&&(u="Service"),(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(u="Service"),e.push({key:c,value:a.length>100?a.substring(0,97)+"...":a,kind:u})}}};n(t)}catch{let n=i.match(/^\s{2}([a-z0-9_-]+):/gm);n&&n.forEach(s=>{let r=s.trim().replace(" : ","");r!=="services"&&r!=="version"&&r!=="volumes"&&r!=="networks"&&e.push({key:"service",value:r,kind:"Service"})})}}function 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(),l=r.slice(1).join("=");l=l.trim().replace(/^['"](.*)['"]$/,"$1");let c="Env";(o.endsWith("_URI")||o.endsWith("_URL")||o.endsWith("_HOST"))&&(c="Service"),e.push({key:o,value:l,kind:c})}}}}function 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 l=/provider\s*=\s*"([^"]+)"/,c=i.match(l);return c&&t.push({key:"datasource_provider",value:c[1],kind:"Database Config"}),{classification:n,configs:t}}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],l="GraphQL Type";o.startsWith("input")&&(l="GraphQL Input"),o.startsWith("interface")&&(l="GraphQL Interface"),o.startsWith("enum")&&(l="GraphQL Enum"),t.push({key:"type_definition",value:r[1],kind:l})}return{classification:n,configs:t}}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(l=>o.includes(l))&&e.push({key:`script:${o}`,value:t.scripts[o],kind:"Env"})}let n={...t.dependencies,...t.devDependencies},s=["react","vue","svelte","angular","next","nuxt","express","fastify","nestjs","remix","vite","webpack","tailwindcss","database"];for(let r of Object.keys(n))if(s.some(o=>r.includes(o))){let o=n[r].replace(/[\^~]/,"");e.push({key:`dep:${r}`,value:o,kind:"Service"})}}catch{}}function ui(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 pi(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
60
|
SELECT * FROM files
|
|
61
61
|
WHERE (path LIKE ? OR path = ?)
|
|
62
62
|
ORDER BY path ASC
|
|
@@ -80,7 +80,7 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
80
80
|
AND file_path NOT LIKE '%.spec.%'
|
|
81
81
|
LIMIT ?
|
|
82
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
|
|
83
|
+
SELECT
|
|
84
84
|
COUNT(*) as total,
|
|
85
85
|
SUM(CASE WHEN summary IS NOT NULL AND summary != '' THEN 1 ELSE 0 END) as withSummary
|
|
86
86
|
FROM files
|
|
@@ -93,14 +93,14 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
93
93
|
OR m.id IN (${e.length>0?e.join(","):"-1"})
|
|
94
94
|
)
|
|
95
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
|
|
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 u=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.file_path].score+=u;let p=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.file_path].reasons.push(`${p}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
|
|
97
97
|
SELECT file_path, type, mission_id
|
|
98
98
|
FROM intent_logs
|
|
99
99
|
WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
|
|
100
100
|
AND file_path IS NOT NULL
|
|
101
101
|
ORDER BY created_at DESC
|
|
102
102
|
LIMIT 100
|
|
103
|
-
`,
|
|
103
|
+
`,l);for(let a of c){n[a.file_path]||(n[a.file_path]={score:1,reasons:[]});let u=a.mission_id?e.includes(a.mission_id):!1,p=u?.1:.2;n[a.file_path].score<5&&(n[a.file_path].score+=p);let d=u?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.file_path].reasons.includes(d)&&n[a.file_path].reasons.length<5&&n[a.file_path].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM files")?.count||0}getTopDirectories(e,t=8){return this.all(`
|
|
104
104
|
SELECT
|
|
105
105
|
SUBSTR(path, LENGTH(?) + 2,
|
|
106
106
|
INSTR(SUBSTR(path, LENGTH(?) + 2), '/') - 1
|
|
@@ -118,12 +118,12 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
118
118
|
ORDER BY total_files DESC
|
|
119
119
|
LIMIT ?
|
|
120
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
|
|
121
|
+
SELECT
|
|
122
122
|
path,
|
|
123
123
|
SUBSTR(path, LENGTH(?) + 2) as relPath
|
|
124
|
-
FROM files
|
|
124
|
+
FROM files
|
|
125
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 = ?"),
|
|
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 = ?"),l=this.db.prepare("DELETE FROM configs WHERE file_path = ?"),c=this.db.prepare("DELETE FROM file_content WHERE file_path = ?"),a=this.db.prepare("DELETE FROM event_synapses WHERE file_path = ?"),u=this.db.prepare("INSERT INTO exports (file_path, name, kind, signature, doc, start_line, end_line, classification, capabilities, parent_id, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),p=this.db.prepare("INSERT INTO imports (file_path, module_specifier, imported_symbols, resolved_path) VALUES (?, ?, ?, ?)"),d=this.db.prepare("INSERT INTO configs (file_path, key, value, kind) VALUES (?, ?, ?, ?)"),f=this.db.prepare("INSERT INTO file_content (file_path, content) VALUES (?, ?)"),h=this.db.prepare("INSERT INTO event_synapses (file_path, type, name, direction, line_number, code_snippet) VALUES (?, ?, ?, ?, ?, ?)"),E=this.db.prepare(`
|
|
127
127
|
INSERT INTO files (path, mtime, last_scanned_at, classification, summary, embedding, content_hash)
|
|
128
128
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
129
129
|
ON CONFLICT(path) DO UPDATE SET
|
|
@@ -133,7 +133,7 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
133
133
|
summary=excluded.summary,
|
|
134
134
|
embedding=excluded.embedding,
|
|
135
135
|
content_hash=excluded.content_hash
|
|
136
|
-
`);this.db.transaction(
|
|
136
|
+
`);this.db.transaction(m=>{for(let g of m){let{meta:b,exports:A,imports:C,configs:I,events:v,content:$,classification:N,summary:R,embedding:x}=g;r.run(b.path),o.run(b.path),l.run(b.path),c.run(b.path),a.run(b.path);let w=$?n($):null;if(E.run(b.path,b.mtime,Date.now(),N||"Unknown",R||"",x?JSON.stringify(x):null,w),A){let D=(j,Q,V)=>{for(let F of Q){let k=F.embedding?JSON.stringify(F.embedding):null,S=u.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,S.lastInsertRowid)}};D(b.path,A,null)}if(C)for(let D of C){let j=s(D.module,b.path,t);p.run(b.path,D.module,D.name,j)}if(I)for(let D of I)d.run(b.path,D.key,D.value,D.kind);if($!==void 0&&f.run(b.path,$),v)for(let D of v)h.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
137
|
SELECT * FROM exports
|
|
138
138
|
WHERE file_path = ? AND start_line <= ? AND end_line >= ?
|
|
139
139
|
ORDER BY (end_line - start_line) ASC -- Get innermost symbol
|
|
@@ -215,16 +215,16 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
215
215
|
WHERE file_path = ? AND parent_id IS NULL
|
|
216
216
|
ORDER BY start_line ASC
|
|
217
217
|
`,e)}findFts(e,t=20){return this.all(`
|
|
218
|
-
SELECT e.*
|
|
218
|
+
SELECT e.*
|
|
219
219
|
FROM exports e
|
|
220
|
-
JOIN exports_fts
|
|
221
|
-
WHERE
|
|
220
|
+
JOIN exports_fts ON e.id = exports_fts.rowid
|
|
221
|
+
WHERE exports_fts MATCH ?
|
|
222
222
|
LIMIT ?
|
|
223
223
|
`,e,t)}findByPartialName(e,t=20){return this.all(`
|
|
224
224
|
SELECT * FROM exports
|
|
225
225
|
WHERE lower(name) LIKE ?
|
|
226
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,
|
|
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={}){let{limit:t=50,includeTests:n=!1,includeMigrations:s=!1,includeFixtures:r=!1,excludePatterns:o=[],confidenceThreshold:l="all"}=e,c=[];n||(c.push("e.file_path NOT LIKE '%/test/%'"),c.push("e.file_path NOT LIKE '%/tests/%'"),c.push("e.file_path NOT LIKE '%/__tests__/%'"),c.push("e.file_path NOT LIKE '%.spec.%'"),c.push("e.file_path NOT LIKE '%.test.%'")),s||(c.push("e.file_path NOT LIKE '%/migrations/%'"),c.push("e.file_path NOT LIKE '%/migration/%'"),c.push("e.file_path NOT LIKE '%Migration.%'")),r||(c.push("e.file_path NOT LIKE '%/__fixtures__/%'"),c.push("e.file_path NOT LIKE '%/__mocks__/%'"),c.push("e.file_path NOT LIKE '%/fixtures/%'"),c.push("e.file_path NOT LIKE '%/mocks/%'"),c.push("e.file_path NOT LIKE '%.fixture.%'"),c.push("e.file_path NOT LIKE '%.mock.%'"));for(let f of o){let h=f.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_");c.push(`e.file_path NOT LIKE '${h}'`)}let a=c.length>0?`AND ${c.join(" AND ")}`:"",p=this.all(`
|
|
228
228
|
SELECT e.name, e.kind, e.file_path, e.start_line
|
|
229
229
|
FROM exports e
|
|
230
230
|
WHERE e.kind IN (
|
|
@@ -233,12 +233,12 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
233
233
|
'ArrowFunctionExpression', 'FunctionExpression'
|
|
234
234
|
)
|
|
235
235
|
AND e.parent_id IS NULL
|
|
236
|
-
${
|
|
236
|
+
${a}
|
|
237
237
|
AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.imported_symbols LIKE '%' || e.name || '%')
|
|
238
238
|
AND NOT EXISTS (SELECT 1 FROM imports i WHERE i.resolved_path = e.file_path AND i.imported_symbols LIKE '%*%')
|
|
239
239
|
ORDER BY e.file_path, e.start_line
|
|
240
240
|
LIMIT ?
|
|
241
|
-
`,e)}getGravityMap(e=[],t){let n={},s=`
|
|
241
|
+
`,t*2).map(f=>{let{confidence:h,reason:E}=this.scoreDeadExportConfidence(f);return{...f,confidence:h,reason:E}}),d=p;return l==="high"?d=p.filter(f=>f.confidence==="high"):l==="medium"&&(d=p.filter(f=>f.confidence==="high"||f.confidence==="medium")),d.slice(0,t)}scoreDeadExportConfidence(e){let t=e.file_path.toLowerCase(),n=e.name;return t.includes("/index.")||t.endsWith("index.ts")||t.endsWith("index.js")?{confidence:"low",reason:"Barrel/index file - likely re-export"}:e.kind==="TsInterfaceDeclaration"||e.kind==="TsTypeAliasDeclaration"?{confidence:"medium",reason:"Type definition - may be used externally"}:t.includes("/entry/")||t.includes("/bin/")||t.includes("main.")||t.includes("server.")||t.includes("cli.")?{confidence:"medium",reason:"Entry point - may be invoked externally"}:n.startsWith("create")||n.endsWith("Factory")||n.endsWith("Builder")?{confidence:"medium",reason:"Factory/builder pattern - may be used dynamically"}:n.startsWith("use")&&n.length>3?{confidence:"medium",reason:"Hook pattern - may be used in components"}:{confidence:"high",reason:"No detected usage"}}getGravityMap(e=[],t){let n={},s=`
|
|
242
242
|
SELECT ws.symbol_id, m.name as mission_name, m.status
|
|
243
243
|
FROM working_set ws
|
|
244
244
|
JOIN missions m ON ws.mission_id = m.id
|
|
@@ -247,14 +247,14 @@ import Ln from"fast-glob";import nt from"fs";import kn from"ignore";import It fr
|
|
|
247
247
|
OR m.id IN (${e.length>0?e.join(","):"-1"})
|
|
248
248
|
)
|
|
249
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
|
|
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 u=a.status==="in-progress"||a.status==="verifying"?1:.5;n[a.symbol_id].score+=u;let p=a.status==="in-progress"||a.status==="verifying"?"Working Set":"Lineage Bleed";n[a.symbol_id].reasons.push(`${p}: ${a.mission_name}`)}let l=Math.floor(Date.now()/1e3)-86400,c=this.all(`
|
|
251
251
|
SELECT symbol_id, type, mission_id
|
|
252
252
|
FROM intent_logs
|
|
253
253
|
WHERE (created_at > ? OR mission_id IN (${e.length>0?e.join(","):"-1"}))
|
|
254
254
|
AND symbol_id IS NOT NULL
|
|
255
255
|
ORDER BY created_at DESC
|
|
256
256
|
LIMIT 200
|
|
257
|
-
`,
|
|
257
|
+
`,l);for(let a of c){n[a.symbol_id]||(n[a.symbol_id]={score:1,reasons:[]});let u=a.mission_id?e.includes(a.mission_id):!1,p=u?.1:.2;n[a.symbol_id].score<5&&(n[a.symbol_id].score+=p);let d=u?`Lineage Intent: ${a.type}`:`Recent Intent: ${a.type}`;!n[a.symbol_id].reasons.includes(d)&&n[a.symbol_id].reasons.length<5&&n[a.symbol_id].reasons.push(d)}return n}getCount(){return this.get("SELECT COUNT(*) as count FROM exports")?.count||0}getKindDistribution(e=5){return this.all(`
|
|
258
258
|
SELECT kind, COUNT(*) as c
|
|
259
259
|
FROM exports
|
|
260
260
|
WHERE kind IS NOT NULL AND kind != ''
|
|
@@ -302,7 +302,14 @@ WITH RECURSIVE dependency_chain AS (
|
|
|
302
302
|
FROM imports i
|
|
303
303
|
JOIN dependency_chain dc ON i.resolved_path = dc.consumer_path
|
|
304
304
|
WHERE dc.depth < ? -- Max depth limit
|
|
305
|
-
AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection
|
|
305
|
+
AND instr(dc.path_chain, i.file_path) = 0 -- Cycle detection
|
|
306
|
+
AND (
|
|
307
|
+
-- If the intermediate file is a re-exporter (barrel),
|
|
308
|
+
-- the next consumer must still be looking for the symbol
|
|
309
|
+
i.imported_symbols LIKE ?
|
|
310
|
+
OR i.imported_symbols = '*'
|
|
311
|
+
OR i.imported_symbols = ''
|
|
312
|
+
)
|
|
306
313
|
)
|
|
307
314
|
SELECT DISTINCT
|
|
308
315
|
dc.consumer_path,
|
|
@@ -337,7 +344,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
337
344
|
SELECT COUNT(*) as count FROM imports
|
|
338
345
|
WHERE resolved_path IN (${n})
|
|
339
346
|
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
|
|
347
|
+
`,...e,`%${t}%`)?.count||0}findImpactDependents(e,t,n){return this.all(ln,e,t,n,t)}getCount(){return this.get("SELECT COUNT(*) as count FROM imports")?.count||0}};var Ke=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
348
|
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
342
349
|
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
350
|
CASE WHEN status = 'in-progress' THEN 0 WHEN status = 'verifying' THEN 1 ELSE 2 END,
|
|
@@ -358,7 +365,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
358
365
|
GROUP BY m.id
|
|
359
366
|
HAVING log_count > ?
|
|
360
367
|
`,e,t).map(s=>s.id)}getStats(){let e=this.get(`
|
|
361
|
-
SELECT
|
|
368
|
+
SELECT
|
|
362
369
|
COUNT(*) as total,
|
|
363
370
|
SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
|
|
364
371
|
SUM(CASE WHEN status IN ('in-progress', 'planned', 'verifying') THEN 1 ELSE 0 END) as active
|
|
@@ -367,7 +374,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
367
374
|
SELECT AVG(updated_at - created_at) AS avg_duration
|
|
368
375
|
FROM missions
|
|
369
376
|
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,
|
|
377
|
+
`),s=n?.avg_duration!=null?Math.round(n.avg_duration):null,r=Math.floor(Date.now()/1e3)-168*3600,o=Math.floor(Date.now()/1e3)-720*3600,l=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",r),c=this.get("SELECT COUNT(*) AS n FROM missions WHERE status = 'completed' AND updated_at >= ?",o),a=l?.n??0,u=c?.n??0,p=`${a} completed in last 7 days, ${u} in last 30 days.`;if(s!=null){let d=Math.round(s/60);p+=` Avg mission duration: ${d} min.`}return{completionRate:t,averageDurationSeconds:s,completedLast7Days:a,completedLast30Days:u,velocityNote:p}}suspendByBranch(e){this.run(`UPDATE missions
|
|
371
378
|
SET status = 'suspended', updated_at = unixepoch()
|
|
372
379
|
WHERE git_branch = ? AND status IN ('in-progress', 'planned', 'verifying')`,e)}resumeByBranch(e){this.run(`UPDATE missions
|
|
373
380
|
SET status = 'in-progress', updated_at = unixepoch()
|
|
@@ -392,7 +399,7 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
392
399
|
SELECT linked_repo_path, linked_mission_id, relationship, direction
|
|
393
400
|
FROM cross_repo_links
|
|
394
401
|
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
|
|
402
|
+
`,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 ze=class extends P{findByMission(e,t=50){return this.all(`
|
|
396
403
|
SELECT * FROM intent_logs
|
|
397
404
|
WHERE mission_id = ?
|
|
398
405
|
ORDER BY created_at DESC
|
|
@@ -430,24 +437,24 @@ ORDER BY dc.depth, dc.consumer_path;
|
|
|
430
437
|
`,e)}importHeritage(e,t,n,s){this.run(`
|
|
431
438
|
INSERT INTO intent_logs (type, content, commit_sha, created_at, confidence, mission_id)
|
|
432
439
|
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
|
|
440
|
+
`,e,t,n,s)}countByType(e){return this.get("SELECT COUNT(*) as count FROM intent_logs WHERE type = ?",e)?.count||0}};var Je=class extends P{findByKey(e,t=20){return this.all(`
|
|
434
441
|
SELECT file_path, key, value, kind
|
|
435
442
|
FROM configs
|
|
436
443
|
WHERE key LIKE ? OR value LIKE ?
|
|
437
444
|
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
|
|
445
|
+
`,`%${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 Ye=class extends P{search(e,t=10){return this.all(`
|
|
439
446
|
SELECT file_path, snippet(content_fts, 1, '<b>', '</b>', '...', 20) as snippet
|
|
440
447
|
FROM content_fts
|
|
441
448
|
WHERE content_fts MATCH ?
|
|
442
449
|
LIMIT ?
|
|
443
|
-
`,e,t)}};var
|
|
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)<=
|
|
450
|
+
`,e,t)}};var un=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
|
|
451
|
+
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)<=un||this.run(`DELETE FROM search_history WHERE id NOT IN (
|
|
445
452
|
SELECT id FROM search_history ORDER BY created_at DESC LIMIT ?
|
|
446
|
-
)`,
|
|
453
|
+
)`,un)}};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
454
|
INSERT INTO hologram_snapshot (section, data, updated_at)
|
|
448
455
|
VALUES (?, ?, unixepoch())
|
|
449
456
|
ON CONFLICT(section) DO UPDATE SET
|
|
450
457
|
data = excluded.data,
|
|
451
458
|
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(
|
|
459
|
+
`,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=pe(e),o=t.files?.database,l=!t.intentLogs||!t.searchHistory||!t.missions||!t.hologram;if(o===r&&r.open&&!l)return t;this.repositoryCache.delete(e)}let n=pe(e),s={files:new Be(n),exports:new qe(n),imports:new Ge(n),missions:new Ke(n),intentLogs:new ze(n),configs:new Je(n),content:new Ye(n),searchHistory:new Qe(n),hologram:new Ve(n)};return this.repositoryCache.set(e,s),s}static closeInstance(e){this.repositoryCache.delete(e),Yt(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 pn}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=pn(mn,"worker.ts");if(dn(e))return e}let i=pn(mn,"worker.js");return dn(i)?i:Ne("dist/logic/domain/embeddings/worker.js")}var xe=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}),l={worker:o,busy:!1,currentTaskId:null};o.on("message",c=>{if(c.type==="ready"){if(clearTimeout(r),this.shutdownRequested){_.debug({workerIndex:t},"Worker ready but shutdown requested, terminating"),o.terminate().catch(()=>{}),n();return}this.workers.push(l),_.debug({workerIndex:t},"Worker ready"),n()}else c.type==="result"&&c.id?this.handleTaskComplete(l,c.id,c.embeddings||[]):c.type==="error"&&c.id&&this.handleTaskError(l,c.id,new Error(c.error||"Unknown error"))}),o.on("error",c=>{if(clearTimeout(r),_.error({err:c,workerIndex:t},"Worker error"),l.currentTaskId&&this.handleTaskError(l,l.currentTaskId,c),!this.initialized){s(c);return}let a=this.workers.indexOf(l);a!==-1&&this.workers.splice(a,1),!this.shutdownRequested&&this.initialized&&this.createWorker(e,t).catch(u=>{_.error({err:u},"Failed to replace crashed worker")})}),o.on("exit",c=>{c!==0&&!this.shutdownRequested&&_.warn({workerIndex:t,code:c},"Worker exited unexpectedly")})})}handleTaskComplete(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.resolve(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}handleTaskError(e,t,n){let s=this.pendingTasks.get(t);s&&(this.pendingTasks.delete(t),s.reject(n)),e.busy=!1,e.currentTaskId=null,this.processQueue()}processQueue(){if(this.taskQueue.length===0)return;let e=this.workers.find(n=>!n.busy);if(!e)return;let t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTaskId=t.id,this.pendingTasks.set(t.id,t),e.worker.postMessage({type:"embed",id:t.id,texts:t.texts}))}async generateEmbeddings(e,t=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,l=s.map((a,u)=>new Promise((p,d)=>{let h={id:`task_${++this.taskIdCounter}`,texts:a,resolve:E=>{if(r[u]=E,o++,n){let y=Math.min(o*t,e.length);n(y,e.length)}p()},reject:E=>{if(r[u]=new Array(a.length).fill(null),o++,_.warn({err:E,chunkIndex:u},"Chunk embedding failed"),n){let y=Math.min(o*t,e.length);n(y,e.length)}p()}};this.taskQueue.push(h),this.processQueue()}));await Promise.all(l);let c=[];for(let a of r)c.push(...a);return _.info({total:e.length,successful:c.filter(a=>a!==null).length,workers:this.workers.length},"Parallel embedding generation complete"),c}get workerCount(){return this.workers.length}get busyWorkers(){return this.workers.filter(e=>e.busy).length}get queueSize(){return this.taskQueue.length}get isInitialized(){return this.initialized}async shutdown(){if(this.shutdownRequested=!0,this.initPromise)try{await this.initPromise}catch{}if(!this.initialized&&this.workers.length===0){this.shutdownRequested=!1,this.initPromise=void 0;return}_.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 xe(i)),fe}async function hn(){fe&&(await fe.shutdown(),fe=null)}var Se=null;async function Ri(){return Se||(Se=await import("@xenova/transformers"),Se.env.cacheDir="./.cache",Se.env.allowLocalModels=!1),Se}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),l=i.slice(r,o);try{let c=await s(l,{pooling:"mean",normalize:!0}),[a,u]=c.dims;for(let p=0;p<a;p++){let d=p*u,f=d+u;n[r+p]=Array.from(c.data.slice(d,f))}}catch(c){_.error({err:c,batchStart:r,batchEnd:o},"Single-threaded batch embedding failed, falling back to sequential for this chunk");for(let a=0;a<l.length;a++)try{let u=l[a];if(!u||u.trim().length===0)continue;let p=await s(u,{pooling:"mean",normalize:!0});n[r+a]=Array.from(p.data)}catch{n[r+a]=null}}t&&t(o,i.length)}return _.debug({total:i.length,successful:n.filter(r=>r!==null).length},"Batch embedding complete"),n}function xi(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(l=>l.text),o=await En(r,r.length);if(s.forEach((l,c)=>{this.results.set(l.id,o[c])}),n){let l=t-this.queue.length;n(l,t)}}}async processQueueParallel(e,t,n){let s=this.queue.splice(0),r=s.map(c=>c.text),l=await Ze().generateEmbeddings(r,e,(c,a)=>{n&&n(c,a)});s.forEach((c,a)=>{this.results.set(c.id,l[a])})}clear(){this.queue=[],this.results.clear()}};import{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 l=r.find(c=>c.signature===s.signature)||r[0];this.intentLogs.update(s.id,{symbol_id:l.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 l=o.filter(c=>c.file_path!==s.file_path);if(l.length>0){let c=l.find(a=>a.signature===s.signature)||l[0];this.intentLogs.update(s.id,{symbol_id:c.id,file_path:c.file_path}),le.info({logId:s.id,symbol:s.symbol_name,oldPath:s.file_path,newPath:c.file_path},"Detected Nano-Repair Shift (file move)"),t++;continue}}n++}return t>0&&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(`
|
|
460
|
+
`).map(l=>l.trim().replace(/^\* /,"")).filter(l=>l&&l!==e)}catch{}let r=0;if(s.length>0){let o=this.missions.findMergedMissions(e,s);for(let l of o)this.missions.updateStatus(l.id,"completed"),le.info({missionId:l.id,branch:l.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 xt(i,e=Li,t=!1,n=!0,s){let r=ie.getInstance(i),o=r.files.database,l=je(i),c=l.concurrency??e;if(Ut(),!t&&zt(i)){let m=Jt(i),g=Ie(i);if(m&&!Rn(i,m))return pt(),_.debug({repoPath:i,commit:g},"Index is current, skipping re-index (fast-path)"),o}$e(i);let a=r.files.findAll(),u=new Map(a.map(m=>[m.path,{mtime:m.mtime,hash:m.content_hash}])),p=Date.now();s?.({phase:"scan",current:0,total:0,message:"Scanning repository..."});let d=await it(i,l.ignore),f=new Map(d.map(m=>[m.path,m.mtime])),h=a.filter(m=>!f.has(m.path)).map(m=>m.path),E=a.length===0,y=[];if(t||E)y.push(...d);else{let m=d.filter(C=>{let I=u.get(C.path);return!I||I.mtime!==C.mtime}),g=xn(c*4),b=m.map(C=>g(async()=>{let I=u.get(C.path);if(!I||!I.hash)return C;try{let v=await Tt.promises.readFile(C.path,"utf8");return Kt(v,I.hash)?C:(r.files.updateMtime(C.path,C.mtime),null)}catch{return null}})),A=await Promise.all(b);y.push(...A.filter(C=>C!==null))}if(h.length===0&&y.length===0){if(pt(),E){let m=Ie(i);ht(i,m||void 0)}return o}if(E?_.info({totalFiles:d.length},"Starting initial repository indexing..."):_.info({toDelete:h.length,toProcess:y.length},"Syncing repository updates..."),h.length>0&&r.files.deletePaths(h),y.length>0){Bt(),n?Xe(!0):Xe(!1);let m=xn(c),g=0,b=y.length,A=y.map(N=>m(async()=>{try{let R=Si.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 g++,(g%50===0||g===b)&&_.info({completed:g,total:b},"Parsing files..."),s?.({phase:"parse",current:g,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 g++,(g%50===0||g===b)&&_.info({completed:g,total:b},"Parsing configs..."),s?.({phase:"parse",current:g,total:b,message:`Parsing config ${R}`}),{meta:N,...w,content:D,embedding:null,kind:"config"}}}catch(R){return g++,_.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(A)).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 x=Date.now()-N;Fe("embed",x),_.info({time:`${(x/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 m=Ie(i);ht(i,m||void 0)}return(y.length>0||h.length>0)&&new et(i).detectAndRepairShifts(),jt(Date.now()-p),s?.({phase:"complete",current:y.length,total:y.length,message:"Indexing complete"}),o}import Sn 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 xt(i,e);let{files:r,exports:o,imports:l}=ie.getInstance(i),c=n?r.findInSubPath(i,n):r.findAll(),a=je(i),u=ki(),p=Sn.join(i,".gitignore");if(In.existsSync(p)&&u.add(In.readFileSync(p,"utf8")),a.ignore&&a.ignore.length>0&&u.add(a.ignore),u.add(ke),c=c.filter(g=>{let b=Sn.relative(i,g.path);return!u.ignores(b)}),_.info({count:c.length},"Fetching data from DB..."),t==="lite"){let g=c.map(b=>({path:b.path,mtime:b.mtime}));return Ee(g,i,t,s)}if(t==="summaries"){let g=c.map(b=>({path:b.path,mtime:b.mtime,classification:b.classification||void 0,summary:b.summary||void 0}));return Ee(g,i,t,s)}let d=c.map(g=>g.path),f=o.findByFiles(d),h=t==="detailed"?l.findByFiles(d):[],E=new Map;for(let g of f){let b=E.get(g.file_path)||[];b.push(g),E.set(g.file_path,b)}let y=new Map;for(let g of h){let b=y.get(g.file_path)||[];b.push(g),y.set(g.file_path,b)}let m=c.map(g=>{let A=(E.get(g.path)||[]).map(I=>({name:I.name,kind:I.kind,signature:I.signature,line:I.start_line}));t==="structure"?A=A.map(I=>({name:I.name,kind:I.kind,line:I.line})):t==="signatures"&&(A=A.map(I=>({name:I.name,kind:I.kind,signature:I.signature,line:I.line})));let C=[];return t==="detailed"&&(C=(y.get(g.path)||[]).map(v=>({module:v.module_specifier,resolved_path:v.resolved_path}))),{path:g.path,mtime:g.mtime,classification:g.classification||void 0,summary:g.summary||void 0,exports:A,imports:C.length>0?C:void 0,chunks:[]}});return _.info({count:m.length},"Building hierarchical project tree..."),Ee(m,i,t,s)}export{Et as EmbeddingPriorityQueue,xe as EmbeddingWorkerPool,Ee as buildTree,Un as chunkFile,xi as cosineSimilarity,xt 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};
|