@precisionutilityguild/liquid-shadow 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +2 -2
  2. package/dist/data/migrations/000_baseline.sql +277 -0
  3. package/dist/entry/cli/index.js +708 -431
  4. package/dist/entry/mcp/server.js +349 -296
  5. package/dist/index.js +676 -123
  6. package/dist/logic/domain/embeddings/worker.js +1 -1
  7. package/dist/logic/parser/index.js +14 -13
  8. package/dist/skills/shadow_audit/SKILL.md +40 -0
  9. package/dist/skills/shadow_chronicle/SKILL.md +40 -0
  10. package/dist/skills/shadow_continue/SKILL.md +55 -0
  11. package/dist/skills/shadow_crystallize/SKILL.md +41 -0
  12. package/dist/skills/shadow_mission/SKILL.md +50 -0
  13. package/dist/skills/shadow_onboard/SKILL.md +35 -0
  14. package/dist/skills/shadow_research/SKILL.md +34 -0
  15. package/dist/skills/shadow_sync/SKILL.md +18 -0
  16. package/dist/skills/shadow_synthesize/SKILL.md +47 -0
  17. package/dist/skills/shadow_trace_impact/SKILL.md +55 -0
  18. package/dist/skills/shadow_understand/SKILL.md +51 -0
  19. package/dist/skills/shadow_workspace/SKILL.md +30 -0
  20. package/dist/web-manifest.json +1 -1
  21. package/package.json +3 -2
  22. package/skills/shadow_audit/SKILL.md +40 -0
  23. package/skills/shadow_chronicle/SKILL.md +40 -0
  24. package/skills/shadow_continue/SKILL.md +55 -0
  25. package/skills/shadow_crystallize/SKILL.md +41 -0
  26. package/skills/shadow_mission/SKILL.md +50 -0
  27. package/skills/shadow_onboard/SKILL.md +35 -0
  28. package/skills/shadow_research/SKILL.md +34 -0
  29. package/skills/shadow_sync/SKILL.md +18 -0
  30. package/skills/shadow_synthesize/SKILL.md +47 -0
  31. package/skills/shadow_trace_impact/SKILL.md +55 -0
  32. package/skills/shadow_understand/SKILL.md +51 -0
  33. package/skills/shadow_workspace/SKILL.md +30 -0
@@ -1 +1 @@
1
- import{parentPort as i,workerData as y}from"worker_threads";import g from"pino";var p={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},m=g({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(e,r){return{level:e,severity:p[r]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),a=m;var n=null;async function f(){return n||(n=await import("@xenova/transformers"),n.env.cacheDir=y?.cacheDir||"./.cache",n.env.allowLocalModels=!0),n}var c=null;async function M(){let{pipeline:e}=await f();c=await e("feature-extraction","Xenova/all-MiniLM-L6-v2")}async function h(e){if(e.length===0)return[];try{let r=await c(e,{pooling:"mean",normalize:!0}),[t,s]=r.dims,o=[];for(let l=0;l<t;l++){let d=l*s,u=d+s;o.push(Array.from(r.data.slice(d,u)))}return o}catch(r){a.error({err:r,batchSize:e.length},"Vectorized batch embedding failed, falling back to sequential");let t=[];for(let s of e){if(!s||s.trim().length===0){t.push(null);continue}try{let o=await c(s,{pooling:"mean",normalize:!0});t.push(Array.from(o.data))}catch{t.push(null)}}return t}}async function b(e){if(e.type==="shutdown"&&process.exit(0),e.type==="embed")try{let r=await h(e.texts),t={type:"result",id:e.id,embeddings:r};i?.postMessage(t)}catch(r){let t={type:"error",id:e.id,error:r instanceof Error?r.message:String(r)};i?.postMessage(t)}}async function v(){await M();let e={type:"ready"};i?.postMessage(e),i?.on("message",r=>{b(r).catch(t=>{a.error({error:t},"Worker error")})})}v().catch(e=>{a.error({error:e},"Failed to initialize embedding worker"),process.exit(1)});
1
+ import{parentPort as c,workerData as h}from"worker_threads";import m from"pino";var y={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},M=m({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(t,e){return{level:t,severity:y[e]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),o=M;var u=process.env.EMBEDDING_MODEL??"Xenova/all-MiniLM-L6-v2",a=process.env.EMBEDDING_DTYPE??"fp32",i=null;async function E(){return i||(i=await import("@xenova/transformers"),i.env.cacheDir=h?.cacheDir||"./.cache",i.env.allowLocalModels=!0),i}var l=null;function p(t=!1){let e=(a||"").toLowerCase(),r={};return a&&(r.dtype=a),t?(r.quantized=!1,r):(e==="fp32"||e==="fp16"||e==="float32"||e==="float16"?r.quantized=!1:e.startsWith("q")&&(r.quantized=!0),r)}async function b(){let{pipeline:t}=await E(),e=p(!1);try{l=await t("feature-extraction",u,e)}catch(r){let n=r?.message||"";if(!(n.includes("/onnx/model_quantized.onnx")||n.includes("model_quantized.onnx")))throw r;o.warn({model:u,dtype:a},"Quantized ONNX artifact missing, retrying with unquantized ONNX"),l=await t("feature-extraction",u,p(!0))}}async function w(t){if(t.length===0)return[];try{let e=await l(t,{pooling:"mean",normalize:!0}),[r,n]=e.dims,s=[];for(let d=0;d<r;d++){let g=d*n,f=g+n;s.push(Array.from(e.data.slice(g,f)))}return s}catch(e){o.error({err:e,batchSize:t.length},"Vectorized batch embedding failed, falling back to sequential");let r=[];for(let n of t){if(!n||n.trim().length===0){r.push(null);continue}try{let s=await l(n,{pooling:"mean",normalize:!0});r.push(Array.from(s.data))}catch{r.push(null)}}return r}}async function v(t){if(t.type==="shutdown"&&process.exit(0),t.type==="embed")try{let e=await w(t.texts),r={type:"result",id:t.id,embeddings:e};c?.postMessage(r)}catch(e){let r={type:"error",id:t.id,error:e instanceof Error?e.message:String(e)};c?.postMessage(r)}}async function z(){await b();let t={type:"ready"};c?.postMessage(t),c?.on("message",e=>{v(e).catch(r=>{o.error({error:r},"Worker error")})})}z().catch(t=>{o.error({error:t},"Failed to initialize embedding worker"),process.exit(1)});
@@ -1,6 +1,6 @@
1
- import fe from"@swc/core";import Pe from"fs";function he(e){let t=e.split(`
2
- `),i=[],n=0;for(let s of t)i.push(n),n+=s.length+1;return i}function I(e,t){for(let i=0;i<t.length;i++)if(t[i+1]>e||i===t.length-1)return i+1;return 1}function te(e,t){return t.slice(0,e).toString("utf8").length}function ye(e){if(e.toString("utf8").length===e.length)return n=>n;let i=new Map;return n=>{let s=i.get(n);return s===void 0&&(s=e.slice(0,n).toString("utf8").length,i.set(n,s)),s}}function ge(e,t,i){let n=e.start-t,s=e.end-t;return n<0||s>i.length?"":i.slice(n,s).toString("utf8")}function be(e){let t=[],i=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=i.exec(e))!==null;)t.push({start:n.index,end:n.index+n[0].length,text:n[0]});return t}function F(e,t,i){for(let n of t){if(n.start===e)return n.text;if(n.start>e&&n.start<e+50){let s=i.substring(e,n.start);if(/^\s*$/.test(s))return n.text}if(n.end<=e&&n.end>e-50){let s=i.substring(n.end,e);if(/^\s*$/.test(s))return n.text}}return""}function xe(e){if(!e)return"";let i=e.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
3
- `)[0].trim();return i.length>200?i.substring(0,197)+"...":i}function ne(e,t,i){let n=e.toLowerCase(),s=t.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":i==="TsInterfaceDeclaration"||i==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function K(e){let t=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(e)&&t.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(e)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(e)||/\.query\s*\(|\.execute\s*\(/i.test(e)&&/db|database|client|pool/i.test(e))&&t.push("Database"),(/\bfs\./i.test(e)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(e)||/import\s+.*\bfs\b/.test(e))&&t.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(e)||/\bdocument\.cookie\b/.test(e))&&t.push("Browser Storage"),t}function N(e,t){if(!e)return"";let i=e.replace(/^([\s\S]*?\*\/)?\s*/,"").replace(/^.*\} from ['"].*['"];?\s*/,"").replace(/^import .*['"];?\s*/,"").trim();if(t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration")return i;let n=0,s=0,p=i.length;for(let d=0;d<i.length;d++){let h=i[d];if(h==="(")n++;else if(h===")")n--;else if(h==="<")s++;else if(h===">")s--;else if(h==="{"){if(n===0&&s===0){p=d;break}}else if(h==="; "&&n===0&&s===0){p=d;break}else if(h==="="&&i[d+1]===">"&&n===0&&s===0){p=d+2;break}}return i.substring(0,p).trim()}function De(e){let t=[];for(let i of e)i.type==="ImportDeclaration"&&t.push({module:i.source.value,name:i.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join("","")}),i.type==="ExportAllDeclaration"&&t.push({module:i.source.value,name:"*"}),i.type==="ExportNamedDeclaration"&&i.source&&t.push({module:i.source.value,name:i.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return t}function ve(e,t,i,n,s,p,d,h,g){let l=g??(a=>te(a,i)),f=[];for(let a of e){if(a.type==="ExportDeclaration"){let c=a.declaration,r=c.type,o="";r==="VariableDeclaration"?o=c.declarations.map(M=>M.id.value).join("",""):o=c.id?.value||c.identifier?.value||"anonymous";let u=l(a.span.start-t),y=l(a.span.end-t),m=F(u,p,n),b=h(a.span),C=[];if(a.type==="ExportDeclaration"&&(r==="ClassDeclaration"||r==="ClassExpression")){let M=c.body||[];for(let _ of M)if(_.type==="ClassMethod"||_.type==="ClassProperty"){let L=_.key.value;if(!L)continue;let k=l(_.span.start-t),q=l(_.span.end-t),P=h(_.span),T=F(k,p,n);C.push({name:L,kind:_.type,signature:N(P,_.type),line:I(k,s),endLine:I(q,s),doc:T,classification:_.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(r==="FunctionDeclaration"&&c.body?.type==="BlockStatement")C=pe(c.body.stmts,t,i,n,s,p,h,l);else if(r==="VariableDeclaration"){for(let M of c.declarations)if(M.init&&(M.init.type==="ArrowFunctionExpression"||M.init.type==="FunctionExpression")&&M.init.body?.type==="BlockStatement"){C=pe(M.init.body.stmts,t,i,n,s,p,h,l);break}}f.push({name:o,kind:r,signature:N(b,r),line:I(u,s),endLine:I(y,s),doc:m,classification:ne(d,o,r),capabilities:JSON.stringify(K(b)),members:C})}if(a.type==="ExportNamedDeclaration"){for(let c of a.specifiers)if(c.type==="ExportSpecifier"){let r=l(a.span.start-t),o=l(a.span.end-t),u=F(r,p,n);f.push({name:c.exported?.value||c.orig.value,kind:"ExportSpecifier",signature:`export { ${c.orig.value} }`,line:I(r,s),endLine:I(o,s),doc:u,classification:"Export mapping",capabilities:"[]"})}}if(a.type==="ExportDefaultDeclaration"){let c=l(a.span.start-t),r=l(a.span.end-t),o=F(c,p,n),u=h(a.span),y=[];if(a.decl.type==="ClassExpression"||a.decl.type==="ClassDeclaration"){let m=a.decl.body||[];for(let b of m)if(b.type==="ClassMethod"||b.type==="ClassProperty"){let C=b.key.value;if(!C)continue;let M=l(b.span.start-t),_=l(b.span.end-t),L=h(b.span),k=F(M,p,n);y.push({name:C,kind:b.type,signature:N(L,b.type),line:I(M,s),endLine:I(_,s),doc:k,classification:b.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(a.decl.type==="FunctionExpression"||a.decl.type==="FunctionDeclaration"||a.decl.type==="ArrowFunctionExpression")&&a.decl.body?.type==="BlockStatement"&&(y=pe(a.decl.body.stmts,t,i,n,s,p,h,l));f.push({name:"default",kind:"DefaultExport",signature:N(u,"DefaultExport"),line:I(c,s),endLine:I(r,s),doc:o,classification:"Default Export",capabilities:JSON.stringify(K(u)),members:y})}if(a.type==="ExportAllDeclaration"){let c=l(a.span.start-t),r=l(a.span.end-t),o=a.source.value,u=F(c,p,n);f.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${o}"`,line:I(c,s),endLine:I(r,s),doc:u,classification:"Re-export",capabilities:"[]"})}}return f}function pe(e,t,i,n,s,p,d,h){let g=[];for(let l of e){if(l.type==="VariableDeclaration")for(let f of l.declarations){let a=[],c=r=>{if(r.type==="Identifier")a.push({name:r.value,span:r.span});else if(r.type==="ArrayPattern")for(let o of r.elements)o&&c(o);else if(r.type==="ObjectPattern")for(let o of r.properties)o.type==="AssignmentPatternProperty"?a.push({name:o.key.value,span:o.span}):o.type==="KeyValuePatternProperty"&&c(o.value)};c(f.id);for(let r of a){let o=h(r.span.start-t),u=h(r.span.end-t),y=d(r.span),m=F(o,p,n);g.push({name:r.name,kind:"VariableDeclaration",signature:N(y,"VariableDeclaration"),line:I(o,s),endLine:I(u,s),doc:m,classification:"Internal Variable",capabilities:"[]"})}}if(l.type==="FunctionDeclaration"){let f=l.identifier?.value||l.ident?.value||"anonymous",a=h(l.span.start-t),c=h(l.span.end-t),r=d(l.span),o=F(a,p,n);g.push({name:f,kind:"FunctionDeclaration",signature:N(r,"FunctionDeclaration"),line:I(a,s),endLine:I(c,s),doc:o,classification:"Internal Function",capabilities:"[]"})}if(l.type==="ReturnStatement"&&l.argument?.type==="ObjectExpression")for(let f of l.argument.properties){let a="",c=f.span||f.key?.span||f.ident?.span;if(f.type==="KeyValueProperty"){let r=f.key;a=r?.value||r?.raw||(r?.type==="Identifier"?r.value:"")}else f.type==="MethodProperty"?a=f.key?.value||f.key?.raw||"":f.type==="ShorthandProperty"?a=f.ident?.value||"":f.type==="Identifier"&&(a=f.value||"");if(a&&c){let r=h(c.start-t),o=h(c.end-t),u=d(c),y=F(r,p,n);g.push({name:a,kind:"ReturnProperty",signature:N(u,"ReturnProperty"),line:I(r,s),endLine:I(o,s),doc:y,classification:"Return Member",capabilities:"[]"})}}if(l.type==="ExpressionStatement"&&l.expression.type==="CallExpression"){let f=l.expression;if(f.callee.type==="MemberExpression"&&(f.callee.property?.value==="on"||f.callee.property?.value==="once")){let a=f.arguments[0]?.expression?.value,c=f.arguments[1]?.expression;if(a&&c&&(c.type==="ArrowFunctionExpression"||c.type==="FunctionExpression")){let r=h(c.span.start-t),o=h(c.span.end-t),u=d(c.span);g.push({name:`on:${a}`,kind:c.type,signature:N(u,c.type),line:I(r,s),endLine:I(o,s),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(f.callee.type==="Identifier"&&f.callee.value==="addRoute"&&f.arguments.length>=3){let a=f.arguments[2].expression;if(a.type==="StringLiteral"){let c=a.value,r=h(f.span.start-t),o=h(f.span.end-t),u=d(f.span);g.push({name:c,kind:"HTTP Route",signature:N(u,"HTTP Route"),line:I(r,s),endLine:I(o,s),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:c})})}}}}return g}function Se(e,t,i,n,s,p){let d=p??(l=>te(l,i)),h=[];function g(l){if(!(!l||typeof l!="object")){if(l.type==="CallExpression"){let f=we(l);if(f){let a=d(l.span.start-t);h.push({...f,line:I(a,n),snippet:s(l.span)})}}for(let f of Object.keys(l)){if(f==="span")continue;let a=l[f];Array.isArray(a)?a.forEach(g):typeof a=="object"&&g(a)}}}return e.forEach(g),h}function we(e){let{callee:t,arguments:i}=e;if(!i||i.length===0)return null;if(t.type==="Identifier"&&t.value,t.type==="Identifier"&&t.value==="addRoute"&&i.length>=3){let n=i[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(t.type==="MemberExpression"&&t.property?.type==="Identifier"){let n=t.property.value;if(n==="emit"&&i[0].expression.type==="StringLiteral")return{type:"socket_event",name:i[0].expression.value,direction:"produce"};if(n==="on"&&i[0].expression.type==="StringLiteral")return{type:"socket_event",name:i[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&i[0].expression.type==="StringLiteral"){let p=i[0].expression.value,d=t.object.type==="Identifier"?t.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(d))return{type:"api_route",name:p,direction:"produce"};if(p.startsWith("/"))return{type:"api_route",name:p,direction:"consume"}}}return t.type==="Identifier"&&t.value==="fetch"&&i[0].expression.type==="StringLiteral"?{type:"api_route",name:i[0].expression.value,direction:"produce"}:null}function X(e){let{classification:t,capabilities:i,exports:n,fileName:s}=e,p={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},d=i.map(o=>p[o]).filter(Boolean).join(" and "),g={Component:(o,u)=>{let y=u.find(b=>b.kind==="FunctionDeclaration"||b.kind==="ClassDeclaration")?.name,m=y?`React component: ${y}`:"React UI component";return o?`${m} with ${o}`:m},Hook:(o,u)=>{let y=u.find(b=>b.name.startsWith("use"))?.name,m=y?`Custom React hook: ${y}`:"Custom React hook";return o?`${m} for ${o}`:m},Service:(o,u)=>{let m=`Service layer: ${u[0]?.name||"Service"}`;return o?`${m} handling ${o}`:m},Repository:(o,u)=>`Data repository: ${u[0]?.name||"Repository"} for ${o||"data access"}`,"Type Definition":(o,u)=>`Type definitions: ${u.slice(0,3).map(m=>m.name).join("")}${u.length>3?"...":""}`,Model:(o,u)=>`Data model: ${u[0]?.name||"Model"}`,"HTTP Route":(o,u)=>{let y=u.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)":(o,u)=>{let y=u.some(b=>b.classification==="Service Boundary"),m=u.find(b=>b.kind==="ClassDeclaration")?.name;return y?"PHP controller with API routes":m?`PHP class: ${m}`:"PHP module"},"Micro IR (Python)":(o,u)=>{let y=u.some(b=>b.classification==="Service Boundary"),m=u.find(b=>b.kind==="ClassDeclaration")?.name;return y?"Python API handler with routes":m?`Python class: ${m}`:"Python module"},"Micro IR (Go/TS) ":(o,u)=>{let y=u.some(b=>b.kind==="TypeDeclaration"),m=u.filter(b=>b.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) ":(o,u)=>{let y=u.find(C=>C.kind==="TraitDeclaration")?.name,m=u.find(C=>C.kind==="StructDeclaration")?.name,b=u.filter(C=>C.kind==="FunctionDeclaration");return y?o.includes("Rust trait")?`Rust module: trait ${y}`:`Rust module: ${y}`:m?`Rust module: struct ${m}`:b.length>0?`Rust module: ${b.length} function(s)`:"Rust module"}}[t];if(g)return g(d,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let l=n.filter(o=>o.kind==="FunctionDeclaration"),f=n.filter(o=>o.kind==="ClassDeclaration"),a=n.filter(o=>o.kind==="TsInterfaceDeclaration"||o.kind==="TsTypeAliasDeclaration"),c=[];if(f.length>0&&c.push(`Class: ${f[0].name}`),l.length>0){let o=l.slice(0,2).map(u=>u.name).join("");c.push(`Functions: ${o}`)}a.length>0&&c.push(`Types: ${a.length}`);let r=c.length>0?c.join(" | "):`Module with ${n.length} export(s)`;return d?`${r} \u2014 ${d}`:r}function Te(e){let t=new Set;function i(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&E(n.typeAnnotation,t),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&E(n,t);for(let s in n){if(s==="span"||s==="comments"||s==="interpreter")continue;let p=n[s];p&&typeof p=="object"&&(Array.isArray(p)?p.forEach(i):i(p))}}}return e.forEach(n=>i(n)),Array.from(t)}function E(e,t){if(e){if(e.type==="TsTypeAnnotation"){E(e.typeAnnotation,t);return}e.type==="TsTypeReference"&&(e.typeName?.type==="Identifier"&&t.add(e.typeName.value),e.typeName?.type==="TsQualifiedName"&&Ce(e.typeName,t),e.typeParams&&E(e.typeParams,t)),e.type==="TsArrayType"&&E(e.elementType,t),e.type==="TsUnionType"&&e.types?.forEach(i=>E(i,t)),e.type==="TsIntersectionType"&&e.types?.forEach(i=>E(i,t)),e.type==="TsTupleType"&&e.elemTypes?.forEach(i=>E(i.ty,t)),(e.type==="TsFunctionType"||e.type==="TsConstructorType")&&(e.params?.forEach(i=>E(i.typeAnnotation,t)),e.typeAnnotation&&E(e.typeAnnotation,t)),e.type==="TsTypeParameterDeclaration"&&e.params?.forEach(i=>{i.constraint&&E(i.constraint,t),i.default&&E(i.default,t)}),e.type==="TsTypeParameterInstantiation"&&e.params?.forEach(i=>E(i,t)),e.type==="TsMappedType"&&e.typeAnnotation&&E(e.typeAnnotation,t),e.type==="TsIndexedAccessType"&&(E(e.objectType,t),E(e.indexType,t)),e.type==="TsConditionalType"&&(E(e.checkType,t),E(e.extendsType,t),E(e.trueType,t),E(e.falseType,t)),e.type==="TsTypeLiteral"&&e.members?.forEach(i=>{i.typeAnnotation&&E(i.typeAnnotation,t)})}}function Ce(e,t){e.type==="TsQualifiedName"?(e.left&&Ce(e.left,t),e.right?.value&&t.add(e.right.value)):e.type==="Identifier"&&t.add(e.value)}import Ae from"path";import me from"path";import Ee from"path";import Je from"fs";import{fileURLToPath as je}from"url";import*as U from"web-tree-sitter";import Le from"pino";var $e={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},Fe=Le({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(e,t){return{level:e,severity:$e[t]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),H=Fe;import{fileURLToPath as Ne}from"node:url";import{dirname as ue,join as Me,resolve as We}from"node:path";import{existsSync as ze}from"node:fs";var Be=Ne(import.meta.url),Re=ue(Be);function Ze(){let e=Re;for(;e!==ue(e);){if(ze(Me(e,"package.json")))return e;e=ue(e)}return We(Re,"..","..")}function Ie(...e){return Me(Ze(),...e)}var ht=Ee.dirname(je(import.meta.url)),ke=H.child({module:"parser:tree-sitter"}),ie=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let t=U.Parser||U;await t.init(),this.parser=new t}async getLanguage(t){if(this.languages.has(t))return this.languages.get(t);let i=Ie("resources","grammars",`tree-sitter-${this.getLangName(t)}.wasm`);if(!Je.existsSync(i))return ke.warn({grammarPath:i},"Grammar WASM not found"),null;try{let n=await U.Language.load(i);return this.languages.set(t,n),n}catch(n){return ke.error({err:n,ext:t},"Failed to load language grammar"),null}}getLangName(t){switch(t.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(t){switch(t.toLowerCase()){case".php":return`
1
+ import Ae from"fs";function he(e){let t=e.split(`
2
+ `),i=[],n=0;for(let s of t)i.push(n),n+=s.length+1;return i}function P(e,t){for(let i=0;i<t.length;i++)if(t[i+1]>e||i===t.length-1)return i+1;return 1}function te(e,t){return t.slice(0,e).toString("utf8").length}function ge(e){if(e.toString("utf8").length===e.length)return n=>n;let i=new Map;return n=>{let s=i.get(n);return s===void 0&&(s=e.slice(0,n).toString("utf8").length,i.set(n,s)),s}}function be(e,t,i){let n=e.start-t,s=e.end-t;return n<0||s>i.length?"":i.slice(n,s).toString("utf8")}function xe(e){let t=[],i=/\/\*\*[\s\S]*?\*\//g,n;for(;(n=i.exec(e))!==null;)t.push({start:n.index,end:n.index+n[0].length,text:n[0]});return t}function F(e,t,i){for(let n of t){if(n.start===e)return n.text;if(n.start>e&&n.start<e+50){let s=i.substring(e,n.start);if(/^\s*$/.test(s))return n.text}if(n.end<=e&&n.end>e-50){let s=i.substring(n.end,e);if(/^\s*$/.test(s))return n.text}}return""}function De(e){if(!e)return"";let i=e.replace(/\/\*\*|\*\/|\*/g,"").trim().split(`
3
+ `)[0].trim();return i.length>200?i.substring(0,197)+"...":i}function ne(e,t,i){let n=e.toLowerCase(),s=t.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":i==="TsInterfaceDeclaration"||i==="TsTypeAliasDeclaration"?"Type Definition":"Other"}function Q(e){let t=[];return/\b(fetch|axios|superagent|got)\s*\(|import\s+.*\b(http|https|node-fetch)\b/i.test(e)&&t.push("Network"),(/\b(knex|prisma|typeorm|mongoose|sequelize|pg|mysql|sqlite3)\b/i.test(e)||/\b(SELECT\s+.*FROM|INSERT\s+INTO|UPDATE\s+.*SET|DELETE\s+FROM)\b/i.test(e)||/\.query\s*\(|\.execute\s*\(/i.test(e)&&/db|database|client|pool/i.test(e))&&t.push("Database"),(/\bfs\./i.test(e)||/\b(readFileSync|writeFileSync|readFile|writeFile|readdir)\b/.test(e)||/import\s+.*\bfs\b/.test(e))&&t.push("File System"),(/\b(localStorage|sessionStorage|indexedDB)\./.test(e)||/\bdocument\.cookie\b/.test(e))&&t.push("Browser Storage"),t}function N(e,t){if(!e)return"";let i=e.trimStart();for(;/^\/\*[\s\S]*?\*\//.test(i);)i=i.replace(/^\/\*[\s\S]*?\*\/\s*/,"");for(;/^\/\/[^\n]*\n/.test(i);)i=i.replace(/^\/\/[^\n]*\n\s*/,"");if(i=i.replace(/^(?:import[^\n]*\n)+/,"").replace(/^(?:export\s+\{[^}]*\}\s+from\s+['"][^'"]+['"];?\s*\n?)+/,"").trim(),t==="TsInterfaceDeclaration"||t==="TsTypeAliasDeclaration")return i;let n=0,s=0,u=i.length;for(let h=0;h<i.length;h++){let S=i[h];if(S==="(")n++;else if(S===")")n--;else if(S==="<")s++;else if(S===">")s--;else if(S==="{"){if(n===0&&s===0){u=h;break}}else if(S===";"&&n===0&&s===0){u=h;break}else if(S==="="&&i[h+1]===">"&&n===0&&s===0){u=h+2;break}}let d=i.substring(0,u).trim();return d.length>500?d.slice(0,497)+"...":d}function Se(e){let t=[];for(let i of e)i.type==="ImportDeclaration"&&t.push({module:i.source.value,name:i.specifiers.map(n=>n.type==="ImportDefaultSpecifier"?"default":n.type==="ImportNamespaceSpecifier"?"*":n.local?.value||n.imported?.value||"*").join(", ")}),i.type==="ExportAllDeclaration"&&t.push({module:i.source.value,name:"*"}),i.type==="ExportNamedDeclaration"&&i.source&&t.push({module:i.source.value,name:i.specifiers.map(n=>n.type==="ExportSpecifier"?n.orig.value:"*").join(", ")});return t}function $e(e,t){for(let i of e){if((i.type==="FunctionDeclaration"||i.type==="ClassDeclaration")&&(i.identifier?.value||i.id?.value)===t)return i.span;if(i.type==="VariableDeclaration"){for(let n of i.declarations)if(n.id?.type==="Identifier"&&n.id.value===t)return n.span||i.span}if((i.type==="TsTypeAliasDeclaration"||i.type==="TsInterfaceDeclaration"||i.type==="TsEnumDeclaration")&&(i.id?.value||i.identifier?.value)===t)return i.span;if(i.type==="ExportDeclaration"){let n=i.declaration;if(!n)continue;if((n.type==="FunctionDeclaration"||n.type==="ClassDeclaration")&&(n.identifier?.value||n.id?.value)===t)return n.span||i.span;if(n.type==="VariableDeclaration"){for(let s of n.declarations)if(s.id?.type==="Identifier"&&s.id.value===t)return s.span||n.span||i.span}}}return null}function ve(e,t,i,n,s,u,d,h,S){let o=S??(a=>te(a,i)),l=[];for(let a of e){if(a.type==="ExportDeclaration"){let p=a.declaration,f=p.type,r="";f==="VariableDeclaration"?r=p.declarations.map(M=>M.id.value).join("",""):r=p.id?.value||p.identifier?.value||"anonymous";let c=o(a.span.start-t),y=o(a.span.end-t),m=F(c,u,n),g=h(a.span),T=[];if(a.type==="ExportDeclaration"&&(f==="ClassDeclaration"||f==="ClassExpression")){let M=p.body||[];for(let w of M)if(w.type==="ClassMethod"||w.type==="ClassProperty"){let A=w.key.value;if(!A)continue;let E=o(w.span.start-t),U=o(w.span.end-t),I=h(w.span),R=F(E,u,n);T.push({name:A,kind:w.type,signature:N(I,w.type),line:P(E,s),endLine:P(U,s),doc:R,classification:w.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else if(f==="FunctionDeclaration"&&p.body?.type==="BlockStatement")T=ue(p.body.stmts,t,i,n,s,u,h,o);else if(f==="VariableDeclaration"){for(let M of p.declarations)if(M.init&&(M.init.type==="ArrowFunctionExpression"||M.init.type==="FunctionExpression")&&M.init.body?.type==="BlockStatement"){T=ue(M.init.body.stmts,t,i,n,s,u,h,o);break}}l.push({name:r,kind:f,signature:N(g,f),line:P(c,s),endLine:P(y,s),doc:m,classification:ne(d,r,f),capabilities:JSON.stringify(Q(g)),members:T})}if(a.type==="ExportNamedDeclaration"){for(let p of a.specifiers)if(p.type==="ExportSpecifier"){let f=p.orig.value,r=p.exported?.value||f,y=$e(e,f)||a.span,m=o(y.start-t),g=o(y.end-t),T=F(m,u,n);l.push({name:r,kind:"ExportSpecifier",signature:`export { ${f} }`,line:P(m,s),endLine:P(g,s),doc:T,classification:"Export mapping",capabilities:"[]"})}}if(a.type==="ExportDefaultDeclaration"){let p=o(a.span.start-t),f=o(a.span.end-t),r=F(p,u,n),c=h(a.span),y=[];if(a.decl.type==="ClassExpression"||a.decl.type==="ClassDeclaration"){let m=a.decl.body||[];for(let g of m)if(g.type==="ClassMethod"||g.type==="ClassProperty"){let T=g.key.value;if(!T)continue;let M=o(g.span.start-t),w=o(g.span.end-t),A=h(g.span),E=F(M,u,n);y.push({name:T,kind:g.type,signature:N(A,g.type),line:P(M,s),endLine:P(w,s),doc:E,classification:g.type==="ClassMethod"?"Method":"Property",capabilities:"[]"})}}else(a.decl.type==="FunctionExpression"||a.decl.type==="FunctionDeclaration"||a.decl.type==="ArrowFunctionExpression")&&a.decl.body?.type==="BlockStatement"&&(y=ue(a.decl.body.stmts,t,i,n,s,u,h,o));l.push({name:"default",kind:"DefaultExport",signature:N(c,"DefaultExport"),line:P(p,s),endLine:P(f,s),doc:r,classification:"Default Export",capabilities:JSON.stringify(Q(c)),members:y})}if(a.type==="ExportAllDeclaration"){let p=o(a.span.start-t),f=o(a.span.end-t),r=a.source.value,c=F(p,u,n);l.push({name:"*",kind:"ExportAllDeclaration",signature:`export * from "${r}"`,line:P(p,s),endLine:P(f,s),doc:c,classification:"Re-export",capabilities:"[]"})}}return l}function ue(e,t,i,n,s,u,d,h){let S=[];for(let o of e){if(o.type==="VariableDeclaration")for(let l of o.declarations){let a=[],p=r=>{if(r.type==="Identifier")a.push({name:r.value,span:r.span});else if(r.type==="ArrayPattern")for(let c of r.elements)c&&p(c);else if(r.type==="ObjectPattern")for(let c of r.properties)c.type==="AssignmentPatternProperty"?a.push({name:c.key.value,span:c.span}):c.type==="KeyValuePatternProperty"&&p(c.value)};p(l.id);let f=l.init&&(l.init.type==="ArrowFunctionExpression"||l.init.type==="FunctionExpression");for(let r of a){let c=f?l.init.span||l.span||r.span:l.span||r.span,y=f?l.init.type:"VariableDeclaration",m=f?"Internal Function":"Internal Variable",g=h(c.start-t),T=h(c.end-t),M=d(c),w=F(g,u,n);S.push({name:r.name,kind:y,signature:N(M,y),line:P(g,s),endLine:P(T,s),doc:w,classification:m,capabilities:"[]"})}}if(o.type==="FunctionDeclaration"){let l=o.identifier?.value||o.ident?.value||"anonymous",a=h(o.span.start-t),p=h(o.span.end-t),f=d(o.span),r=F(a,u,n);S.push({name:l,kind:"FunctionDeclaration",signature:N(f,"FunctionDeclaration"),line:P(a,s),endLine:P(p,s),doc:r,classification:"Internal Function",capabilities:"[]"})}if(o.type==="ReturnStatement"&&o.argument?.type==="ObjectExpression")for(let l of o.argument.properties){let a="",p=l.span||l.key?.span||l.ident?.span;if(l.type==="KeyValueProperty"){let f=l.key;a=f?.value||f?.raw||(f?.type==="Identifier"?f.value:"")}else l.type==="MethodProperty"?a=l.key?.value||l.key?.raw||"":l.type==="ShorthandProperty"?a=l.ident?.value||"":l.type==="Identifier"&&(a=l.value||"");if(a&&p){let f=h(p.start-t),r=h(p.end-t),c=d(p),y=F(f,u,n);S.push({name:a,kind:"ReturnProperty",signature:N(c,"ReturnProperty"),line:P(f,s),endLine:P(r,s),doc:y,classification:"Return Member",capabilities:"[]"})}}if(o.type==="ExpressionStatement"&&o.expression.type==="CallExpression"){let l=o.expression;if(l.callee.type==="MemberExpression"&&(l.callee.property?.value==="on"||l.callee.property?.value==="once")){let a=l.arguments[0]?.expression?.value,p=l.arguments[1]?.expression;if(a&&p&&(p.type==="ArrowFunctionExpression"||p.type==="FunctionExpression")){let f=h(p.span.start-t),r=h(p.span.end-t),c=d(p.span);S.push({name:`on:${a}`,kind:p.type,signature:N(c,p.type),line:P(f,s),endLine:P(r,s),doc:"",classification:"Event Handler",capabilities:"[]"})}}if(l.callee.type==="Identifier"&&l.callee.value==="addRoute"&&l.arguments.length>=3){let a=l.arguments[2].expression;if(a.type==="StringLiteral"){let p=a.value,f=h(l.span.start-t),r=h(l.span.end-t),c=d(l.span);S.push({name:p,kind:"HTTP Route",signature:N(c,"HTTP Route"),line:P(f,s),endLine:P(r,s),doc:"",classification:"Service Boundary",capabilities:JSON.stringify({path:p})})}}}}return S}function Te(e,t,i,n,s,u){let d=u??(o=>te(o,i)),h=[];function S(o){if(!(!o||typeof o!="object")){if(o.type==="CallExpression"){let l=Fe(o);if(l){let a=d(o.span.start-t);h.push({...l,line:P(a,n),snippet:s(o.span)})}}for(let l of Object.keys(o)){if(l==="span")continue;let a=o[l];Array.isArray(a)?a.forEach(S):typeof a=="object"&&S(a)}}}return e.forEach(S),h}function Fe(e){let{callee:t,arguments:i}=e;if(!i||i.length===0)return null;if(t.type==="Identifier"&&t.value,t.type==="Identifier"&&t.value==="addRoute"&&i.length>=3){let n=i[2].expression;if(n.type==="StringLiteral")return{type:"api_route",name:n.value,direction:"consume"}}if(t.type==="MemberExpression"&&t.property?.type==="Identifier"){let n=t.property.value;if(n==="emit"&&i[0].expression.type==="StringLiteral")return{type:"socket_event",name:i[0].expression.value,direction:"produce"};if(n==="on"&&i[0].expression.type==="StringLiteral")return{type:"socket_event",name:i[0].expression.value,direction:"consume"};if(["get","post","put","delete","patch"].includes(n)&&i[0].expression.type==="StringLiteral"){let u=i[0].expression.value,d=t.object.type==="Identifier"?t.object.value:"";if(["axios","http","request","appApi","restApi","adminApi","client"].includes(d))return{type:"api_route",name:u,direction:"produce"};if(u.startsWith("/"))return{type:"api_route",name:u,direction:"consume"}}}return t.type==="Identifier"&&t.value==="fetch"&&i[0].expression.type==="StringLiteral"?{type:"api_route",name:i[0].expression.value,direction:"produce"}:null}function X(e){let{classification:t,capabilities:i,exports:n,fileName:s}=e,u={Network:"API integration",Database:"data persistence","File System":"file I/O operations","Browser Storage":"client-side storage"},d=i.map(r=>u[r]).filter(Boolean).join(" and "),S={Component:(r,c)=>{let y=c.find(g=>g.kind==="FunctionDeclaration"||g.kind==="ClassDeclaration")?.name,m=y?`React component: ${y}`:"React UI component";return r?`${m} with ${r}`:m},Hook:(r,c)=>{let y=c.find(g=>g.name.startsWith("use"))?.name,m=y?`Custom React hook: ${y}`:"Custom React hook";return r?`${m} for ${r}`:m},Service:(r,c)=>{let m=`Service layer: ${c[0]?.name||"Service"}`;return r?`${m} handling ${r}`:m},Repository:(r,c)=>`Data repository: ${c[0]?.name||"Repository"} for ${r||"data access"}`,"Type Definition":(r,c)=>`Type definitions: ${c.slice(0,3).map(m=>m.name).join("")}${c.length>3?"...":""}`,Model:(r,c)=>`Data model: ${c[0]?.name||"Model"}`,"HTTP Route":(r,c)=>{let y=c.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)":(r,c)=>{let y=c.some(g=>g.classification==="Service Boundary"),m=c.find(g=>g.kind==="ClassDeclaration")?.name;return y?"PHP controller with API routes":m?`PHP class: ${m}`:"PHP module"},"Micro IR (Python)":(r,c)=>{let y=c.some(g=>g.classification==="Service Boundary"),m=c.find(g=>g.kind==="ClassDeclaration")?.name;return y?"Python API handler with routes":m?`Python class: ${m}`:"Python module"},"Micro IR (Go/TS) ":(r,c)=>{let y=c.some(g=>g.kind==="TypeDeclaration"),m=c.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) ":(r,c)=>{let y=c.find(T=>T.kind==="TraitDeclaration")?.name,m=c.find(T=>T.kind==="StructDeclaration")?.name,g=c.filter(T=>T.kind==="FunctionDeclaration");return y?r.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"}}[t];if(S)return S(d,n);if(n.length===0)return s?`Module: ${s}`:"Module with no exports";let o=n.filter(r=>r.kind==="FunctionDeclaration"),l=n.filter(r=>r.kind==="ClassDeclaration"),a=n.filter(r=>r.kind==="TsInterfaceDeclaration"||r.kind==="TsTypeAliasDeclaration"),p=[];if(l.length>0&&p.push(`Class: ${l[0].name}`),o.length>0){let r=o.slice(0,2).map(c=>c.name).join("");p.push(`Functions: ${r}`)}a.length>0&&p.push(`Types: ${a.length}`);let f=p.length>0?p.join(" | "):`Module with ${n.length} export(s)`;return d?`${f} \u2014 ${d}`:f}function Re(e){let t=new Set;function i(n){if(!(!n||typeof n!="object")){n.typeAnnotation&&k(n.typeAnnotation,t),(n.type==="TsTypeReference"||n.type==="TsTypeAnnotation")&&k(n,t);for(let s in n){if(s==="span"||s==="comments"||s==="interpreter")continue;let u=n[s];u&&typeof u=="object"&&(Array.isArray(u)?u.forEach(i):i(u))}}}return e.forEach(n=>i(n)),Array.from(t)}function k(e,t){if(e){if(e.type==="TsTypeAnnotation"){k(e.typeAnnotation,t);return}e.type==="TsTypeReference"&&(e.typeName?.type==="Identifier"&&t.add(e.typeName.value),e.typeName?.type==="TsQualifiedName"&&Ce(e.typeName,t),e.typeParams&&k(e.typeParams,t)),e.type==="TsArrayType"&&k(e.elementType,t),e.type==="TsUnionType"&&e.types?.forEach(i=>k(i,t)),e.type==="TsIntersectionType"&&e.types?.forEach(i=>k(i,t)),e.type==="TsTupleType"&&e.elemTypes?.forEach(i=>k(i.ty,t)),(e.type==="TsFunctionType"||e.type==="TsConstructorType")&&(e.params?.forEach(i=>k(i.typeAnnotation,t)),e.typeAnnotation&&k(e.typeAnnotation,t)),e.type==="TsTypeParameterDeclaration"&&e.params?.forEach(i=>{i.constraint&&k(i.constraint,t),i.default&&k(i.default,t)}),e.type==="TsTypeParameterInstantiation"&&e.params?.forEach(i=>k(i,t)),e.type==="TsMappedType"&&e.typeAnnotation&&k(e.typeAnnotation,t),e.type==="TsIndexedAccessType"&&(k(e.objectType,t),k(e.indexType,t)),e.type==="TsConditionalType"&&(k(e.checkType,t),k(e.extendsType,t),k(e.trueType,t),k(e.falseType,t)),e.type==="TsTypeLiteral"&&e.members?.forEach(i=>{i.typeAnnotation&&k(i.typeAnnotation,t)})}}function Ce(e,t){e.type==="TsQualifiedName"?(e.left&&Ce(e.left,t),e.right?.value&&t.add(e.right.value)):e.type==="Identifier"&&t.add(e.value)}import Le from"path";import fe from"path";import ke from"path";import He from"fs";import{fileURLToPath as Ue}from"url";import*as H from"web-tree-sitter";import Ne from"pino";var We={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"},ze=Ne({level:process.env.LOG_LEVEL||"warn",base:{service:"liquid-shadow"},formatters:{level(e,t){return{level:e,severity:We[t]??"INFO"}}},transport:{target:"pino-pretty",options:{colorize:!0,translateTime:"HH:MM:ss",destination:2,levelKey:"severity",messageKey:"message"}}}),O=ze;import{fileURLToPath as Be}from"node:url";import{dirname as me,join as Pe,resolve as Ze}from"node:path";import{existsSync as je}from"node:fs";var Je=Be(import.meta.url),we=me(Je);function Oe(){let e=we;for(;e!==me(e);){if(je(Pe(e,"package.json")))return e;e=me(e)}return Ze(we,"..","..")}function Me(...e){return Pe(Oe(),...e)}var St=ke.dirname(Ue(import.meta.url)),Ee=O.child({module:"parser:tree-sitter"}),ie=class{parser=null;languages=new Map;async ensureInitialized(){if(this.parser)return;let t=H.Parser||H;await t.init(),this.parser=new t}async getLanguage(t){if(this.languages.has(t))return this.languages.get(t);let i=Me("resources","grammars",`tree-sitter-${this.getLangName(t)}.wasm`);if(!He.existsSync(i))return Ee.warn({grammarPath:i},"Grammar WASM not found"),null;try{let n=await H.Language.load(i);return this.languages.set(t,n),n}catch(n){return Ee.error({err:n,ext:t},"Failed to load language grammar"),null}}getLangName(t){switch(t.toLowerCase()){case".php":return"php";case".py":return"python";case".go":return"go";case".rs":return"rust";default:return""}}getQueries(t){switch(t.toLowerCase()){case".php":return`
4
4
  (function_definition name: (name) @name) @func
5
5
  (class_declaration name: (name) @name) @class
6
6
  (interface_declaration name: (name) @name) @interface
@@ -24,13 +24,14 @@ import fe from"@swc/core";import Pe from"fs";function he(e){let t=e.split(`
24
24
  (trait_item name: (_type_identifier) @name) @trait
25
25
  (type_item name: (_type_identifier) @name) @type
26
26
  (use_declaration argument: (_) @name) @import
27
- `;default:return""}}mapKind(t,i){if(t==="import")return"ImportDeclaration";if(i===".php"){if(t==="func")return"FunctionDeclaration";if(t==="class")return"ClassDeclaration";if(t==="interface")return"InterfaceDeclaration";if(t==="trait")return"TraitDeclaration";if(t==="method")return"MethodDeclaration"}if(i===".py"){if(t==="func")return"FunctionDeclaration";if(t==="class")return"ClassDeclaration"}if(i===".go"){if(t==="func")return"FunctionDeclaration";if(t==="type")return"TypeDeclaration"}if(i===".rs"){if(t==="func")return"FunctionDeclaration";if(t==="struct")return"StructDeclaration";if(t==="enum")return"EnumDeclaration";if(t==="trait")return"TraitDeclaration";if(t==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(t){return t==="import"?"Dependency":t==="func"||t==="method"?"Function":t==="class"||t==="interface"||t==="trait"||t==="struct"||t==="enum"||t==="type"?"Class":"Other"}async parse(t,i){await this.ensureInitialized();let n=Ee.extname(t).toLowerCase(),s=await this.getLanguage(n);if(!s||!this.parser)return[];this.parser.setLanguage(s);let p=this.parser.parse(i),d=i.split(`
28
- `),h=this.getQueries(n);if(!h)return[];let l=new U.Query(s,h).matches(p.rootNode),f=[];for(let a of l){let c=a.captures.find(u=>u.name==="name")?.node,r=a.captures[0].node,o=a.captures[0].name;if(c){let u=r.startPosition.row+1,y=r.endPosition.row+1,m=d[r.startPosition.row].trim();f.push({name:c.text,kind:this.mapKind(o,n),classification:this.mapClassification(o),signature:m,line:u,endLine:y,doc:"",capabilities:"{}"})}}return f}};var se=class{parse(t,i=!1){let n=[],s=[],p=t.split(`
29
- `),d="",h="",g=0,l=0,f=-1,a=-1,c=[],r=[],o=!1,u=i?"api":"",y="",m=/^namespace\s+([a-zA-Z0-9_\\]+);/,b=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,C=/^interface\s+([a-zA-Z0-9_]+)/,M=/^trait\s+([a-zA-Z0-9_]+)/,_=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,L=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,k=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,q=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,P=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let T=0;T<p.length;T++){let S=p[T].trim();if(!S)continue;let $=(S.match(/{/g)||[]).length,oe=(S.match(/}/g)||[]).length,ce=l;if(l+=$-oe,h&&l<=a){let v=n.find(x=>x.name===h&&x.line===g);v&&(v.endLine=T+1),h="",a=-1}if(d&&l<=f){let v=n.find(x=>x.name===d&&(x.kind==="ClassDeclaration"||x.kind==="TraitDeclaration"||x.kind==="InterfaceDeclaration"));v&&(v.endLine=T+1),d="",f=-1}let Y=S.match(P);if(Y&&(u=Y[1]),S.includes("});")&&(u=""),S.startsWith("/**")){o=!0,r=[];continue}if(o){S.endsWith("*/")?o=!1:r.push(S.replace(/^\*\s?/,""));continue}let G=S.match(k);if(G){c.push(G[1]);continue}let O=S.match(m);if(O){y=O[1]||"",c=[],r=[];continue}let R=S.match(b);if(R){d=R[1],f=l-$;let v={attributes:c};y&&(v.namespace=y),n.push({name:d,kind:"ClassDeclaration",classification:"Class",signature:`class ${d}`,line:T+1,endLine:T+1,doc:r.join(`
30
- `).trim(),capabilities:JSON.stringify(v),members:[]}),c=[],r=[];continue}let D=S.match(C);if(D){let v=D[1];d=v,f=l-$,n.push({name:v,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${v}`,line:T+1,endLine:T+1,doc:r.join(`
31
- `).trim(),capabilities:JSON.stringify({attributes:c}),members:[]}),c=[],r=[];continue}let w=S.match(M);if(w){let v=w[1];d=v,f=l-$,n.push({name:v,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${v}`,line:T+1,endLine:T+1,doc:r.join(`
32
- `).trim(),capabilities:JSON.stringify({attributes:c}),members:[]}),c=[],r=[];continue}let Q=S.match(_);if(Q){let v=Q[1],x=!!d;h=v,g=T+1,a=l-$;let j=!1,W={};for(let A of c)A.toLowerCase().includes("route")&&(j=!0,W={type:"route",method:"GET",path:"/"});let z=r.join(`
33
- `).trim();if(j){let A=W.path||"/";n.push({name:A,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${v}`,line:T+1,endLine:T+1,doc:z,capabilities:JSON.stringify({type:"route",handler:d?`${d}@${v}`:v,...W})}),s.push({type:"api_route",name:A,direction:"consume",line:T+1,snippet:S})}n.push({name:v,kind:x?"MethodDeclaration":"FunctionDeclaration",classification:x?"Method":"Function",signature:`${x?d+":: ":""}${v}`,line:T+1,endLine:T+1,doc:z,capabilities:JSON.stringify({attributes:c})}),c=[],r=[];continue}let Z=S.match(L);if(Z){let v=Z[1]||"",x=Z[2]||v.split("\\").pop()||"";n.push({name:x,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${v}`,line:T+1,endLine:T+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:v})}),c=[],r=[];continue}let V=S.match(q);if(V){let v=V[1].toUpperCase(),x=V[2];if(S.includes("Route::")||S.includes("router->")||S.includes("action")||S.includes(",")&&!S.includes("view(")){if(u){let B=u.startsWith("/")?u:`/${u}`,le=x.startsWith("/")?x:`/${x}`;x=(B+le).replace(/\/+/g,"/")}let W=null,z=S.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(z)W=`${z[1]}@${z[2]}`;else if(S.includes("::class")){let B=S.match(/([a-zA-Z0-9_]+)::class/);B&&(W=B[1])}let A=S;!S.endsWith(");")&&T+1<p.length&&(A+=" "+p[T+1].trim(),!A.endsWith(");")&&T+2<p.length&&(A+=" "+p[T+2].trim())),n.push({name:x,kind:"HTTP Route",classification:"Service Boundary",signature:A,line:T+1,endLine:T+1,doc:"",capabilities:JSON.stringify({type:"route",method:v,path:x,handler:W})}),s.push({type:"api_route",name:x,direction:"consume",line:T+1,snippet:A,method:v,url:x}),r=[];continue}}let ee=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,J=S.match(ee);if(J){let v=(J[1]||J[3]).toUpperCase(),x=(J[2]||J[4]).trim();(x.startsWith("'")&&x.endsWith("'")||x.startsWith('"')&&x.endsWith('"'))&&(x=x.substring(1,x.length-1)),s.push({type:"api_route",name:x,direction:"produce",line:T+1,snippet:S,method:v,url:x})}!S.startsWith("#[")&&!S.startsWith("//")&&!S.startsWith("*")&&!o&&(c=[],r=[])}return{nodes:n,events:s}}};var re=class{currentRoutePrefix="";parse(t){this.currentRoutePrefix="";let i=[],n=[],s=t.split(`
34
- `),p=[{indent:-1,name:"root",type:"root"}],d=[],h=/^class\s+([a-zA-Z0-9_]+)/,g=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,l=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,f=/^@(.*)/;function a(m){return m.trim().split(/[.(]/)[0]?.trim()||m}function c(m){let b=m.decorators.map(M=>a(M.raw)),C={decorators:m.decorators,decoratorNames:b};return m.async===!0&&(C.async=!0),JSON.stringify(C)}let r=!1,o="",u=[],y=[];for(let m=0;m<s.length;m++){let b=s[m],C=b.trim();if(!C||C.startsWith("#"))continue;let M=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,_=C.match(M);if(_&&(this.currentRoutePrefix=_[2]),r){if(C.endsWith(o)||C.includes(o)){r=!1;let R=C.replace(o,"").trim();R&&u.push(R);let D=p[p.length-1];D.node&&(D.node.doc=u.join(`
35
- `).trim()),u=[]}else u.push(C);continue}let L=b.search(/\S/),k=b.trim(),q=k.match(/^(['"]{3})/);if(q){let R=q[1],D=p[p.length-1];if(D.node&&!D.node.doc){if(k.substring(3).includes(R)){let w=k.replace(new RegExp(R,"g"),"").trim();D.node.doc=w}else{r=!0,o=R;let w=k.substring(3).trim();w&&u.push(w)}continue}}for(;p.length>1&&p[p.length-1].indent>=L;)p.pop();let P=p[p.length-1],T=k.match(f);if(T){d.push({raw:T[1].trim(),line:m+1});continue}let S=k.match(h);if(S){let R=S[1],D={name:R,kind:"ClassDeclaration",classification:"Class",signature:`class ${R}`,line:m+1,endLine:m+1,doc:"",capabilities:c({decorators:d}),members:[]};y.push(D),P.node?(P.node.members||(P.node.members=[]),P.node.members.push(D)):i.push(D),p.push({indent:L,name:R,type:"class",node:D}),d=[];continue}let $=k.match(g);if($){let R=!!$[1],D=$[1]||$[2],w=P.type==="class",Q=!1,Z={};for(let x of d)if(x.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){Q=!0;let W=["get","post","put","delete","patch"].find(B=>x.raw.toLowerCase().includes(`.${B}`))?.toUpperCase()||"GET",z=x.raw.match(/['"]([^'"]+)['"]/),A=z?z[1]:"/";if(this.currentRoutePrefix){let B=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,le=A.startsWith("/")?A:`/${A}`;A=B+le}Z={type:"route",method:W,path:A}}if(Q){let x=Z.path||"",j={name:x||D,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${D}`,line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({handler:w?`${P.name}.${D}`:D,async:R,...Z})};y.push(j),i.push(j),n.push({type:"api_route",name:x,direction:"consume",line:m+1,snippet:k})}let V=d.some(x=>x.raw==="staticmethod"),ee=d.some(x=>x.raw==="classmethod"),J=`${R?"async ":""}${w?(V?"@staticmethod ":ee?"@classmethod ":"")+P.name+".":""}${D}`,v={name:D,kind:R&&w?"AsyncMethodDeclaration":R?"AsyncFunctionDeclaration":w?"MethodDeclaration":"FunctionDeclaration",classification:w?V||ee?"Static Method":"Method":"Function",signature:J,line:m+1,endLine:m+1,doc:"",capabilities:c({decorators:d,async:R}),members:[]};y.push(v),P.node?(P.node.members||(P.node.members=[]),P.node.members.push(v)):i.push(v),p.push({indent:L,name:D,type:"function",node:v}),d=[];continue}let oe=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,ce=k.match(oe);if(ce){let R=ce[1].replace(/^\^/,""),D={name:R,kind:"HTTP Route",classification:"Service Boundary",signature:k.trim(),line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:R})};y.push(D),i.push(D),n.push({type:"api_route",name:R,direction:"consume",line:m+1,snippet:k});continue}let Y=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,G=k.match(Y);if(G){let R=G[1].toUpperCase(),D=G[2].trim();(D.startsWith("'")&&D.endsWith("'")||D.startsWith('"')&&D.endsWith('"'))&&(D=D.substring(1,D.length-1)),n.push({type:"api_route",name:D,direction:"produce",line:m+1,snippet:k,method:R,url:D})}let O=k.match(l);if(O){let R=O[1]||O[2],D={name:R,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${R}`,line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({type:"import",module:R})};y.push(D),i.push(D),d=[];continue}d=[],P.node&&(P.node.endLine=m+1)}return{nodes:y,events:n}}};var _e=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:e=>({name:e[1],kind:"FunctionDeclaration",classification:"Function",signature:e[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:e=>({name:e[1],kind:"MethodDeclaration",classification:"Method",signature:e[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:e=>({name:e[1],kind:"ImportSpecifier",classification:"Dependency",signature:e[0],meta:{type:"import",path:e[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:e=>({name:e[1],kind:"FunctionDeclaration",classification:"Function",signature:e[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"StructDeclaration",classification:"Class",signature:e[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"EnumDeclaration",classification:"Class",signature:e[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"TraitDeclaration",classification:"Class",signature:e[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:e=>({name:e[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:e[0],meta:{type:"import",path:e[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:e=>({name:e[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:e=>({name:e[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:e=>({name:e[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:e[1]}})}]}];function He(e,t){let i=[];if(e===".go"&&t.some(n=>n.kind==="TypeDeclaration")&&i.push("Go type"),e===".rs"&&(t.some(n=>n.kind==="TraitDeclaration")&&i.push("Rust trait"),t.some(n=>n.kind==="StructDeclaration")&&i.push("Rust struct"),t.some(n=>n.kind==="EnumDeclaration")&&i.push("Rust enum")),e===".py"){for(let n of t)if(n.capabilities)try{if(JSON.parse(n.capabilities).decoratorNames?.length){i.push("Python decorators");break}}catch{}t.some(n=>n.kind==="AsyncFunctionDeclaration"||n.kind==="AsyncMethodDeclaration")&&i.push("Async")}return i}var ae=class{phpParser=new se;pythonParser=new re;treeSitterParser=new ie;supports(t){return _e.some(i=>i.extension.includes(t.toLowerCase()))}async parse(t,i){let n=me.extname(t).toLowerCase(),s=[],p=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let g=this.pythonParser.parse(i);s=g.nodes,p=g.events}else if(n===".php"){let g=t.toLowerCase().endsWith("api.php"),l=this.phpParser.parse(i,g);s=l.nodes,p=l.events}else try{s=await this.treeSitterParser.parse(t,i)}catch{}if(s.length>0){let g=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",l=s.filter(r=>r.classification!=="Dependency"),f=s.filter(r=>r.classification==="Dependency"),a=He(n,s),c=X({classification:g,capabilities:a,exports:l.map(r=>({name:r.name,kind:r.kind,classification:r.classification})),fileName:me.basename(t)});return{exports:l,imports:f.map(r=>({module:r.name,name:r.name,kind:r.kind,classification:r.classification})),events:p,classification:g,summary:c||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let d=_e.find(g=>g.extension.includes(n));if(!d)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};for(let g of d.rules){g.regex.lastIndex=0;let l;for(;(l=g.regex.exec(i))!==null;){let f=g.onMatch(l),a=i.substring(0,l.index).split(`
36
- `).length;s.push({name:f.name||"anonymous",kind:f.kind||"Unknown",classification:f.classification||"Other",signature:f.signature||l[0],line:a,endLine:a,doc:"",capabilities:JSON.stringify(f.meta||{})})}}let h=X({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:s.map(g=>({name:g.name,kind:g.kind,classification:g.classification})),fileName:me.basename(t)});return{exports:s,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:h||"Module",parseStatus:s.length>0?"success":"partial"}}};var de=new ae;async function Nt(e){let t=Ae.extname(e);if(de.supports(t)&&t!==".ts"&&t!==".tsx")try{let p=await Pe.promises.readFile(e,"utf-8");return{...await de.parse(e,p),content:p}}catch(p){return H.error({filePath:e,error:p.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:p.message}}let i;try{i=await Pe.promises.readFile(e)}catch(p){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${p.message}`}}let n=i.toString("utf8"),s=he(n);try{let p=e.endsWith(".tsx"),d=e.endsWith(".d.ts")||e.endsWith(".d.tsx"),h,g={syntax:"typescript",tsx:p,decorators:!0,comments:!0};if(d)try{h=fe.parseSync(n,g)}catch{h=fe.parseSync(n,{...g,isModule:!1})}else h=fe.parseSync(n,g);let l=h.span.start,f=ye(i),a=be(n),c=M=>ge(M,l,i),r=De(h.body),o=Te(h.body);o.length>0&&H.debug({filePath:e,count:o.length},"Extracted type references"),o.forEach(M=>{r.push({module:"__type_reference__",name:M})});let u=ve(h.body,l,i,n,s,a,e,c,f),y=Se(h.body,l,i,s,c,f),m=ne(e,"","Module"),b=a.length>0&&a[0].start===0?a[0].text:u.find(M=>M.doc)?.doc||"",C=xe(b);if(!C&&u.length>0){let M=K(n);C=X({classification:m,capabilities:M,exports:u.map(_=>({name:_.name,kind:_.kind,classification:_.classification})),fileName:Ae.basename(e)})}return{exports:u,imports:r,events:y,classification:m,summary:C,content:n,parseStatus:"success"}}catch(p){H.warn({filePath:e,error:p.message},"SWC parsing failed, using heuristic fallback");try{let d=await de.parse(e,n);return{...d,content:n,classification:d.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${p.message}`}}catch(d){return H.error({filePath:e,error:d.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${d.message}`}}}}export{Nt as parseFile};
27
+ `;default:return""}}mapKind(t,i){if(t==="import")return"ImportDeclaration";if(i===".php"){if(t==="func")return"FunctionDeclaration";if(t==="class")return"ClassDeclaration";if(t==="interface")return"InterfaceDeclaration";if(t==="trait")return"TraitDeclaration";if(t==="method")return"MethodDeclaration"}if(i===".py"){if(t==="func")return"FunctionDeclaration";if(t==="class")return"ClassDeclaration"}if(i===".go"){if(t==="func")return"FunctionDeclaration";if(t==="type")return"TypeDeclaration"}if(i===".rs"){if(t==="func")return"FunctionDeclaration";if(t==="struct")return"StructDeclaration";if(t==="enum")return"EnumDeclaration";if(t==="trait")return"TraitDeclaration";if(t==="type")return"TypeDeclaration"}return"Unknown"}mapClassification(t){return t==="import"?"Dependency":t==="func"||t==="method"?"Function":t==="class"||t==="interface"||t==="trait"||t==="struct"||t==="enum"||t==="type"?"Class":"Other"}async parse(t,i){await this.ensureInitialized();let n=ke.extname(t).toLowerCase(),s=await this.getLanguage(n);if(!s||!this.parser)return[];this.parser.setLanguage(s);let u=this.parser.parse(i),d=i.split(`
28
+ `),h=this.getQueries(n);if(!h)return[];let o=new H.Query(s,h).matches(u.rootNode),l=[];for(let a of o){let p=a.captures.find(c=>c.name==="name")?.node,f=a.captures[0].node,r=a.captures[0].name;if(p){let c=f.startPosition.row+1,y=f.endPosition.row+1,m=d[f.startPosition.row].trim();l.push({name:p.text,kind:this.mapKind(r,n),classification:this.mapClassification(r),signature:m,line:c,endLine:y,doc:"",capabilities:"{}"})}}return l}};var se=class{parse(t,i=!1){let n=[],s=[],u=t.split(`
29
+ `),d="",h="",S=0,o=0,l=-1,a=-1,p=[],f=[],r=!1,c=i?"api":"",y="",m=/^namespace\s+([a-zA-Z0-9_\\]+);/,g=/^(?:abstract\s+)?(?:readonly\s+)?class\s+([a-zA-Z0-9_]+)/,T=/^interface\s+([a-zA-Z0-9_]+)/,M=/^trait\s+([a-zA-Z0-9_]+)/,w=/^(?:public|protected|private|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/,A=/^use\s+([a-zA-Z0-9_\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?;/,E=/^#\[([a-zA-Z0-9_\\]+)(?:\((.*)\))?\]/,U=/(?:Route::|router->|\$router->|->)(get|post|put|delete|patch|match)\s*\(\s*(?:uri\s*:\s*)?['"]([^'"]+)['"]/,I=/->prefix\s*\(\s*(?:prefix\s*:\s*)?['"]([^'"]+)['"]/;for(let R=0;R<u.length;R++){let v=u[R].trim();if(!v)continue;let $=(v.match(/{/g)||[]).length,ce=(v.match(/}/g)||[]).length,le=o;if(o+=$-ce,h&&o<=a){let D=n.find(b=>b.name===h&&b.line===S);D&&(D.endLine=R+1),h="",a=-1}if(d&&o<=l){let D=n.find(b=>b.name===d&&(b.kind==="ClassDeclaration"||b.kind==="TraitDeclaration"||b.kind==="InterfaceDeclaration"));D&&(D.endLine=R+1),d="",l=-1}let Y=v.match(I);if(Y&&(c=Y[1]),v.includes("});")&&(c=""),v.startsWith("/**")){r=!0,f=[];continue}if(r){v.endsWith("*/")?r=!1:f.push(v.replace(/^\*\s?/,""));continue}let q=v.match(E);if(q){p.push(q[1]);continue}let G=v.match(m);if(G){y=G[1]||"",p=[],f=[];continue}let C=v.match(g);if(C){d=C[1],l=o-$;let D={attributes:p};y&&(D.namespace=y),n.push({name:d,kind:"ClassDeclaration",classification:"Class",signature:`class ${d}`,line:R+1,endLine:R+1,doc:f.join(`
30
+ `).trim(),capabilities:JSON.stringify(D),members:[]}),p=[],f=[];continue}let x=v.match(T);if(x){let D=x[1];d=D,l=o-$,n.push({name:D,kind:"InterfaceDeclaration",classification:"Interface",signature:`interface ${D}`,line:R+1,endLine:R+1,doc:f.join(`
31
+ `).trim(),capabilities:JSON.stringify({attributes:p}),members:[]}),p=[],f=[];continue}let L=v.match(M);if(L){let D=L[1];d=D,l=o-$,n.push({name:D,kind:"TraitDeclaration",classification:"Trait",signature:`trait ${D}`,line:R+1,endLine:R+1,doc:f.join(`
32
+ `).trim(),capabilities:JSON.stringify({attributes:p}),members:[]}),p=[],f=[];continue}let K=v.match(w);if(K){let D=K[1],b=!!d;h=D,S=R+1,a=o-$;let J=!1,W={};for(let _ of p)_.toLowerCase().includes("route")&&(J=!0,W={type:"route",method:"GET",path:"/"});let z=f.join(`
33
+ `).trim();if(J){let _=W.path||"/";n.push({name:_,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${D}`,line:R+1,endLine:R+1,doc:z,capabilities:JSON.stringify({type:"route",handler:d?`${d}@${D}`:D,...W})}),s.push({type:"api_route",name:_,direction:"consume",line:R+1,snippet:v})}n.push({name:D,kind:b?"MethodDeclaration":"FunctionDeclaration",classification:b?"Method":"Function",signature:`${b?d+":: ":""}${D}`,line:R+1,endLine:R+1,doc:z,capabilities:JSON.stringify({attributes:p})}),p=[],f=[];continue}let Z=v.match(A);if(Z){let D=Z[1]||"",b=Z[2]||D.split("\\").pop()||"";n.push({name:b,kind:"ImportSpecifier",classification:"Dependency",signature:`use ${D}`,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"use",namespace:D})}),p=[],f=[];continue}let V=v.match(U);if(V){let D=V[1].toUpperCase(),b=V[2];if(v.includes("Route::")||v.includes("router->")||v.includes("action")||v.includes(",")&&!v.includes("view(")){if(c){let B=c.startsWith("/")?c:`/${c}`,pe=b.startsWith("/")?b:`/${b}`;b=(B+pe).replace(/\/+/g,"/")}let W=null,z=v.match(/\[\s*([a-zA-Z0-9_]+)::class\s*,\s*['"]([^'"]+)['"]\s*\]/);if(z)W=`${z[1]}@${z[2]}`;else if(v.includes("::class")){let B=v.match(/([a-zA-Z0-9_]+)::class/);B&&(W=B[1])}let _=v;!v.endsWith(");")&&R+1<u.length&&(_+=" "+u[R+1].trim(),!_.endsWith(");")&&R+2<u.length&&(_+=" "+u[R+2].trim())),n.push({name:b,kind:"HTTP Route",classification:"Service Boundary",signature:_,line:R+1,endLine:R+1,doc:"",capabilities:JSON.stringify({type:"route",method:D,path:b,handler:W})}),s.push({type:"api_route",name:b,direction:"consume",line:R+1,snippet:_,method:D,url:b}),f=[];continue}}let ee=/(?:\$client|client|Http)::(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)|(?:\$client|client)->(request|get|post|put|delete|patch)\s*\(\s*([^,)]+)/,j=v.match(ee);if(j){let D=(j[1]||j[3]).toUpperCase(),b=(j[2]||j[4]).trim();(b.startsWith("'")&&b.endsWith("'")||b.startsWith('"')&&b.endsWith('"'))&&(b=b.substring(1,b.length-1)),s.push({type:"api_route",name:b,direction:"produce",line:R+1,snippet:v,method:D,url:b})}!v.startsWith("#[")&&!v.startsWith("//")&&!v.startsWith("*")&&!r&&(p=[],f=[])}return{nodes:n,events:s}}};var re=class{currentRoutePrefix="";parse(t){this.currentRoutePrefix="";let i=[],n=[],s=t.split(`
34
+ `),u=[{indent:-1,name:"root",type:"root"}],d=[],h=/^class\s+([a-zA-Z0-9_]+)/,S=/^async\s+def\s+([a-zA-Z0-9_]+)|^def\s+([a-zA-Z0-9_]+)/,o=/^(?:from\s+([a-zA-Z0-9_\.]+)\s+import|import\s+([a-zA-Z0-9_\.]+))/,l=/^@(.*)/;function a(m){return m.trim().split(/[.(]/)[0]?.trim()||m}function p(m){let g=m.decorators.map(M=>a(M.raw)),T={decorators:m.decorators,decoratorNames:g};return m.async===!0&&(T.async=!0),JSON.stringify(T)}let f=!1,r="",c=[],y=[];for(let m=0;m<s.length;m++){let g=s[m],T=g.trim();if(!T||T.startsWith("#"))continue;let M=/^([a-zA-Z0-9_]+)\s*=\s*(?:APIRouter|Blueprint)\s*\(\s*(?:prefix\s*=\s*)?['"]([^'"]+)['"]/,w=T.match(M);if(w&&(this.currentRoutePrefix=w[2]),f){if(T.endsWith(r)||T.includes(r)){f=!1;let C=T.replace(r,"").trim();C&&c.push(C);let x=u[u.length-1];x.node&&(x.node.doc=c.join(`
35
+ `).trim()),c=[]}else c.push(T);continue}let A=g.search(/\S/),E=g.trim(),U=E.match(/^(['"]{3})/);if(U){let C=U[1],x=u[u.length-1];if(x.node&&!x.node.doc){if(E.substring(3).includes(C)){let L=E.replace(new RegExp(C,"g"),"").trim();x.node.doc=L}else{f=!0,r=C;let L=E.substring(3).trim();L&&c.push(L)}continue}}for(;u.length>1&&u[u.length-1].indent>=A;)u.pop();let I=u[u.length-1],R=E.match(l);if(R){d.push({raw:R[1].trim(),line:m+1});continue}let v=E.match(h);if(v){let C=v[1],x={name:C,kind:"ClassDeclaration",classification:"Class",signature:`class ${C}`,line:m+1,endLine:m+1,doc:"",capabilities:p({decorators:d}),members:[]};y.push(x),I.node?(I.node.members||(I.node.members=[]),I.node.members.push(x)):i.push(x),u.push({indent:A,name:C,type:"class",node:x}),d=[];continue}let $=E.match(S);if($){let C=!!$[1],x=$[1]||$[2],L=I.type==="class",K=!1,Z={};for(let b of d)if(b.raw.match(/(?:app|router)\.(get|post|put|delete|patch)/)){K=!0;let W=["get","post","put","delete","patch"].find(B=>b.raw.toLowerCase().includes(`.${B}`))?.toUpperCase()||"GET",z=b.raw.match(/['"]([^'"]+)['"]/),_=z?z[1]:"/";if(this.currentRoutePrefix){let B=this.currentRoutePrefix.endsWith("/")?this.currentRoutePrefix.slice(0,-1):this.currentRoutePrefix,pe=_.startsWith("/")?_:`/${_}`;_=B+pe}Z={type:"route",method:W,path:_}}if(K){let b=Z.path||"",J={name:b||x,kind:"HTTP Route",classification:"Service Boundary",signature:`Function: ${x}`,line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({handler:L?`${I.name}.${x}`:x,async:C,...Z})};y.push(J),i.push(J),n.push({type:"api_route",name:b,direction:"consume",line:m+1,snippet:E})}let V=d.some(b=>b.raw==="staticmethod"),ee=d.some(b=>b.raw==="classmethod"),j=`${C?"async ":""}${L?(V?"@staticmethod ":ee?"@classmethod ":"")+I.name+".":""}${x}`,D={name:x,kind:C&&L?"AsyncMethodDeclaration":C?"AsyncFunctionDeclaration":L?"MethodDeclaration":"FunctionDeclaration",classification:L?V||ee?"Static Method":"Method":"Function",signature:j,line:m+1,endLine:m+1,doc:"",capabilities:p({decorators:d,async:C}),members:[]};y.push(D),I.node?(I.node.members||(I.node.members=[]),I.node.members.push(D)):i.push(D),u.push({indent:A,name:x,type:"function",node:D}),d=[];continue}let ce=/^(?:path|re_path|url)\s*\(\s*['"]([^'"]+)['"]/,le=E.match(ce);if(le){let C=le[1].replace(/^\^/,""),x={name:C,kind:"HTTP Route",classification:"Service Boundary",signature:E.trim(),line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({type:"route",method:"GET",path:C})};y.push(x),i.push(x),n.push({type:"api_route",name:C,direction:"consume",line:m+1,snippet:E});continue}let Y=/(?:requests|httpx|client|http)\.(get|post|put|delete|patch|request)\s*\(\s*(?:url\s*:\s*)?([^,)]+)/,q=E.match(Y);if(q){let C=q[1].toUpperCase(),x=q[2].trim();(x.startsWith("'")&&x.endsWith("'")||x.startsWith('"')&&x.endsWith('"'))&&(x=x.substring(1,x.length-1)),n.push({type:"api_route",name:x,direction:"produce",line:m+1,snippet:E,method:C,url:x})}let G=E.match(o);if(G){let C=G[1]||G[2],x={name:C,kind:"ImportSpecifier",classification:"Dependency",signature:`import ${C}`,line:m+1,endLine:m+1,doc:"",capabilities:JSON.stringify({type:"import",module:C})};y.push(x),i.push(x),d=[];continue}d=[],I.node&&(I.node.endLine=m+1)}return{nodes:y,events:n}}};function qe(e,t){let i=0,n=!1;for(let s=t;s<e.length;s++){let u=e[s];for(let d of u)if(d==="{")i++,n=!0;else if(d==="}"&&(i--,n&&i<=0))return s+1;if(!n&&s>t&&/[;}]$/.test(u.trim()))return s+1}return Math.min(e.length,t+41)}var Ie=[{extension:[".php"],rules:[]},{extension:[".py"],rules:[]},{extension:[".go"],rules:[{regex:/func\s+([a-zA-Z0-9_]+)\(/g,onMatch:e=>({name:e[1],kind:"FunctionDeclaration",classification:"Function",signature:e[0]})},{regex:/func\s+\([^\)]+\)\s+([a-zA-Z0-9_]+)\(/g,onMatch:e=>({name:e[1],kind:"MethodDeclaration",classification:"Method",signature:e[0]})},{regex:/import\s+['"]([^'"]+)['"]/g,onMatch:e=>({name:e[1],kind:"ImportSpecifier",classification:"Dependency",signature:e[0],meta:{type:"import",path:e[1]}})}]},{extension:[".rs"],rules:[{regex:/fn\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:e=>({name:e[1],kind:"FunctionDeclaration",classification:"Function",signature:e[0]})},{regex:/struct\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"StructDeclaration",classification:"Class",signature:e[0]})},{regex:/enum\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"EnumDeclaration",classification:"Class",signature:e[0]})},{regex:/trait\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"TraitDeclaration",classification:"Class",signature:e[0]})},{regex:/use\s+([a-zA-Z0-9_:]+(?:\s+as\s+[a-zA-Z0-9_]+)?);/g,onMatch:e=>({name:e[1].trim(),kind:"ImportDeclaration",classification:"Dependency",signature:e[0],meta:{type:"import",path:e[1].trim()}})}]},{extension:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],rules:[{regex:/(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z0-9_]+)\s*\(/g,onMatch:e=>({name:e[1],kind:"FunctionDeclaration",classification:"Function"})},{regex:/(?:export\s+)?class\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"ClassDeclaration",classification:"Class"})},{regex:/(?:export\s+)?interface\s+([a-zA-Z0-9_]+)/g,onMatch:e=>({name:e[1],kind:"InterfaceDeclaration",classification:"Interface"})},{regex:/(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=/g,onMatch:e=>({name:e[1],kind:"VariableDeclaration",classification:"Constant"})},{regex:/import\s+.*\s+from\s+['"]([^'"]+)['"]/g,onMatch:e=>({name:e[1],kind:"ImportDeclaration",classification:"Dependency",meta:{path:e[1]}})}]}];function Ge(e,t){let i=[];if(e===".go"&&t.some(n=>n.kind==="TypeDeclaration")&&i.push("Go type"),e===".rs"&&(t.some(n=>n.kind==="TraitDeclaration")&&i.push("Rust trait"),t.some(n=>n.kind==="StructDeclaration")&&i.push("Rust struct"),t.some(n=>n.kind==="EnumDeclaration")&&i.push("Rust enum")),e===".py"){for(let n of t)if(n.capabilities)try{if(JSON.parse(n.capabilities).decoratorNames?.length){i.push("Python decorators");break}}catch{}t.some(n=>n.kind==="AsyncFunctionDeclaration"||n.kind==="AsyncMethodDeclaration")&&i.push("Async")}return i}var ae=class{phpParser=new se;pythonParser=new re;treeSitterParser=new ie;supports(t){return Ie.some(i=>i.extension.includes(t.toLowerCase()))}async parse(t,i){let n=fe.extname(t).toLowerCase(),s=[],u=[];if(n===".php"||n===".py"||n===".go"||n===".rs"){if(n===".py"){let o=this.pythonParser.parse(i);s=o.nodes,u=o.events}else if(n===".php"){let o=t.toLowerCase().endsWith("api.php"),l=this.phpParser.parse(i,o);s=l.nodes,u=l.events}else try{s=await this.treeSitterParser.parse(t,i)}catch{}if(s.length>0){let o=n===".php"?"Micro IR (PHP/TS) ":n===".py"?"Micro IR (Python/TS) ":n===".go"?"Micro IR (Go/TS) ":"Micro IR (Rust/TS) ",l=s.filter(r=>r.classification!=="Dependency"),a=s.filter(r=>r.classification==="Dependency"),p=Ge(n,s),f=X({classification:o,capabilities:p,exports:l.map(r=>({name:r.name,kind:r.kind,classification:r.classification})),fileName:fe.basename(t)});return{exports:l,imports:a.map(r=>({module:r.name,name:r.name,kind:r.kind,classification:r.classification})),events:u,classification:o,summary:f||`${n.substring(1).toUpperCase()} module`,parseStatus:"success"}}}let d=Ie.find(o=>o.extension.includes(n));if(!d)return{exports:[],imports:[],classification:"Unknown",summary:"",parseStatus:"failed",parseError:`Unsupported file extension: ${n}`};let h=i.split(`
36
+ `);for(let o of d.rules){o.regex.lastIndex=0;let l;for(;(l=o.regex.exec(i))!==null;){let a=o.onMatch(l),p=i.substring(0,l.index).split(`
37
+ `).length,f=qe(h,p-1);s.push({name:a.name||"anonymous",kind:a.kind||"Unknown",classification:a.classification||"Other",signature:a.signature||l[0],line:p,endLine:f,doc:"",capabilities:JSON.stringify(a.meta||{})})}}let S=X({classification:`Micro IR (${n.substring(1).toUpperCase()})`,capabilities:[],exports:s.map(o=>({name:o.name,kind:o.kind,classification:o.classification})),fileName:fe.basename(t)});return{exports:s,imports:[],classification:`Micro IR (${n.substring(1).toUpperCase()})`,summary:S||"Module",parseStatus:s.length>0?"success":"partial"}}};import*as de from"@swc/core";function _e(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.parse=="function"&&typeof t.parseSync=="function"}function Ve(){if(_e(de))return de;let e=de;if(_e(e.default))return e.default;throw new Error("SWC runtime unavailable: couldn't resolve parse/parseSync from @swc/core exports")}var Ke=Ve();function oe(e,t,i){return Ke.parseSync(e,t,i)}var ye=new ae;async function Ot(e){let t=Le.extname(e);if(ye.supports(t)&&t!==".ts"&&t!==".tsx")try{let u=await Ae.promises.readFile(e,"utf-8");return{...await ye.parse(e,u),content:u}}catch(u){return O.error({filePath:e,error:u.message},"HeuristicParser failed"),{exports:[],imports:[],classification:"Unknown",summary:"",content:"",parseStatus:"failed",parseError:u.message}}let i;try{i=await Ae.promises.readFile(e)}catch(u){return{exports:[],imports:[],classification:"Error",summary:"",content:"",parseStatus:"failed",parseError:`File read error: ${u.message}`}}let n=i.toString("utf8"),s=he(n);try{let u=e.endsWith(".tsx"),d=e.endsWith(".d.ts")||e.endsWith(".d.tsx"),h,S={syntax:"typescript",tsx:u,decorators:!0,comments:!0};if(d)try{h=oe(n,S)}catch{h=oe(n,{...S,isModule:!1})}else h=oe(n,S);let o=h.span.start,l=ge(i),a=xe(n),p=w=>be(w,o,i),f=Se(h.body),r=Re(h.body);r.length>0&&O.debug({filePath:e,count:r.length},"Extracted type references"),r.forEach(w=>{f.push({module:"__type_reference__",name:w})});let c=ve(h.body,o,i,n,s,a,e,p,l),y=Te(h.body,o,i,s,p,l),m=ne(e,"","Module"),T=a.length>0&&n.slice(0,a[0].start).trim().length===0?a[0].text:c.find(w=>w.doc)?.doc||"",M=De(T);if(!M&&c.length>0){let w=Q(n);M=X({classification:m,capabilities:w,exports:c.map(A=>({name:A.name,kind:A.kind,classification:A.classification})),fileName:Le.basename(e)})}return{exports:c,imports:f,events:y,classification:m,summary:M,content:n,parseStatus:"success"}}catch(u){O.warn({filePath:e,error:u.message},"SWC parsing failed, using heuristic fallback");try{let d=await ye.parse(e,n);return{...d,content:n,classification:d.classification+" (Degraded)",parseStatus:"partial",parseError:`SWC failed, used heuristic fallback: ${u.message}`}}catch(d){return O.error({filePath:e,error:d.message},"All parsing strategies failed"),{exports:[],imports:[],classification:"Error",summary:"",content:n,parseStatus:"failed",parseError:`All parsing strategies failed: ${d.message}`}}}}export{Ot as parseFile};
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: audit
3
+ description: Perform codebase health audits to identify dead code, circular dependencies, and technical debt. Use when auditing code quality, finding unused code, detecting circular dependencies, or when the user asks about codebase health, technical debt, or code cleanup.
4
+ ---
5
+
6
+ # Codebase Audit
7
+
8
+ Comprehensive health audit using Shadow analyze toolkit.
9
+
10
+ ## 🚀 Workflow
11
+
12
+ 1. **Session Context**: `shadow_ops_context` (repoPath) — **ONE CALL** for hologram + chronicle + briefing. Get architecture baseline.
13
+ 2. **Dead Code Detection**: `shadow_analyze_debt` (mode: "dead-code", limit: 100, includeTests: false, repoPath) — Unused exports.
14
+ 3. **Circular Dependencies**: `shadow_analyze_debt` (mode: "circular-deps", limit: 20, repoPath) — Import cycles.
15
+ 4. **Layer Integrity** (optional): `shadow_recon_topography` (repoPath) — Detailed layer analysis if hologram summary isn't enough.
16
+ 5. **Log Findings**: `shadow_ops_log` (missionId, type: "discovery", content, repoPath).
17
+ 6. **Create Cleanup Mission** (optional): `shadow_ops_plan` (name: "Codebase Cleanup", templateId: "refactoring", templateVars, repoPath).
18
+
19
+ ## 🛠 Precise Tooling
20
+
21
+ | Audit Target | Atomic Tool |
22
+ | :------------------- | :------------------------------------------------------------------------------------- |
23
+ | **Session Start** 🚀 | `shadow_ops_context` (repoPath) — **START HERE** for baseline |
24
+ | **Architecture** | `shadow_recon_hologram` (repoPath) — if you need standalone |
25
+ | **Dead Code** | `shadow_analyze_debt` (mode: "dead-code", limit: 100, **confidenceThreshold: "high"**) |
26
+ | **Circular Deps** | `shadow_analyze_debt` (mode: "circular-deps") |
27
+ | **Layers** | `shadow_recon_topography` — detailed breakdown if needed |
28
+ | **Config Audit** | `shadow_search_config` (kind: "Env", **showUsage: true**) — find orphaned env vars |
29
+
30
+ ## 💡 Intelligence Options
31
+
32
+ - **`shadow_analyze_debt` confidence levels**: Use `confidenceThreshold: "high"` for likely dead code, `"medium"` for possibly intentional (test fixtures, etc.), `"all"` for everything.
33
+ - **`shadow_analyze_debt` exclusion filters**: Use `excludePatterns`, `includeMigrations: false`, `includeFixtures: false` to reduce noise.
34
+ - **`shadow_search_config` with `showUsage: true`**: Cross-references config vars with code to show usage counts and identify orphaned vars (defined but never used).
35
+
36
+ ## 🔍 Health Criteria
37
+
38
+ - **Critical Issues**: Circular deps in core logic, >50 dead exports, orphaned env vars with secrets
39
+ - **Warning Signs**: Layer violations (Test → Logic), >20 dead exports, >10 orphaned configs
40
+ - **Good Health**: Clean layers, <10 dead exports, no circular deps, all configs in use
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: chronicle
3
+ description: Retrieve and analyze the repository's narrative archive as recorded in Git-native memory. Use when you need to understand historical decisions, catch up on repository progress, review recently completed missions, or when the user asks for a project history, changelog, or chronological overview of architectural changes.
4
+ ---
5
+
6
+ # Repository Chronicle
7
+
8
+ Retrieve narrative archive from Git-native memory.
9
+
10
+ ## 🚀 Workflow
11
+
12
+ 1. **Recent History**: `shadow_ops_chronicle` (limit: 10, format: "markdown", repoPath) — Last 10 entries.
13
+ 2. **Time-Filtered**:
14
+ - `shadow_ops_chronicle` (since: &lt;unix&gt;, limit: 20, repoPath)
15
+ - `shadow_ops_chronicle` (until: &lt;unix&gt;, limit: 20, repoPath)
16
+ 3. **Structured Data**: `shadow_ops_chronicle` (format: "json", limit: 50, repoPath) — For processing.
17
+ 4. **Paginated**: `shadow_ops_chronicle` (limit: 10, offset: 10, repoPath) — Second page.
18
+
19
+ ## 🛠 Precise Tooling
20
+
21
+ | Chronicle Query | Atomic Tool |
22
+ | :-------------------- | :---------------------------------------------------------------- |
23
+ | **Recent (Markdown)** | `shadow_ops_chronicle` (limit: 10, format: "markdown") |
24
+ | **Time Range** | `shadow_ops_chronicle` (since: &lt;unix&gt;, until: &lt;unix&gt;) |
25
+ | **JSON Data** | `shadow_ops_chronicle` (format: "json", limit: 50) |
26
+ | **Pagination** | `shadow_ops_chronicle` (limit: 10, offset: 10) |
27
+
28
+ ## Output Formats
29
+
30
+ - **`format: "markdown"`** (default): Human-readable narrative feed with missions grouped as Strategic Initiatives and Standalone Episodes
31
+ - **`format: "json"`**: Structured data for programmatic analysis (includes missionId, steps, timestamps, ADRs)
32
+
33
+ ## Use Cases
34
+
35
+ - **Onboarding**: Read last 10 entries to catch up
36
+ - **Release Notes**: Get completed missions since last release
37
+ - **ADR Review**: Extract all architectural decisions
38
+ - **Progress Reports**: Show what's been done this week
39
+
40
+ **Note:** Chronicle reads from Git Notes, so it's persistent across branches and clones.
@@ -0,0 +1,55 @@
1
+ ---
2
+ name: continue
3
+ description: Get briefing, pick one mission from next_work_candidates, then work that mission to completion with all remaining steps in one run. Use when continuing work on missions, executing mission steps, or when the user asks to continue work, finish a mission, or proceed with development tasks.
4
+ ---
5
+
6
+ **In one sentence:** Get briefing (+ optional trace), pick **one mission** from **next_work_candidates** (ranked by relevance), then work that mission to completion — all remaining steps in one run. Update and log as you go. No status reports; when you're done with that mission, it's done.
7
+
8
+ ---
9
+
10
+ ## 1. Context
11
+
12
+ - **Option A (one shot):** `shadow_ops_context` (repoPath) → returns hologram + chronicle(5) + **briefing** (counts, **next_work_candidates** ranked by relevance). Use when you want architecture + history + backlog in one call at the start of /continue.
13
+ - **Option B:** `shadow_ops_briefing` (scope: "project", repoPath) → **next_work_candidates** (relevance-ranked), hierarchy, analytics.
14
+ - Use **altitude** to control output density: `orbit` (~200 tokens, counts + candidates only), `atmosphere` (default, strategy + crystals), `ground` (raw logs + working set + collisions).
15
+ - `shadow_sync_trace` (repoPath) only if you care about external changes. Otherwise skip.
16
+
17
+ ## 2. Pick one mission
18
+
19
+ - **`next_work_candidates`** are ranked by the MissionRelevanceScorer (recency × 0.4 + activity × 0.3 + status × 0.2 + blockers × 0.1). Higher score = more relevant.
20
+ - Choose the top-ranked candidate. Prefer in-progress over planned. Parent-only missions (umbrellas) are already filtered out.
21
+
22
+ ## 3. Work the whole mission
23
+
24
+ - For that mission, run through **all remaining steps** (not just one):
25
+ - **Surgical Discovery:** `shadow_analyze_flow` (symbolName, filePath, repoPath).
26
+ - **Execute Step**: Set in-progress → implement → `shadow_ops_track` (missionId, stepId, status: "completed", contextPivot, repoPath).
27
+ - **Atomic Logging:** At least once per step. `shadow_ops_log` (missionId, type: "decision", content, symbolName, repoPath).
28
+ - **Seal the mission**: `shadow_ops_track` (missionId, status: "completed", repoPath).
29
+ - This **auto-triggers**: ADR synthesis, Git Notes persistence, and cascade parent completion (if all sibling missions are also done, the parent auto-completes too).
30
+ - No need to call `shadow_ops_synthesize` separately — it's automatic on completion.
31
+ - **Optional — Crystallize** (for long-running missions with many logs): `shadow_ops_crystallize` (missionId, repoPath) compresses raw intent logs into a single crystal summary. Useful mid-mission to keep briefings lean.
32
+
33
+ ## 🛠 Precise Tooling
34
+
35
+ | Action | Atomic Tool | Example |
36
+ | :--------------------- | :----------------------- | :------------------------------------------------------- |
37
+ | **Context (one shot)** | `shadow_ops_context` | repoPath — hologram + chronicle + briefing |
38
+ | **Briefing** | `shadow_ops_briefing` | scope: "project", altitude: "orbit", repoPath |
39
+ | **Flow Trace** | `shadow_analyze_flow` | symbolName: "handleRequest", filePath, repoPath |
40
+ | **Step Update** | `shadow_ops_track` | missionId: 4, stepId: "s2", status: "completed" |
41
+ | **Intent Log** | `shadow_ops_log` | missionId: 4, type: "fix", content: "..." |
42
+ | **Complete Mission** | `shadow_ops_track` | missionId: 4, status: "completed" — auto-synthesizes ADR |
43
+ | **Crystallize** | `shadow_ops_crystallize` | missionId: 4 — compress logs mid-mission |
44
+
45
+ _Note: Always use `symbolName` in `shadow_ops_log` to create Liquid Anchors._
46
+
47
+ ## 4. Don't
48
+
49
+ - Don't do one step and stop — /continue is "finish a mission," not "do one step."
50
+ - Don't call `shadow_ops_synthesize` after completing — it's automatic on `status: "completed"`.
51
+ - Don't long status reports. Don't ask "what should I work on?" unless a real tie. Don't auto-commit.
52
+
53
+ ---
54
+
55
+ **Tools:** `shadow_ops_context` (optional start), `shadow_ops_briefing`, `shadow_ops_track`, `shadow_ops_log`, `shadow_ops_crystallize`, `shadow_sync_trace`. For discovery: `shadow_search_*`, `shadow_recon_*`, `shadow_analyze_*`.
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: crystallize
3
+ description: Compress a mission's intent logs into a dense crystal summary for token-efficient briefings. Use when a mission has accumulated many raw logs, when briefings are too verbose, or when the user asks about log compression, crystallization, or context reduction.
4
+ ---
5
+
6
+ # Intent Log Crystallization
7
+
8
+ Compress raw intent logs into a single crystal summary node. The crystal replaces verbose raw logs in briefings, reducing token usage while preserving the mission's key decisions, context, and consequences.
9
+
10
+ ## When to Crystallize
11
+
12
+ - A mission has **10+ raw intent logs** and briefings are getting verbose.
13
+ - Mid-mission, before requesting a detailed briefing — keeps `atmosphere` altitude lean.
14
+ - Before synthesis (optional) — produces cleaner ADRs from compressed input.
15
+ - The briefing at `atmosphere` altitude already prefers crystals over raw logs (`findByMissionPreferCrystal`), so crystallizing makes those briefings significantly leaner.
16
+
17
+ ## Workflow
18
+
19
+ 1. **Crystallize**: `shadow_ops_crystallize` (missionId, repoPath) — Compresses all raw logs into one crystal node. Raw logs are marked as `absorbed`.
20
+ 2. **Verify**: `shadow_ops_briefing` (scope: "mission", missionId, altitude: "atmosphere", repoPath) — Crystal should appear in `recent_activity` instead of raw logs.
21
+
22
+ ## Precise Tooling
23
+
24
+ | Action | Atomic Tool | Usage |
25
+ | :--------------- | :--------------------------------------------- | :-------------------------------------- |
26
+ | **Crystallize** | `shadow_ops_crystallize` | missionId, repoPath — compress raw logs |
27
+ | **Check Status** | `shadow_ops_briefing` (altitude: "atmosphere") | Verify crystal appears in activity |
28
+ | **Full Logs** | `shadow_ops_briefing` (altitude: "ground") | Still shows raw logs if needed |
29
+
30
+ ## What the Crystal Contains
31
+
32
+ - Mission name and ID
33
+ - Count of compressed logs and symbols
34
+ - Log types present (decision, fix, discovery, blocker)
35
+ - Structured breakdown: decisions, context, consequences, recommendations
36
+
37
+ ## Notes
38
+
39
+ - Crystallization is **idempotent**: if no new raw logs exist, it reports `already_crystallized`.
40
+ - New logs added after crystallization remain as raw until the next crystallize call.
41
+ - Raw logs are **not deleted** — they're marked as absorbed. `ground` altitude still shows them.
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: mission
3
+ description: Define the objective, strategy, and success criteria for a new development mission. Use when planning strategic initiatives, creating missions, setting up development goals, or when the user asks about mission planning, strategic alignment, or outcome contracts.
4
+ ---
5
+
6
+ # Mission Strategy & Setup
7
+
8
+ Define the objective, strategy, and success criteria for a new mission. This workflow is for **Strategic Alignment and Planning**.
9
+
10
+ > **IMPORTANT**: This workflow stops at the "Ready to Execute" state. For implementation and automated execution, use **/continue**.
11
+
12
+ ## Workflow
13
+
14
+ 1. **Session Context**: `shadow_ops_context` (repoPath) — **ONE CALL** for hologram + chronicle(5) + briefing (with relevance-ranked `next_work_candidates`). Check existing candidates and recent decisions before creating new work.
15
+ 2. **Optional Expanded Context** (only if needed):
16
+ - `shadow_recon_topography` (repoPath) — Detailed layer breakdown to align goal with architecture.
17
+ - `shadow_ops_chronicle` (limit: 10, repoPath) — More historical ADRs if 5 isn't enough.
18
+ - `shadow_ops_briefing` (scope: "project", altitude: "ground", repoPath) — Full detail with analytics, collisions, and working sets.
19
+ 3. **Strategic Plan**: `shadow_ops_plan` (name, goal, outcomeContract, ...).
20
+ - **Strategy DAG**: Define logical steps and verification rules.
21
+ - **Initiative vs Mission**: Decide if this is a parent (Initiative) or a leaf (Mission). Parent missions auto-complete via cascade when all children finish.
22
+ 4. **Alignment**: Present the plan to the user. Do not begin execution until the user approves the strategy.
23
+
24
+ ## Precise Tooling
25
+
26
+ | Setup Action | Precise Tool Call | Usage |
27
+ | :-------------------- | :----------------------------------------- | :----------------------------------------------------------- |
28
+ | **Session Start** | `shadow_ops_context` | **START HERE** — hologram + chronicle + briefing in one call |
29
+ | **Establish Plan** | `shadow_ops_plan` | Create the mission and strategy. |
30
+ | **Architectural Map** | `shadow_recon_topography` | Contextualize the target layers (if context wasn't enough). |
31
+ | **Detailed Briefing** | `shadow_ops_briefing` (altitude: "ground") | Full analytics, collisions, working sets. |
32
+ | **Lean Briefing** | `shadow_ops_briefing` (altitude: "orbit") | Counts + candidates only (~200 tokens). |
33
+ | **Graph View** | `shadow_ops_graph` | Visualize the initiative's hierarchy. |
34
+
35
+ _Note: **Always start with `shadow_ops_context`** for instant mission landscape + architectural context. Ensure the `outcomeContract` is binary and verifiable. Parent initiatives auto-cascade on child completion — no manual closing needed._
36
+
37
+ ## Briefing Altitude Levels
38
+
39
+ - **`orbit`** (~200 tokens): Counts + relevance-ranked candidates only. Use for quick checks.
40
+ - **`atmosphere`** (default): Strategy graphs, crystal summaries, hierarchy, analytics.
41
+ - **`ground`** (full): Raw logs, working sets, collision analysis, ancestor activity.
42
+
43
+ ## Intent Logging (Strategic Quality)
44
+
45
+ Capture the "Why" and "How" during the planning phase to ensure the final ADR has architectural depth.
46
+
47
+ - **Decision Logs**: Capture why a specific strategy or library was chosen.
48
+ - **Discovery Logs**: Record insights found during initial reconnaissance.
49
+
50
+ **Hand-off**: Once the mission is planned and logged, the setup phase is over. Execute via `/continue`.
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: onboard
3
+ description: Initialize and analyze a new repository for deep intelligence by building semantic index, syncing state, activating git hooks, and establishing missions. Use when onboarding to a new repository, initializing Shadow Engine, setting up git hooks, or when the user asks about repository setup, initialization, or first-time configuration.
4
+ ---
5
+
6
+ # Repository Onboarding
7
+
8
+ Initialize and analyze a new repository for deep intelligence.
9
+
10
+ ## Workflow
11
+
12
+ 1. **Semantic Init**: `shadow_recon_onboard` (repoPath) — **Only run once** per repo to build the baseline. Auto-populates the hologram.
13
+ 2. **Read Hologram**: `shadow_recon_hologram` (repoPath) — Get instant architectural context (~1300 tokens: topography + gravity zones).
14
+ 3. **Unified Sync**: `shadow_sync_trace` (repoPath) — **The One-Stop Shop**. Performs indexing + ghost analysis + mission re-hydration.
15
+ 4. **Active Briefing**: `shadow_ops_briefing` (scope: "project", altitude: "atmosphere", repoPath) — Resumes the shared backlog with relevance-ranked candidates.
16
+ - Use `altitude: "orbit"` for a lean overview (~200 tokens), or `altitude: "ground"` for full detail.
17
+ 5. **Architectural Deep Dive** (optional):
18
+ - `shadow_recon_topography` (repoPath) — View layers (Entry/Logic/Data/Utility/Test).
19
+ - `shadow_ops_chronicle` (limit: 5, repoPath) — Narrative feed.
20
+ 6. **Hooks Activation**: `shadow_env_hooks` (action: "install", repoPath).
21
+ 7. **Establish Mission**: `shadow_ops_plan` (name, goal, repoPath).
22
+
23
+ ## Precise Tooling
24
+
25
+ | Action | Atomic Tool |
26
+ | :---------------- | :--------------------------------------------------------------- |
27
+ | **Index** | `shadow_recon_onboard` |
28
+ | **Hologram** | `shadow_recon_hologram` (repoPath) |
29
+ | **Layers** | `shadow_recon_topography` |
30
+ | **History** | `shadow_ops_chronicle` (limit: 10) |
31
+ | **Resume (lean)** | `shadow_ops_briefing` (scope: "project", altitude: "orbit") |
32
+ | **Resume (full)** | `shadow_ops_briefing` (scope: "project", altitude: "atmosphere") |
33
+ | **Hooks** | `shadow_env_hooks` (action: "install") |
34
+
35
+ _Note: Always use absolute paths for `repoPath`. Call `shadow_recon_hologram` immediately after init for instant architectural context._
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: research
3
+ description: Conduct high-signal research for external dependencies by combining local context, web search, and Context7 documentation. Use when researching libraries, checking integration examples, verifying versions, or when the user asks about external dependencies, library documentation, or integration patterns.
4
+ ---
5
+
6
+ # External Research
7
+
8
+ High-signal research for external dependencies.
9
+
10
+ ## 🚀 Workflow
11
+
12
+ 1. **Local Context**: `shadow_search_concept` (query: "library name", repoPath). Find existing integration examples.
13
+ 2. **Web Search**: Use the `WebSearch` tool for official docs and latest versions.
14
+ 3. **Deep Intel (Context7)**: resolve-library-id, query-docs (server: user-context7).
15
+ 4. **Integration Check**: `shadow_inspect_file` (filePath, detailLevel: "signatures", repoPath).
16
+ 5. **Log Findings**: `shadow_ops_log` (type: "discovery", content, repoPath).
17
+
18
+ ## 🛠 Precise Tooling
19
+
20
+ | Discovery Layer | Atomic Tool |
21
+ | :----------------- | :-------------------------------------------------------------------------- |
22
+ | **Local Usage** | `shadow_search_concept` (query, **compact: true** for broad search) |
23
+ | **File Discovery** | `shadow_search_path` (query, **ranked: true**) — gravity-sorted with layers |
24
+ | **Config Check** | `shadow_search_config` (key, **showUsage: true**) — with usage counts |
25
+ | **External Docs** | context7 tools (user-context7) |
26
+ | **Relational** | `shadow_analyze_deps` (filePath, direction) |
27
+
28
+ ## 💡 Intelligence Options
29
+
30
+ - **`shadow_search_concept` with `compact: true`**: Returns file paths + scores without snippets (~60% token savings). Use for broad exploration.
31
+ - **`shadow_search_path` with `ranked: true`**: Results sorted by gravity (high-import files first) with layer classification. Reveals architecturally important files.
32
+ - **`shadow_search_config` with `showUsage: true`**: Shows usage counts per config var and identifies orphaned vars (defined but never used in code).
33
+
34
+ _Note: Always check `package.json` for the exact version before querying Context7 to ensure documentation alignment._
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: sync
3
+ description: Sync index and mission state after external changes. Day-to-day: index + NanoRepair run automatically when MCP tools (search, inspect, etc.) trigger reindex. Use trace after git pull/checkout/merge (or rely on hooks); use index deep:true for full rebuild.
4
+ ---
5
+
6
+ # Repository Synchronization
7
+
8
+ **Day-to-day:** Index and NanoRepair run automatically when you use MCP tools (search, inspect, analyze, etc.) and a reindex occurs. No manual sync needed for edits or renames.
9
+
10
+ ## When to run sync manually
11
+
12
+ | Situation | Action |
13
+ | :-------------------------------- | :----------------------------------------------------------------- |
14
+ | **After git pull/checkout/merge** | `shadow_sync_trace` (repoPath) — or rely on Git hooks if installed |
15
+ | **Full rebuild (corruption)** | `shadow_sync_index` (repoPath; use deep: true if supported) |
16
+ | **Repair only (rare)** | `shadow_sync_repair` (repoPath) |
17
+
18
+ **Note:** `trace` does index + ghost analysis + NanoRepair + lifecycle + mission re-hydration. Hooks run it on commit/checkout/merge.