knodin 0.7.4 → 0.7.6

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 (104) hide show
  1. package/README.md +4 -1
  2. package/dist/bin/cli.js +108 -1859
  3. package/dist/bin/launcher.js +3 -10
  4. package/dist/chunks/chunk-DMQAGX77.js +654 -0
  5. package/dist/chunks/chunk-F4Z3Z766.js +4 -0
  6. package/dist/chunks/chunk-SIJAQVSX.js +3 -0
  7. package/dist/chunks/chunk-X6M4HUUE.js +2 -0
  8. package/dist/chunks/chunk-YPRMY2LP.js +8 -0
  9. package/dist/chunks/pure-compression-cli-4TA2TQD5.js +5 -0
  10. package/dist/chunks/server-7EDF4CBY.js +14 -0
  11. package/dist/chunks/structural-fast-path-KD5KQSPX.js +4 -0
  12. package/dist/src/init-progress-worker.js +2 -106
  13. package/dist/src/repair-progress-worker.js +2 -120
  14. package/docs/INSTALLATION.md +17 -1
  15. package/docs/releases/0.7.6.md +25 -0
  16. package/package.json +1 -110
  17. package/dist/src/agent-integration.js +0 -238
  18. package/dist/src/artifact-refresh.js +0 -81
  19. package/dist/src/cli-args.js +0 -274
  20. package/dist/src/cli-model.js +0 -358
  21. package/dist/src/codeflow-replay.js +0 -80
  22. package/dist/src/compact-structural.js +0 -96
  23. package/dist/src/competitive-cold-mcp.js +0 -40
  24. package/dist/src/competitive-constraints.js +0 -20
  25. package/dist/src/competitive-manifest.js +0 -411
  26. package/dist/src/competitive-measurement.js +0 -183
  27. package/dist/src/competitive-runner.js +0 -487
  28. package/dist/src/competitive-sandbox.js +0 -108
  29. package/dist/src/context-export.js +0 -422
  30. package/dist/src/context.js +0 -102
  31. package/dist/src/diagnostics.js +0 -449
  32. package/dist/src/docs-sections.js +0 -141
  33. package/dist/src/doctor.js +0 -380
  34. package/dist/src/engine/ann-hnsw.js +0 -271
  35. package/dist/src/engine/embeddings.js +0 -193
  36. package/dist/src/engine/file-walker.js +0 -43
  37. package/dist/src/engine/git-history.js +0 -289
  38. package/dist/src/engine/index.js +0 -13377
  39. package/dist/src/engine/perf.js +0 -115
  40. package/dist/src/engine/prune.js +0 -112
  41. package/dist/src/engine/scip-import.js +0 -408
  42. package/dist/src/engine/source-policy.js +0 -69
  43. package/dist/src/engine/sqlite.js +0 -71
  44. package/dist/src/engine/symbol-delete.js +0 -58
  45. package/dist/src/execution-profile.js +0 -203
  46. package/dist/src/failure-diagnosis.js +0 -649
  47. package/dist/src/fleet.js +0 -7
  48. package/dist/src/git-executable.js +0 -31
  49. package/dist/src/graph-query-health.js +0 -115
  50. package/dist/src/hook-manager-integration.js +0 -156
  51. package/dist/src/index-activity.js +0 -125
  52. package/dist/src/init-progress.js +0 -155
  53. package/dist/src/init.js +0 -1254
  54. package/dist/src/lifecycle-health.js +0 -250
  55. package/dist/src/lsp-readonly.js +0 -217
  56. package/dist/src/output-compression.js +0 -629
  57. package/dist/src/output-telemetry.js +0 -363
  58. package/dist/src/pr-triage.js +0 -638
  59. package/dist/src/progressive-evidence.js +0 -473
  60. package/dist/src/pure-compression-cli.js +0 -101
  61. package/dist/src/relationship-adapters.js +0 -370
  62. package/dist/src/release-attestation.js +0 -533
  63. package/dist/src/release-preflight.js +0 -510
  64. package/dist/src/repair-progress.js +0 -262
  65. package/dist/src/repository-init-process.js +0 -173
  66. package/dist/src/repository-management.js +0 -1231
  67. package/dist/src/response-budget.js +0 -194
  68. package/dist/src/server.js +0 -73
  69. package/dist/src/structural-fast-path.js +0 -338
  70. package/dist/src/structural-snapshot.js +0 -33
  71. package/dist/src/system-config.js +0 -615
  72. package/dist/src/terminal-help.js +0 -83
  73. package/dist/src/tools/knodin-tools.js +0 -1529
  74. package/dist/src/update-ceremony.js +0 -158
  75. package/dist/src/update-policy.js +0 -944
  76. package/dist/src/update-trust.js +0 -503
  77. package/dist/src/version.js +0 -13
  78. package/dist/src/visualization.js +0 -162
  79. package/dist/src/wait-for-fresh.js +0 -98
  80. package/dist/src/worktree-lifecycle.js +0 -231
  81. package/docs/CONTAINED-EXECUTION.md +0 -77
  82. package/docs/DIAGNOSTICS.md +0 -45
  83. package/docs/GIT-HISTORY-REVIEW.md +0 -39
  84. package/docs/PROGRESSIVE-EVIDENCE.md +0 -37
  85. package/docs/PT-ACCESS-RECOMMENDATION.md +0 -91
  86. package/docs/RELEASE-0.3-EVIDENCE.md +0 -73
  87. package/docs/SCIP-IMPORT.md +0 -57
  88. package/docs/SIGNED-UPDATES.md +0 -151
  89. package/docs/TELEMETRY.md +0 -46
  90. package/docs/assets/knodin-favicon.svg +0 -4
  91. package/docs/releases/0.3.0.md +0 -46
  92. package/docs/releases/0.4.0.md +0 -68
  93. package/docs/releases/0.4.1.md +0 -28
  94. package/docs/releases/0.4.2.md +0 -27
  95. package/docs/releases/0.4.3.md +0 -23
  96. package/docs/releases/0.5.0.md +0 -29
  97. package/docs/releases/0.5.1.md +0 -17
  98. package/docs/releases/0.6.0.md +0 -18
  99. package/docs/releases/0.7.0.md +0 -24
  100. package/docs/releases/0.7.1.md +0 -21
  101. package/docs/releases/0.7.2.md +0 -21
  102. package/docs/releases/0.7.3.md +0 -23
  103. package/docs/releases/0.7.4.md +0 -17
  104. package/schemas/release-attestation-v1.schema.json +0 -210
@@ -0,0 +1,654 @@
1
+ import{a as Tr,b as Rr}from"./chunk-X6M4HUUE.js";import{a as $r,c as Ci}from"./chunk-YPRMY2LP.js";import Oi from"node:child_process";import it from"node:fs";import ge from"node:path";function Eb(t){if(t==="personal"||t==="team"||t==="cli-only")return t;throw new Error("knodin: --scope must be personal, team, or cli-only")}var Gt="knodin",_r="# knodin:start",Ar="# knodin:end",hu=`${_r}
2
+ [mcp_servers."${Gt}"]
3
+ command = "knodin"
4
+ args = ["serve"]
5
+ ${Ar}`;function Ii(t){return t instanceof Error?t.message:String(t)}function kn(t){try{return Oi.execFileSync("which",[t],{stdio:"ignore"}),!0}catch{return!1}}function Fr(){let t=[];return kn("claude")&&t.push("claude"),kn("codex")&&t.push("codex"),kn("gemini")&&t.push("gemini"),(kn("antigravity")||kn("agy"))&&t.push("antigravity"),t}function Lr(t){try{Oi.execFileSync(t.executable,t.args,{cwd:t.cwd,stdio:["ignore","ignore","pipe"]})}catch(e){if(t.executable!=="claude"||!t.args.includes("add"))throw e;Oi.execFileSync("claude",["mcp","get",Gt],{cwd:t.cwd,stdio:["ignore","ignore","pipe"]})}}function gu(t){let e=t.run??Lr,n=[],s=[],i=[];for(let o of t.detected){if(o!=="claude")continue;let r=t.remove?{executable:"claude",args:["mcp","remove",Gt,"--scope","local"]}:{executable:"claude",args:["mcp","add",Gt,"--scope","local","--","knodin","serve"]};try{e(r),(t.remove?s:n).push(o)}catch(c){t.remove?s.push(o):i.push({agent:o,message:Ii(c)})}}return{configured:n,removed:s,failed:i,projectFiles:[]}}function yu(t){try{let e=JSON.parse(it.readFileSync(t,"utf-8"));if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("expected a JSON object");return e}catch(e){if(e.code==="ENOENT")return{};throw new Error(`${t}: ${Ii(e)}`)}}function vn(t,e){let n=ge.relative(t,e);if(n.startsWith("..")||ge.isAbsolute(n))throw new Error(`${e}: agent configuration must stay inside the repository`);let s=t;for(let i of n.split(ge.sep)){s=ge.join(s,i);try{if(it.lstatSync(s).isSymbolicLink())throw new Error(`${e}: refusing to follow a symbolic link`)}catch(o){if(o.code==="ENOENT")break;throw o}}}function bu(t){return`${JSON.stringify(t,null," ").replace(/"args": \[\n(\t+)"serve"\n\t+\]/g,'"args": ["serve"]')}
6
+ `}function us(t,e){let n=yu(t),s=n.mcpServers,i=typeof s=="object"&&s!==null&&!Array.isArray(s)?{...s}:{};return e?delete i[Gt]:i[Gt]={command:"knodin",args:["serve"]},Object.keys(i).length>0?n.mcpServers=i:delete n.mcpServers,e&&Object.keys(n).length===0?(it.rmSync(t,{force:!0}),!1):(it.mkdirSync(ge.dirname(t),{recursive:!0}),it.writeFileSync(t,bu(n),"utf-8"),!0)}function wu(t,e){let n="";try{n=it.readFileSync(t,"utf-8")}catch(r){if(r.code!=="ENOENT")throw r}function s(r,c,a){let l=r.indexOf(c),u=r.indexOf(a);return l>=0&&u>=l?`${r.slice(0,l)}${r.slice(u+a.length)}`.trim():r.trim()}let i=s(n,_r,Ar),o=e?i:[i,hu].filter(Boolean).join(`
7
+
8
+ `);return o?(it.mkdirSync(ge.dirname(t),{recursive:!0}),it.writeFileSync(t,`${o}
9
+ `,"utf-8"),!0):(it.rmSync(t,{force:!0}),!1)}function Mi(t){let e=ge.resolve(t.repo),n=t.scope==="cli-only",s=t.scope==="team"?["claude","codex","gemini","antigravity"]:t.agents,i=t.scope==="team"?{configured:[],removed:[],failed:[],projectFiles:[]}:gu({detected:s,remove:n,run:t.run??(l=>Lr({...l,cwd:e}))}),o=[...i.configured],r=[...i.removed],c=[...i.failed],a=[];for(let l of s)try{let u=null,f=!1;l==="claude"&&t.scope==="team"?(u=".mcp.json",vn(e,ge.join(e,u)),f=us(ge.join(e,u),!1)):l==="claude"?(u=".mcp.json",vn(e,ge.join(e,u)),f=us(ge.join(e,u),!0)):l==="codex"?(u=".codex/config.toml",vn(e,ge.join(e,u)),f=wu(ge.join(e,u),n)):l==="gemini"?(u=".gemini/settings.json",vn(e,ge.join(e,u)),f=us(ge.join(e,u),n)):l==="antigravity"&&(u=".agents/mcp_config.json",vn(e,ge.join(e,u)),f=us(ge.join(e,u),n)),u&&f&&a.push(u),l==="claude"&&t.scope==="team"&&!o.includes(l)&&o.push(l),l!=="claude"&&!n&&!o.includes(l)&&o.push(l),n&&!r.includes(l)&&r.push(l)}catch(u){c.push({agent:l,message:Ii(u)})}return{configured:o,removed:r,failed:c,projectFiles:a}}import Or from"node:fs";import{createRequire as Su}from"node:module";import He from"node:path";var Di=new Set(["--identity","--file","--kind","--to-identity","--to-file","--to-kind","--bytes","--tokens","--items","--impact-mode","--direction","--depth","--relations","--min-confidence","--limit"]),Eu=new Set(["--exclude-tests","--data-flow","--json"]),Pi=t=>{try{return Or.statSync(t).isDirectory()}catch{return!1}},Nr=new Set(["--import","--loader","--experimental-loader","--require","-r"]);function Cr(t,e,n){return He.isAbsolute(t)||/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)?t:t.startsWith(".")?He.resolve(e,t):n(t,e)}function Rb(t,e=(n,s)=>Su(He.join(s,"package.json")).resolve(n)){let n=t.argv[1];if(!n)throw new Error("knodin: CLI entry path is unavailable");let s=t.cwd(),i=[];for(let o=0;o<t.execArgv.length;o++){let r=t.execArgv[o];if(Nr.has(r)){let a=t.execArgv[o+1];if(!a)throw new Error(`knodin: ${r} requires a runtime module`);i.push(r,Cr(a,s,e)),o++;continue}let c=[...Nr].find(a=>r.startsWith(`${a}=`));if(c){let a=r.slice(c.length+1);if(!a)throw new Error(`knodin: ${c} requires a runtime module`);i.push(`${c}=${Cr(a,s,e)}`);continue}i.push(r)}return[He.resolve(s,t.execPath),...i,He.resolve(s,n)]}function $b(t){let e=[],n=[],s,i=!1;for(let o=0;o<t.length;o++){let r=t[o];r==="--repo"?(s=t[o+1]??"",o++):r.startsWith("--repo=")?s=r.slice(7):!i&&Di.has(r)?(n.push(r),t[o+1]!==void 0&&n.push(t[++o])):!i&&Eu.has(r)?n.push(r):(e.push(r),i=!0)}return e.push(...n),{repoFlag:s,rest:e}}function _b(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n];if(s.startsWith("--")){!s.includes("=")&&Di.has(s)&&n++;continue}e.push(s)}return e}function ku(t,e){if(t===void 0)return{ok:!0,repo:e};if(t==="")return{ok:!1,error:"knodin: --repo requires a <path>"};let n=He.resolve(e,t);return Or.existsSync(n)?Pi(n)?{ok:!0,repo:n}:{ok:!1,error:`knodin: --repo path is not a directory: ${n}`}:{ok:!1,error:`knodin: --repo path does not exist: ${n}`}}function Ab(t,e,n){if(t===void 0&&e.length===1){let a=He.resolve(n,e[0]);if(Pi(a))return{ok:!0,repo:a,files:void 0}}let s=ku(t,n);if(!s.ok)return s;let i=s.repo;if(e.length===0)return{ok:!0,repo:i,files:void 0};let o=[],r=[],c=[];for(let a of e){let l=He.resolve(i,a),u=He.relative(i,l);if(u===""||u===".."||u.startsWith(`..${He.sep}`)||He.isAbsolute(u)){r.push(a);continue}if(Pi(l)){o.push(a);continue}c.push(a)}if(r.length>0||o.length>0){let a=[];if(r.length>0&&a.push(`outside repo (${r.join(", ")})`),o.length>0){let l=t===void 0?"use --repo to index a whole repo":"pass files, not directories, alongside --repo";a.push(`directories \u2014 ${l} (${o.join(", ")})`)}return{ok:!1,error:`knodin index: refusing to index against ${i}; rejected ${a.join("; ")}`}}return{ok:!0,repo:i,files:c}}function Fb(t,e){return!t||t.length===0?{ok:!1,error:`knodin index: indexed 0 files in ${e} (nothing matched)`}:{ok:!0}}function Lb(t){let e=a=>{let l=t.indexOf(a);if(l<0)return;let u=t[l+1];if(!u||u.startsWith("--"))throw new Error(`knodin review: ${a} requires a value`);return u},n=e("--scope");if(n&&!["unstaged","staged","all","compare"].includes(n))throw new Error(`invalid review scope: ${n}`);let i=new Set([...Di,"--scope","--from","--to","--files","--scip"]),o=t.filter((a,l)=>a.startsWith("--")?!1:l===0||!i.has(t[l-1])),r=e("--files"),c=r?.split(",").map(a=>a.trim()).filter(Boolean);if(r!==void 0&&c?.length===0)throw new Error("knodin review: --files requires at least one repo-relative path");return{base:o.find(a=>a!=="minimal")??"HEAD~1",detailLevel:o.includes("minimal")?"minimal":"standard",options:{scope:n,from:e("--from"),to:e("--to"),files:c}}}var ds=null;function vu(){try{let t=process.resourceUsage().maxRSS;return Number.isFinite(t)&&t>=0?t*1024:void 0}catch{return}}function ji(t,e){let n=ds;if(!n)return;n.phases[t]+=Math.max(0,performance.now()-e);let s=vu();s!==void 0&&(n.peakRssBytes=Math.max(n.peakRssBytes??0,s))}function Vt(t){if(!ds)return()=>{};let e=performance.now(),n=!1;return()=>{n||(n=!0,ji(t,e))}}async function Ue(t,e){if(!ds)return e();let n=performance.now();try{return await e()}finally{ji(t,n)}}function re(t,e){if(!ds)return e();let n=performance.now();try{return e()}finally{ji(t,n)}}function xu(t){let e=t.toLowerCase();return/\b(bug|review|diff|pr|pull request|regression|risk|approve|merge)\b/.test(e)?"review":/\b(batch outline|file outline|outline files?|project overview|directory overview)\b/.test(e)?"query":/\b(how does|how do|architecture|architectural|structure|structured|design|subsystem|boundaries|overview)\b/.test(e)?"map":/^[A-Za-z_][A-Za-z0-9_]*$/.test(t.trim())?"explain":"search"}function Ir(t){let e=t.toLowerCase();if(/\bbatch outline\b/.test(e))return"batch_outline";if(/\b(project|directory) overview\b/.test(e))return"project_overview";if(/\bfile outline\b|\boutline (?:the )?file\b/.test(e))return"file_summary"}async function Ib(t,e,n,s,i){return Ue("context_composition",async()=>{let r=await t.map(n,"standard"),c=i===void 0||i.length>0,[a,l,u]=await Promise.all([t.query("stats","",n),t.query("flows","",n,void 0,5),c?t.review(s??"HEAD~1",n,"minimal"):Promise.resolve(void 0)]),f;return u&&u.changedSymbolCount>0&&(f=u.riskScore),{repoPath:n,task:e,stats:a.totals,communities:[...r.communities].sort((m,d)=>d.size-m.size).slice(0,5).map(m=>({name:m.name,size:m.size})),hubs:[...r.hubs].sort((m,d)=>d.degree-m.degree).slice(0,5).map(m=>({symbol:m.symbol,degree:m.degree})),flows:l.results.slice(0,5).map(m=>({symbol:m.symbol,criticality:m.criticality})),...f!==void 0?{riskScore:f}:{},suggestedOperation:xu(e),...Ir(e)?{suggestedQueryPattern:Ir(e)}:{},suggestionNote:"Heuristic from keywords in `task`; a hint only \u2014 any operation can be called directly regardless."}})}import{execFileSync as Tu}from"node:child_process";import Ce from"node:fs";import Ne from"node:path";import{RE2 as Ru}from"re2-wasm";var zi=[".git/**",".knodin/**","node_modules/**","dist/**","build/**"],$u=256,xn=new Map;function Qe(t){return t.replaceAll("\\","/").replace(/^\.\//,"")}function Bi(t){let e=Qe(t),n=xn.get(e);if(n)return n;let s="^";for(let o=0;o<e.length;o++){let r=e[o];r==="*"?e[o+1]==="*"?(o++,e[o+1]==="/"?(o++,s+="(?:.*/)?"):s+=".*"):s+="[^/]*":r==="?"?s+="[^/]":s+=r.replace(/[\\^$+?.()|{}[\]]/g,"\\$&")}let i=new RegExp(`${s}$`);if(xn.size>=$u){let o=xn.keys().next().value;o!==void 0&&xn.delete(o)}return xn.set(e,i),i}function Mr(t,e){return e.some(n=>Bi(Qe(n)).test(t))}function Pr(t){return t.map(e=>Bi(Qe(e)))}function Dr(t,e){return e.some(n=>n.test(t))}function zr(t,e=t,n=[]){for(let s of Ce.readdirSync(e,{withFileTypes:!0})){let i=Ne.join(e,s.name),o=Qe(Ne.relative(t,i));Mr(o,zi)||Mr(`${o}/`,zi)||(s.isDirectory()?zr(t,i,n):s.isFile()&&n.push(o))}return n}function _u(t,e){for(let{pattern:n,policy:s}of e)if(n.test(t))return s;return"full"}function Br(t,e=!1){return t.split(/\r?\n/).map((n,s)=>({line:n,index:s})).filter(({line:n})=>/^\s*(export\s+)?(async\s+)?(class|interface|type|enum|function|const|let|var|def|module|namespace)\b/.test(n)||/^\s*(import|export)\b/.test(n)).map(({line:n,index:s})=>e?`${s+1}: ${n}`:n).join(`
10
+ `)}function Au(t,e=!1){let n=t.split(/\r?\n/),s=Br(t,e);return[`[summary: ${n.length} lines, ${Buffer.byteLength(t)} bytes]`,s].filter(Boolean).join(`
11
+ `)}function Fu(t){return t.split(/\r?\n/).map((e,n)=>`${n+1}: ${e}`).join(`
12
+ `)}function jr(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function Tn(t,e,n,s){if(t==="json")return JSON.stringify({tree:n,files:e,git:s},null,2);if(t==="xml"){let r=n?`<tree>${n.map(l=>`<path>${jr(l)}</path>`).join("")}</tree>`:"",c=e.map(l=>`<file path="${jr(l.path)}" policy="${l.policy}"><![CDATA[${l.content.replaceAll("]]>","]]]]><![CDATA[>")}]]></file>`).join(""),a=s?`<git>${s.diff===void 0?"":`<diff><![CDATA[${s.diff.replaceAll("]]>","]]]]><![CDATA[>")}]]></diff>`}${s.log===void 0?"":`<log><![CDATA[${s.log.replaceAll("]]>","]]]]><![CDATA[>")}]]></log>`}</git>`:"";return`<context>${r}<files>${c}</files>${a}</context>`}let i=(r,c="")=>{let a=Math.max(0,...[...r.matchAll(/`+/g)].map(u=>u[0].length)),l="`".repeat(Math.max(3,a+1));return[`${l}${c}`,r,l]},o=["# knodin context export"];n&&o.push("## Tree",...i(n.join(`
13
+ `),"text"));for(let r of e)o.push(`## ${r.path} (${r.policy})`,...i(r.content));return s?.diff!==void 0&&o.push("## Git diff",...i(s.diff,"diff")),s?.log!==void 0&&o.push("## Git log",...i(s.log,"text")),o.join(`
14
+ `)}function Lu(t,e,n){if(!n)return Buffer.byteLength(Tn(t,[e]))-Buffer.byteLength(Tn(t,[]));let s={path:"",policy:"full",content:""};return Buffer.byteLength(Tn(t,[s,e]))-Buffer.byteLength(Tn(t,[s]))}function Nu(t,e){if(!e)return;let n=i=>Tu("git",i,{cwd:t,encoding:"utf8",maxBuffer:4*1024*1024}),s={};if(e.diffScope){let i=r=>{let c=[...r].some(a=>{let l=a.charCodeAt(0);return l<32||l===127});if(!r||r.startsWith("-")||c)throw new Error(`knodin pack: invalid git revision: ${r}`);return r},o=e.diffScope==="unstaged"?["diff","--"]:e.diffScope==="staged"?["diff","--cached","--"]:e.diffScope==="compare"?["diff",i(e.from??"HEAD~1"),i(e.to??"HEAD"),"--"]:["diff",i(e.from??"HEAD"),"--"];s.diff=n(o)}return e.log!==void 0&&(s.log=n(["log",`-${Math.max(0,Math.min(100,Math.floor(e.log)))}`,"--oneline"])),s}function Cu(t,e){let n=Ne.resolve(t,e);if(n!==t&&!n.startsWith(`${t}${Ne.sep}`))throw new Error("knodin pack: outputPath must stay inside the repository");if(Ce.existsSync(n)){let o=Ce.realpathSync(n);if(o!==t&&!o.startsWith(`${t}${Ne.sep}`))throw new Error("knodin pack: outputPath may not follow a symlink outside the repository")}let s=Ne.dirname(n);for(;!Ce.existsSync(s)&&s!==t;)s=Ne.dirname(s);let i=Ce.realpathSync(s);if(i!==t&&!i.startsWith(`${t}${Ne.sep}`))throw new Error("knodin pack: outputPath may not traverse a symlink outside the repository");return n}function Hb(t,e={}){let n=Ce.realpathSync(t),s=e.format??"markdown";if(!["markdown","json","xml"].includes(s))throw new Error("knodin pack: format must be markdown, json, or xml");if(e.byteBudget!==void 0&&(!Number.isFinite(e.byteBudget)||e.byteBudget<256))throw new Error("knodin pack: byteBudget must be at least 256");if(e.tokenBudget!==void 0&&(!Number.isFinite(e.tokenBudget)||e.tokenBudget<64))throw new Error("knodin pack: tokenBudget must be at least 64");if(e.git?.diffScope!==void 0&&!["unstaged","staged","all","compare"].includes(e.git.diffScope))throw new Error("knodin pack: invalid git diff scope");if(e.git?.log!==void 0&&(!Number.isInteger(e.git.log)||e.git.log<0||e.git.log>100))throw new Error("knodin pack: git log must be an integer from 0 to 100");if(Object.values(e.policies??{}).some(p=>!["full","summary","structure-only"].includes(p)))throw new Error("knodin pack: invalid file policy");let i=Math.floor(e.byteBudget??65536),o=Math.floor(e.tokenBudget??16384),r=Math.min(i,o*4),c=e.include?.length?e.include:["**"],a=[...zi,...e.exclude??[]],l=Pr(c),u=Pr(a),f=e.policies??{},m=Object.keys(f).sort().map(p=>({pattern:Bi(Qe(p)),policy:f[p]})),d=new Set([...e.alreadyPresent??[],...e.chatFiles??[]].map(Qe));e.outputPath&&d.add(Qe(e.outputPath));let y=re("pack_walk",()=>zr(n)).filter(p=>Dr(p,l)&&!Dr(p,u)&&!d.has(p)).sort(),g=e.includeTree?[...y]:void 0,h=Nu(n,e.git),w=[],k=()=>re("pack_serialize",()=>Tn(s,w,g,h)),_=k();Buffer.byteLength(_)>r&&(h=void 0,_=k()),Buffer.byteLength(_)>r&&(g=void 0,_=k());let R=Buffer.byteLength(_);for(let p of y){let F=_u(p,m),L=Ce.readFileSync(Ne.join(n,p),"utf8");F==="summary"?L=Au(L,e.lineNumbers):F==="structure-only"?L=Br(L,e.lineNumbers):e.lineNumbers&&(L=Fu(L));let T={path:p,policy:F,content:L},x=re("pack_serialize",()=>Lu(s,T,w.length>0));R+x>r||(w.push(T),R+=x)}_=k();let v=Buffer.byteLength(_),S=e.outputPath?Cu(n,e.outputPath):void 0,E={format:s,artifact:_,files:w.map(({path:p,policy:F})=>({path:p,policy:F})),telemetry:{byteLimit:i,tokenLimit:o,serializedBytes:v,responseBytes:0,estimatedTokens:Math.ceil(v/4),tokenizer:"estimate:deterministic-utf8-bytes-divided-by-4",includedFiles:w.length,candidateFiles:y.length,truncated:w.length<y.length},...S?{outputPath:Qe(Ne.relative(n,S))}:{}},$=()=>{for(let p=0;p<4;p++){let F=Buffer.byteLength(JSON.stringify(E));if(F===E.telemetry.responseBytes)break;E.telemetry.responseBytes=F}};for($();E.telemetry.responseBytes>r&&w.length>0;)w.pop(),E.files.pop(),E.artifact=k(),E.telemetry.serializedBytes=Buffer.byteLength(E.artifact),E.telemetry.estimatedTokens=Math.ceil(E.telemetry.serializedBytes/4),E.telemetry.includedFiles=w.length,E.telemetry.truncated=!0,$();if(E.telemetry.responseBytes>r)throw new Error("knodin pack: budget is too small for the requested format and telemetry");return S&&(Ce.mkdirSync(Ne.dirname(S),{recursive:!0}),Ce.writeFileSync(S,E.artifact)),E}function Ou(t,e){let n=Ce.realpathSync(t),s=Ne.resolve(n,e);if(s!==n&&!s.startsWith(`${n}${Ne.sep}`))throw new Error("knodin pack: artifactPath must stay inside the repository");let i=Ce.realpathSync(s);if(i!==n&&!i.startsWith(`${n}${Ne.sep}`))throw new Error("knodin pack: artifactPath may not follow a symlink outside the repository");let o=Ce.statSync(i);if(!o.isFile()||o.size>16*1024*1024)throw new Error("knodin pack: artifactPath must be a packed file no larger than 16 MiB");return i}var Iu=2,Mu=4*1024*1024,pt=new Map;function Hr(t,e){let n=Ou(t,e),s=Ce.statSync(n),i=pt.get(n);if(i&&i.mtimeMs===s.mtimeMs&&i.size===s.size)return pt.delete(n),pt.set(n,i),i.lines;i&&pt.delete(n);let o=Ce.readFileSync(n,"utf8").split(/\r?\n/);if(s.size<=Mu){for(;pt.size>=Iu;){let r=pt.keys().next().value;if(r===void 0)break;pt.delete(r)}pt.set(n,{mtimeMs:s.mtimeMs,size:s.size,lines:o})}return o}function Pu(t,e){if(Buffer.byteLength(t)<=e)return t;let n=0,s=t.length;for(;n<s;){let i=Math.ceil((n+s)/2);Buffer.byteLength(t.slice(0,i))<=e?n=i:s=i-1}return t.slice(0,n)}function Ub(t,e,n=1,s=n+199,i=16384){if(!Number.isFinite(i)||!Number.isInteger(i)||i<256)throw new Error("knodin pack read: byteBudget must be an integer >= 256");if(!Number.isInteger(n)||!Number.isInteger(s)||n<1||s<n||s-n>999)throw new Error("knodin pack read: invalid or unbounded line range");let o=re("artifact_read",()=>Hr(t,e).slice(n-1,s)),r=o.join(`
15
+ `),c=Math.max(256,Math.min(65536,Math.floor(i)));return r=Pu(r,c),{artifactPath:Qe(e),startLine:n,endLine:n+r.split(/\r?\n/).length-1,content:r,truncated:o.join(`
16
+ `)!==r}}function Wb(t,e,n,s="",i=100){if(!Number.isFinite(i)||!Number.isInteger(i)||i<1||i>1e3)throw new Error("knodin pack grep: limit must be an integer from 1 to 1000");if(n.length===0||n.length>1e3||!/^[gimsuy]*$/.test(s))throw new Error("knodin pack grep: invalid regex or flags");let o;try{let c=s.replace("g","").includes("u")?s.replace("g",""):`${s.replace("g","")}u`;o=new Ru(n,c)}catch{throw new Error("knodin pack grep: invalid or unsupported linear-time regex")}let r=[];return re("artifact_grep",()=>{for(let[c,a]of Hr(t,e).entries())if(o.lastIndex=0,o.test(a)&&r.push({line:c+1,text:a}),r.length>=Math.max(1,Math.min(1e3,Math.floor(i))))break}),{artifactPath:Qe(e),pattern:n,flags:s,matches:r,truncated:r.length>=i}}import Rn from"node:crypto";import oe from"node:fs";import Du from"node:os";import ot from"node:path";import Wr from"node:zlib";var fs=".knodin/diagnostics/config.json",Ui=".knodin/diagnostics/events.jsonl",ju=".knodin/diagnostics/events.lock",qr=14,Hi=365,Gr=500,zu=64*1024,Bu=20*1024*1024,Hu=2*1024*1024,Uu=new Set(["init","configure","index","doctor","status","wait","repair","serve","context","explain","review","map","search","query","rename","wiki","visualize","pack","compress","prs","worktrees","telemetry","diagnostics","system","repos","repositories","update","docs","unknown"]);function et(t,e,n){let s=oe.realpathSync(t),i=ot.resolve(s,e);if(i!==s&&!i.startsWith(`${s}${ot.sep}`))throw new Error(`knodin diagnostics ${n}: path must stay inside the repository`);let o=s;for(let r of ot.relative(s,i).split(ot.sep).filter(Boolean)){o=ot.join(o,r);try{if(oe.lstatSync(o).isSymbolicLink())throw new Error(`knodin diagnostics ${n}: refusing symlinked path`)}catch(c){if(c.code==="ENOENT")break;throw c}}return{repo:s,target:i}}function ms(t,e){oe.mkdirSync(ot.dirname(t),{recursive:!0,mode:448});let n=`${t}.${process.pid}.${Date.now()}.${Rn.randomBytes(6).toString("hex")}.tmp`;oe.writeFileSync(n,e,{mode:384,flag:"wx"}),oe.renameSync(n,t)}function ps(t,e){let{target:n}=et(t,ju,"record");oe.mkdirSync(ot.dirname(n),{recursive:!0,mode:448});for(let s=0;;s++)try{oe.mkdirSync(n,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-oe.statSync(n).mtimeMs>3e4){oe.rmdirSync(n);continue}}catch(o){if(o.code==="ENOENT")continue;throw o}if(s>=100)throw new Error("knodin diagnostics record: journal is busy");Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{return e()}finally{try{oe.rmdirSync(n)}catch{}}}function Wi(t){if(!Number.isInteger(t)||t<1||t>Hi)throw new Error(`knodin diagnostics: retention days must be an integer from 1 to ${Hi}`);return t}function $n(t){let{target:e}=et(t,fs,"status");if(!oe.existsSync(e))return null;try{let n=JSON.parse(oe.readFileSync(e,"utf8"));return n.schemaVersion!==1||n.enabled!==!0?null:(Wi(n.retentionDays),(!Number.isInteger(n.generation)||n.generation<1)&&(n.generation=1),(typeof n.sessionId!="string"||!/^[a-f0-9]{32}$/.test(n.sessionId))&&(n.sessionId=Rn.createHash("sha256").update(n.enabledAt).digest("hex").slice(0,32)),n)}catch{return null}}function Ur(t,e){return t&&/^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$/.test(t)?t:e}function Wu(t){let e=t?.code;return typeof e=="string"&&/^(?:E[A-Z0-9]+|ERR_[A-Z0-9_]+|SQLITE_[A-Z0-9_]+|KNODIN_[A-Z0-9_]+)$/.test(e)?e:null}function Vr(t,e){let n=t,s=0,i=(o,r)=>{n=n.replace(o,()=>(s++,r))};for(let o of[e,Du.homedir()].filter(Boolean).sort((r,c)=>c.length-r.length))i(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"<path>");return i(/\b(?:ghp|github_pat|sk|xox[baprs])-[-A-Za-z0-9_]{10,}\b/g,"<secret>"),i(/\b(?:password|passwd|token|secret|api[_-]?key|authorization)\s*[=:]\s*[^\s,;]+/gi,"$1=<secret>"),i(/\b[A-Z]:\\(?:[^\s<>:"|?*]+\\)*[^\s<>:"|?*]*/g,"<path>"),i(/(?:^|[\s('"`])\/(?:[^\s)'"`]+\/)*[^\s)'"`]*/g,"<path>"),i(/\b(?:[A-Za-z0-9_.-]+\/)+(?:[A-Za-z0-9_.-]+\.[A-Za-z0-9]{1,12})\b/g,"<path>"),i(/\b[A-Za-z0-9_.+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,"<email>"),{value:n.slice(0,2e3),redactions:s}}function qu(t,e){return(t.stack??"").split(/\r?\n/).slice(1,9).map(n=>`at ${n.includes(e)?"<repository>":"<runtime>"}`)}function Kt(t,e,n){if(typeof t=="string"){let s=Vr(t,e);return n.redactions+=s.redactions,s.value}if(Array.isArray(t))return t.slice(0,500).map(s=>Kt(s,e,n));if(t&&typeof t=="object"){let s={};for(let[i,o]of Object.entries(t).slice(0,500)){let r=/[\\/]|\.[A-Za-z0-9]{1,12}$/.test(i)?"<path-key>":i;r!==i&&n.redactions++,/^(?:source|content|query|command|arguments?|env(?:ironment)?|remote)$/i.test(i)?(s[r]="<omitted>",n.redactions++):s[r]=Kt(o,e,n)}return s}return t}function hs(t,e,n){let{target:s}=et(t,Ui,"read");if(!oe.existsSync(s))return[];if(oe.statSync(s).size>Hu)throw new Error("knodin diagnostics read: journal exceeds the 2 MiB safety limit");let i=Math.max(Date.now()-Wi(e)*864e5,n?.getTime()??Number.NEGATIVE_INFINITY);return oe.readFileSync(s,"utf8").split(/\r?\n/).filter(Boolean).flatMap(o=>{try{let r=JSON.parse(o);return r.schemaVersion===1&&Date.parse(r.at)>=i?[r]:[]}catch{return[]}}).slice(-Gr)}function Jb(t,e=qr){let{repo:n,target:s}=et(t,fs,"enable");return ps(n,()=>{let i=$n(n),o={schemaVersion:1,enabled:!0,retentionDays:Wi(e),enabledAt:new Date().toISOString(),generation:(i?.generation??0)+1,sessionId:Rn.randomBytes(16).toString("hex")};ms(s,`${JSON.stringify(o,null,2)}
17
+ `)}),{...qi(n),message:"Local diagnostics enabled; nothing is uploaded."}}function Yb(t){let{repo:e,target:n}=et(t,fs,"disable");return ps(e,()=>{oe.existsSync(n)&&oe.unlinkSync(n)}),{...qi(e),message:"Local diagnostics disabled; retained events were not deleted."}}function qi(t){let e=$n(t),n=e?.retentionDays??qr,s=[],i={status:"healthy",issue:null};try{s=hs(t,n)}catch(o){i={status:"unavailable",issue:o instanceof Error?o.message:"diagnostic journal is unavailable"}}return{schemaVersion:1,enabled:e!==null,localOnly:!0,uploaded:!1,retentionDays:n,records:s.length,oldestAt:s[0]?.at??null,newestAt:s.at(-1)?.at??null,journal:i}}function Qb(t,e){try{let n=oe.realpathSync(t),s=$n(n);return s?ps(n,()=>{let i=$n(n);if(!i)return{recorded:!1,reason:"disabled"};if(i.sessionId!==s.sessionId||i.generation!==s.generation)return{recorded:!1,reason:"state-changed"};let o=e.error instanceof Error?e.error:new Error(String(e.error)),r=Vr(o.message,n).value,c={schemaVersion:1,at:new Date().toISOString(),correlationId:Rn.randomBytes(8).toString("hex"),surface:e.surface,operation:Uu.has(e.operation)?e.operation:"unknown",phase:Ur(e.phase,"operation"),error:{name:Ur(o.name,"Error"),code:Wu(e.error),messageFingerprint:Rn.createHash("sha256").update(r).digest("hex").slice(0,16),stack:qu(o,n)}},a=[...hs(n,i.retentionDays),c].slice(-Gr),{target:l}=et(n,Ui,"record");return ms(l,`${a.map(u=>JSON.stringify(u)).join(`
18
+ `)}
19
+ `),{recorded:!0,correlationId:c.correlationId}}):{recorded:!1,reason:"disabled"}}catch{return{recorded:!1,reason:"unavailable"}}}function ew(t){let{repo:e,target:n}=et(t,Ui,"clear");return ps(e,()=>{if(!oe.existsSync(n))return{removed:!1,records:0,bytes:0};let s=null;try{s=hs(e,Hi).length}catch{}let i=oe.statSync(n).size;oe.unlinkSync(n);let o=$n(e);return o&&ms(et(e,fs,"clear").target,`${JSON.stringify({...o,generation:o.generation+1},null,2)}
20
+ `),{removed:!0,records:s,bytes:i}})}function Gu(){return`.knodin/diagnostics/knodin-diagnostics-${new Date().toISOString().replace(/[:.]/g,"-")}.json.gz`}function Vu(t,e){let n=ot.join(t,".knodin","indexer.log");if(!oe.existsSync(n)||oe.lstatSync(n).isSymbolicLink())return[];let s=oe.statSync(n).size,i=oe.openSync(n,"r");try{let o=Math.min(s,zu),r=Buffer.alloc(o);return oe.readSync(i,r,0,o,Math.max(0,s-o)),r.toString("utf8").split(/\r?\n/).filter(Boolean).slice(-200).map(c=>Kt(c,t,e))}finally{oe.closeSync(i)}}function tw(t,e={}){let{repo:n,target:s}=et(t,e.outputPath??Gu(),"collect");if(oe.existsSync(s))throw new Error("knodin diagnostics collect: refusing to overwrite an existing bundle");let i=e.sinceHours??24;if(!Number.isFinite(i)||i<=0||i>24*365)throw new Error("knodin diagnostics collect: --since must be from 1h through 8760h");let o={redactions:0},r=qi(n),c={manifest:{schemaVersion:1,generatedAt:new Date().toISOString(),privacy:"redacted-local-only",localOnly:!0,uploaded:!1,redactions:0,omissions:["source","queries-and-arguments","environment-values","git-remotes-diffs-and-messages","raw-paths"]},runtime:{...e.knodinVersion?{knodinVersion:e.knodinVersion}:{},node:process.version,platform:process.platform,arch:process.arch},diagnostics:r,diagnosticEvents:hs(n,r.retentionDays,new Date(Date.now()-i*36e5)),telemetry:Kt(e.telemetry??[],n,o),doctor:Kt(e.doctor??null,n,o),graph:Kt(e.graph??null,n,o),lifecycleLog:Vu(n,o)};return c.manifest.redactions=o.redactions,ms(s,Wr.gzipSync(`${JSON.stringify(c,null,2)}
21
+ `,{level:9})),{schemaVersion:1,outputPath:ot.relative(n,s),format:"gzip-json",localOnly:!0,uploaded:!1,bytes:oe.statSync(s).size,records:c.diagnosticEvents.length,redactions:c.manifest.redactions,message:"Bundle created locally. Run `knodin diagnostics inspect <bundle>` before sharing it."}}function nw(t,e){let{target:n}=et(t,e,"inspect");if(!oe.existsSync(n))throw new Error("knodin diagnostics inspect: bundle does not exist");if(oe.statSync(n).size>10*1024*1024)throw new Error("knodin diagnostics inspect: bundle exceeds the 10 MiB safety limit");let s;try{s=JSON.parse(Wr.gunzipSync(oe.readFileSync(n),{maxOutputLength:Bu}).toString("utf8"))}catch{throw new Error("knodin diagnostics inspect: invalid gzip JSON bundle")}if(s.manifest?.schemaVersion!==1||s.manifest.privacy!=="redacted-local-only")throw new Error("knodin diagnostics inspect: unsupported or unsafe bundle manifest");if(!Array.isArray(s.diagnosticEvents)||!Array.isArray(s.telemetry)||!Array.isArray(s.lifecycleLog))throw new Error("knodin diagnostics inspect: malformed bundle sections");return{manifest:s.manifest,runtime:s.runtime,diagnostics:s.diagnostics,sections:["diagnosticEvents","telemetry","doctor","graph","lifecycleLog"],counts:{diagnosticEvents:s.diagnosticEvents.length,telemetry:s.telemetry.length,lifecycleLogLines:s.lifecycleLog.length},bundle:s}}import Kr from"node:fs";import _n from"node:path";import{fileURLToPath as Ku}from"node:url";var Xr={quickstart:`# Quickstart Guide
22
+
23
+ knodin \u2014 source-evidenced local code intelligence with known bounds. It builds a semantic and syntactic knowledge graph of your repository and exposes five primary operations through its MCP tool gateway or CLI:
24
+
25
+ 1. **context**: Orient on a repository. Returns high-level statistics, key subsystems/hubs/flows, a heuristic next-operation recommendation, and a diff-based risk score if changes are detected.
26
+ 2. **explain**: Understand a specific symbol (function, class, or file). Returns edit-ready source code, inbound/outbound call paths, and blast radius (transitive callers).
27
+ 3. **review**: Analyze local modifications. Displays risk-scored changes, affected execution flows, and missing test coverage before you commit or create a PR.
28
+ 4. **map**: Visualize subsystem boundaries. Partitions the code into cohesive modular communities using Louvain community detection.
29
+ 5. **search**: Fuzzy semantic and keyword lookup to find symbols when you do not know their exact name.
30
+
31
+ ### Command Usage (CLI)
32
+ \`\`\`bash
33
+ knodin context "explore auth"
34
+ knodin explain login
35
+ knodin map
36
+ \`\`\``,"query-patterns":'# Structured Query Patterns\n\nThe `query` operation lets you ask precise, structured questions about your code using a variety of built-in graph patterns:\n\n- **callers_of <target>**: Who invokes this symbol (transitive/direct).\n- **callees_of <target>**: What other symbols does this symbol invoke.\n- **tests_for <target>**: Find test files that cover this symbol.\n- **file_summary <target>**: Lists all symbols defined in a file.\n- **shortest_path <from> <to>**: Find the call-graph chain connecting two symbols.\n- **impact <symbol>**: Directional, depth-bounded symbol reach with stable selectors, relation/confidence/test filters, edge evidence, and heuristic summaries. Use `impactMode: "file"` explicitly for a distinctly labeled changed-file blast radius.\n- **dead_code**: Surface exported or unexported symbols with zero references.\n- **large_functions / large_files**: Spot complex "god" functions and files exceeding size thresholds.\n- **traverse <symbol>**: Perform a bounded BFS neighborhood walk. Use `direction` (`upstream|downstream|both`), `relationKinds`, and optional `includeDataFlow`; every discovered hop carries its exact kind, direction, confidence, provenance, source line, and files. Call arguments are labeled heuristic source evidence, never runtime proof.\n- **knowledge_gaps**: Report repo-health weaknesses like thin communities (<3 symbols) and untested hubs/bridges.\n- **surprising_connections**: Score and rank coupling that crosses community, language, or test boundaries.\n- **suggested_questions**: prioritizes human-readable review prompts based on untested hotspots and high-surprise edges.\n- **architecture_overview**: Formats community cohesion and coupling plus independently selectable `architectureFacets`: packages, layers, boundaries, hotspots, entryPoints, and languages. `path` scopes every facet consistently.',federation:"# Cross-Repository Composition\n\nFederation is knodin's internal query-composition mechanism, not the primary\nuser-facing model. Use `knodin repos` for operational checkout management and\n`knodin system` with commit-ready `knodin.yaml` stable identities for\ncooperating components. Sibling directory placement and shared search matches\nnever establish system membership.\n\nLegacy `.knodin/federation.json` remains a compatibility input and is not\nsilently discarded. Migrate it to `knodin.yaml` plus personal XDG checkout\npaths. The `federated_repos` query remains available for inspecting the\nengine's currently composed repository paths; it does not prove those\nrepositories form one system.","rename-safety":`# Rename Safety and Refactoring
37
+
38
+ knodin provides an AST-backed, type-safe refactoring pipeline for renaming symbols.
39
+
40
+ ### Two-Step Pipeline
41
+ 1. **Dry-Run (default)**: Returns every edit site (definitions, references, imports) and generates a unified diff. Refuses to make changes if there's an ambiguity or conflict.
42
+ 2. **Apply (\`apply: true\` or \`--apply\`)**: Atomically writes line-scoped word-boundary edits to disk and triggers an automatic reindexing of touched files.
43
+
44
+ ### Safety Guards
45
+ The engine refuses to write to disk and rolls back any changes if:
46
+ - **Ambiguity**: The old symbol name resolves to more than one definition file.
47
+ - **Collision**: The new name already exists as a symbol in any of the edit-site files.
48
+ - **Out of Scope**: The edit targets files outside the repository.
49
+ - **Type Errors**: If verification is enabled (default), it verifies the workspace compiles successfully using \`tsc\` (or equivalent) after applying the edit, and automatically rolls back if compilation fails.`,"language-support":`# Language and Metadata Support
50
+
51
+ knodin is multi-language, not language-universal.
52
+
53
+ ### Native syntax
54
+ TypeScript (\`.ts/.tsx/.mts/.cts\`), JavaScript (\`.js/.jsx/.mjs/.cjs\`), Python, Java, C#, Salesforce Apex, SQL/PLSQL, Prisma, and XML-backed formats.
55
+
56
+ ### Domain-specific structure
57
+ Salesforce LWC, Aura, Visualforce, Experience Cloud, and selected Salesforce DX metadata/automations; Terraform/HCL; Dockerfiles; dbt manifests; and Workday Studio XML.
58
+
59
+ ### Imported graph
60
+ LSIF can import symbols and relationships produced by a compatible language server. This is not native parsing.
61
+
62
+ Go, Rust, PHP, Ruby, Kotlin, Swift, Perl, PowerShell, Bash, and MuleSoft/RAML are known native-parser gaps. Coverage differs by language, and static dead-code candidates must be corroborated when runtime or platform configuration can invoke code dynamically. Salesforce candidates should be checked against deployed-org and platform dependency data before deletion.`,troubleshooting:'# Troubleshooting and Recovery\n\n### Index health and surgical repair\n\nRun `knodin status` (or MCP `operation: "status"`) to inspect the local schema/model/version, file and symbol coverage, orphaned or missing records, and the last successful reconciliation. Its repair steps are actionable. Run `knodin repair` (or MCP `operation: "repair"`) to rebuild only missing/damaged rows and verify health; healthy indexed files are not deleted or rebuilt.\n\nThe MCP `telemetry` operation reads process-local metadata-only measurements: actual response bytes and `gpt-tokenizer@3.4.0:o200k_base` tokens, executed baselines where available, negative or positive savings, latency, RSS, schema cost, truncation, and detail mode. It never contains source or file paths and does not change existing operation response shapes. Telemetry is not persisted by default. Set MCP `persistTelemetry: true` to append metadata-only JSONL to the repo-root `.knodin-telemetry.jsonl`; knodin never sends it over the network. Use `telemetryAction: "report"` or `knodin telemetry report` for a static repository-local HTML report.\n\nCommon issues and how to resolve them when using knodin:\n\n### Corrupt Embedding Row\nIf you see warnings like `Skipping corrupt embedding... dimension mismatch`, your index database contains malformed embeddings.\n- **Fix**: Force a clean re-index of the repository to rebuild the vector store.\n```bash\n# Prefer surgical local repair; it preserves healthy state\nknodin repair\n```\n\n### Missing \'gh\' CLI Dependency\nThe `prs` triage operation requires the official GitHub CLI (`gh`) to be installed, in your PATH, and authenticated.\n- **Fix**: Run `gh auth login` to authenticate locally.\n\n### Legacy federation configuration\nIf legacy federation configuration fails, validate\n`.knodin/federation.json`, then migrate stable identities to `knodin.yaml`\nand local paths to XDG configuration. Do not infer membership from siblings.'},Zr={installation:"INSTALLATION.md",mcp:"MCP.md",repositories:"REPOSITORIES-AND-WORKTREES.md",systems:"SYSTEMS-AND-RELATIONSHIPS.md",provenance:"INDEXING-POLICY-AND-PROVENANCE.md","dead-code":"DEAD-CODE-AND-IMPACT.md",doctor:"DOCTOR-AND-UPDATES.md",compression:"COMMAND-OUTPUT-COMPRESSION.md"};function Xu(){let t=_n.dirname(Ku(import.meta.url));for(;!Kr.existsSync(_n.join(t,"package.json"))&&t!==_n.parse(t).root;)t=_n.dirname(t);return t}function aw(){return[...new Set([...Object.keys(Xr),...Object.keys(Zr)])].sort((t,e)=>t.localeCompare(e))}function cw(t){let e=Zr[t];if(e)try{return Kr.readFileSync(_n.join(Xu(),"docs",e),"utf-8")}catch(n){if(n.code==="ENOENT")return;throw n}return Xr[t]}import Yu from"node:child_process";import Oe from"node:fs";import qe from"node:path";import We from"node:fs";import ht from"node:path";import{isMap as ea,parseDocument as ta}from"yaml";var Gi="knodin-refresh",Zu="Managed locally by knodin init; repository hook configuration is not modified.",Ju=[{main:"lefthook.yml",local:"lefthook-local.yml"},{main:"lefthook.yaml",local:"lefthook-local.yaml"},{main:".lefthook.yml",local:".lefthook-local.yml"},{main:".lefthook.yaml",local:".lefthook-local.yaml"},{main:".config/lefthook.yml",local:".config/lefthook-local.yml"},{main:".config/lefthook.yaml",local:".config/lefthook-local.yaml"}],na={"post-commit":{run:".knodin/hooks/manager-dispatch.sh post-commit"},"post-checkout":{run:".knodin/hooks/manager-dispatch.sh post-checkout {1} {2} {3}"},"post-merge":{run:".knodin/hooks/manager-dispatch.sh post-merge {1}"},"post-rewrite":{run:".knodin/hooks/manager-dispatch.sh post-rewrite {1}",use_stdin:!0}},sa=`#!/bin/sh
63
+ # knodin manager-native lifecycle dispatcher. Generated by knodin init.
64
+ set -u
65
+ [ "\${KNODIN_WRAPPER_ACTIVE:-0}" = "1" ] && exit 0
66
+ REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)"
67
+ [ -n "$REPO_ROOT" ] || exit 0
68
+ BACKGROUND="$REPO_ROOT/.knodin/hooks/background-index.sh"
69
+ [ -x "$BACKGROUND" ] || exit 0
70
+ HOOK="\${1:-}"
71
+ shift || true
72
+ case "$HOOK" in
73
+ post-commit)
74
+ set -- commit
75
+ ;;
76
+ post-checkout)
77
+ [ "$#" -ge 2 ] || exit 0
78
+ set -- checkout "$1" "$2"
79
+ ;;
80
+ post-merge)
81
+ BEFORE="$(git rev-parse ORIG_HEAD 2>/dev/null || true)"
82
+ AFTER="$(git rev-parse HEAD 2>/dev/null || true)"
83
+ [ -n "$BEFORE" ] && [ -n "$AFTER" ] || exit 0
84
+ set -- merge "$BEFORE" "$AFTER"
85
+ ;;
86
+ post-rewrite)
87
+ INPUT="$(mktemp "$REPO_ROOT/.knodin/hooks/rewrite-input.XXXXXX")" || exit 0
88
+ cat > "$INPUT"
89
+ set -- rewrite "$INPUT"
90
+ ;;
91
+ *) exit 0 ;;
92
+ esac
93
+ nohup "$BACKGROUND" "$@" >/dev/null 2>&1 &
94
+ exit 0
95
+ `;function ia(t){for(let e of Ju)if(We.existsSync(ht.join(t,e.main)))return e;return null}function Jr(t){try{let e=We.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error(`knodin init: refusing non-regular hook-manager config: ${t}`)}catch(e){if(e.code!=="ENOENT")throw e}}function Yr(t,e,n){We.mkdirSync(ht.dirname(t),{recursive:!0});let s=`${t}.${process.pid}.${Date.now()}.tmp`;We.writeFileSync(s,e,{encoding:"utf-8",mode:n,flag:"wx"}),We.renameSync(s,t),n!==void 0&&We.chmodSync(t,n)}function Qr(t,e){let n=t.getIn(e,!0);if(n!==void 0&&!ea(n))throw new Error(`knodin init: cannot merge Lefthook integration because ${e.join(".")} is not a map`)}function oa(t){let e=ht.resolve(t),n=ia(e);if(!n)return null;let s=ht.join(e,n.local);Jr(s);let i=We.existsSync(s)?We.readFileSync(s,"utf-8"):"",o=ta(i||`{}
96
+ `,{keepSourceTokens:!0});if(o.errors.length>0)throw new Error(`knodin init: cannot parse ${n.local}: ${o.errors[0]?.message}`);if(!ea(o.contents))throw new Error(`knodin init: cannot merge ${n.local}: root must be a map`);i||(o.commentBefore=Zu);for(let[c,a]of Object.entries(na))Qr(o,[c]),Qr(o,[c,"commands"]),o.setIn([c,"commands",Gi],a);Yr(s,o.toString({lineWidth:0}));let r=ht.join(e,".knodin","hooks","manager-dispatch.sh");return Jr(r),Yr(r,sa,493),{manager:"lefthook",localConfig:n.local,dispatcher:".knodin/hooks/manager-dispatch.sh"}}function gs(t){let e=ht.resolve(t),n=ia(e);if(!n)return{configured:!1,localConfig:null};try{let s=ta(We.readFileSync(ht.join(e,n.local),"utf-8"));if(s.errors.length>0)return{configured:!1,localConfig:n.local};for(let[r,c]of Object.entries(na)){if(s.getIn([r,"commands",Gi,"run"])!==c.run)return{configured:!1,localConfig:n.local};if("use_stdin"in c&&s.getIn([r,"commands",Gi,"use_stdin"])!==!0)return{configured:!1,localConfig:n.local}}let i=ht.join(e,".knodin","hooks","manager-dispatch.sh"),o=We.statSync(i);return{configured:o.isFile()&&(o.mode&73)!==0&&We.readFileSync(i,"utf-8")===sa,localConfig:n.local}}catch{return{configured:!1,localConfig:n.local}}}function ys(t){return/\bcall_lefthook\b|\blefthook(?:\s|")/.test(t)}var Qu="KNODIN MANAGED HOOK",Vi=["post-commit","post-checkout","post-merge","post-rewrite"],ed="last-refresh-failure";function ua(t){try{let[e="",n="",s="",...i]=Oe.readFileSync(t,"utf-8").split(/\r?\n/);if(!e)return null;let o=new Map([n,s,...i].map(r=>{let c=r.indexOf("=");return c<0?null:[r.slice(0,c),r.slice(c+1)]}).filter(r=>r!==null));return{sequence:o.get("sequence")||null,kind:e,before:o.get("before")||(e==="commit"||e==="checkout"||e==="merge"?n:"")||null,after:o.get("after")||(e==="commit"||e==="checkout"||e==="merge"?s:"")||null,worktree:o.get("worktree")||null,at:o.get("at")||Oe.statSync(t).mtime.toISOString()}}catch{return null}}function ra(t){return ua(qe.join(t,".knodin","hooks","last-refresh-event"))}function aa(t){try{let e=qe.join(t,".knodin","hooks","events"),n=Oe.readdirSync(e).filter(s=>s.endsWith(".event")).sort((s,i)=>s.localeCompare(i))[0];return n?ua(qe.join(e,n)):null}catch{return null}}function ca(t){let e=qe.join(t,".knodin","hooks","refresh.lock","pid");if(!Oe.existsSync(qe.dirname(e)))return{state:"idle",pid:null};let n=null;try{let s=Number(Oe.readFileSync(e,"utf-8"));Number.isInteger(s)&&s>0&&(n=s)}catch{return{state:"stale-lock",pid:null}}if(n===null)return{state:"stale-lock",pid:null};try{return process.kill(n,0),{state:"running",pid:n}}catch(s){return s.code==="EPERM"?{state:"running",pid:n}:{state:"stale-lock",pid:n}}}function la(t){try{return Oe.readdirSync(qe.join(t,".knodin","hooks","events")).filter(e=>e.endsWith(".event")).length}catch{return 0}}function td(t){return Yu.execFileSync("git",["rev-parse","--path-format=absolute","--git-path","hooks"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}function nd(t,e){let n=[],s=[],i=0,o=0,r=gs(t);for(let c of Vi)try{let a=qe.join(e,c),l=Oe.readFileSync(a,"utf-8"),u=Oe.statSync(a).mode,f=l.startsWith(`#!/bin/sh
97
+ # ${Qu}: ${c}
98
+ `),m=r.configured&&ys(l),d=(u&73)!==0&&(f||m);d&&f?i++:d&&m&&o++,(d?n:s).push(c)}catch{s.push(c)}return{activeHooks:n,missingHooks:s,hookManager:r.configured?"lefthook":null,routing:i>0&&o>0?"mixed":i>0?"managed-wrapper":o>0?"manager-native":"unavailable"}}function sd(t){let e=qe.join(t,".knodin","hooks",ed);if(!Oe.existsSync(e))return null;try{return Oe.readFileSync(e,"utf-8").split(/\r?\n/,1)[0]?.trim()||"last background refresh failed"}catch{return"last background refresh failed"}}function Xt(t){let e=qe.resolve(t);if(!Oe.existsSync(qe.join(e,".knodin","db.sqlite")))return{status:"unconfigured",refreshCapable:!1,hooksDirectory:null,activeHooks:[],missingHooks:[...Vi],issues:["local graph database is not initialized"],queuedEvents:0,processor:{state:"idle",pid:null},pendingEvent:null,lastEvent:null,lastError:null,hookManager:null,routing:"unavailable"};let n;try{n=td(e)}catch{return{status:"degraded",refreshCapable:!1,hooksDirectory:null,activeHooks:[],missingHooks:[...Vi],issues:["active Git hooks directory could not be resolved"],queuedEvents:la(e),processor:ca(e),pendingEvent:aa(e),lastEvent:ra(e),lastError:null,hookManager:null,routing:"unavailable"}}let{activeHooks:s,missingHooks:i,hookManager:o,routing:r}=nd(e,n),c=qe.join(e,".knodin","hooks","background-index.sh"),a=Oe.existsSync(c)&&(Oe.statSync(c).mode&73)!==0,l=i.map(m=>`${m} no longer routes through knodin's active Git hook path`);a||l.push("background indexer is missing or not executable");let u=sd(e);u&&l.push(`${u} See .knodin/indexer.log for details`);let f=i.length===0&&a&&l.length===0;return{status:f?"healthy":"degraded",refreshCapable:f,hooksDirectory:n,activeHooks:s,missingHooks:i,issues:l,queuedEvents:la(e),processor:ca(e),pendingEvent:aa(e),lastEvent:ra(e),lastError:u,hookManager:o,routing:r}}function Ki(t,e){let n=Xt(t);return n.queuedEvents>0&&e.status!=="repair-needed"&&e.status!=="indexing"&&e.freshness?{...e,status:"stale",freshness:{...e.freshness,state:"queued"},lifecycle:n}:e.status!=="healthy"||n.status!=="degraded"?{...e,lifecycle:n}:{...e,status:"repair-needed",missing:{files:[...e.missing.files],records:[...e.missing.records,...n.issues]},repairSteps:[...e.repairSteps,"Run `knodin init` to restore managed lifecycle hooks.","Run `knodin status` again to verify graph and refresh-path health."],lifecycle:n}}function bw(t,e){let n=Xt(t);return{...e,lifecycle:n,nextSteps:n.status==="degraded"?["Run `knodin init` to restore lifecycle routing, then `knodin status`."]:[]}}import{createHash as Ie}from"node:crypto";import se from"node:fs";import $a from"node:os";import ae from"node:path";import{createHash as xd,timingSafeEqual as Td}from"node:crypto";import{createHash as Yi,createPublicKey as pa,verify as id,timingSafeEqual as ha}from"node:crypto";var pe=class extends Error{code;role;constructor(e,n,s){super(n),this.name="UpdateTrustError",this.code=e,this.role=s}},An=["root","targets","snapshot","timestamp"],Jt=/^[a-f0-9]{64}$/,od=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,rd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ad=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,cd=300*1e3,ld={root:366*24*60*60*1e3,targets:2232*60*60*1e3,snapshot:768*60*60*1e3,timestamp:11520*60*1e3};function Q(t,e){throw new pe("invalid-schema",t,e)}function Xi(t,e){if(t===null)return"null";if(typeof t=="string"||typeof t=="boolean")return JSON.stringify(t);if(typeof t=="number")return Number.isFinite(t)||Q("metadata numbers must be finite"),JSON.stringify(t);if(Array.isArray(t)){e.has(t)&&Q("metadata must not contain cycles"),e.add(t);let o=`[${t.map(r=>Xi(r,e)).join(",")}]`;return e.delete(t),o}(typeof t!="object"||t===void 0)&&Q(`metadata contains unsupported ${typeof t} value`),e.has(t)&&Q("metadata must not contain cycles");let n=Object.getPrototypeOf(t);n!==Object.prototype&&n!==null&&Q("metadata objects must be plain"),e.add(t);let s=t,i=`{${Object.keys(s).sort().map(o=>(s[o]===void 0&&Q(`metadata field ${o} must not be undefined`),`${JSON.stringify(o)}:${Xi(s[o],e)}`)).join(",")}}`;return e.delete(t),i}function je(t){return Xi(t,new Set)}function Fn(t){return Yi("sha256").update(je(t)).digest("hex")}function ud(t){return Fn(t)}function dd(t){let e=je(t);return{version:t.signed.version,length:Buffer.byteLength(e),hashes:{sha256:Yi("sha256").update(e).digest("hex")}}}function me(t,e,n){return(t===null||typeof t!="object"||Array.isArray(t))&&Q(`${e} must be an object`,n),t}function ke(t,e,n,s){let i=Object.keys(t).filter(o=>!e.includes(o));i.length>0&&Q(`${n} contains unsupported fields: ${i.join(", ")}`,s)}function Zi(t,e){let n=me(t,`${e} envelope`,e);ke(n,["signed","signatures"],`${e} envelope`,e),me(n.signed,`${e} signed payload`,e),(!Array.isArray(n.signatures)||n.signatures.length>64)&&Q(`${e} signatures must be a bounded array`,e)}function ws(t,e,n){return(!Number.isSafeInteger(t)||t<1)&&Q(`${e} must be a positive safe integer`,n),t}function ga(t,e,n){return(!Number.isSafeInteger(t)||t<0)&&Q(`${e} must be a non-negative safe integer`,n),t}function da(t,e,n){(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(t))&&Q(`${e} must be an ISO-8601 instant`,n);let s=Date.parse(t);return(!Number.isFinite(s)||new Date(s).toISOString()!==t)&&Q(`${e} must be a canonical UTC ISO-8601 instant`,n),s}function Ss(t,e,n){let s=me(t,`${e} signed payload`,e);s._type!==e&&Q(`${e} metadata has the wrong _type`,e),s.specVersion!=="1.0"&&Q(`${e} metadata requires specVersion 1.0`,e),ws(s.version,`${e}.version`,e);let i=da(s.generatedAt,`${e}.generatedAt`,e),o=da(s.expires,`${e}.expires`,e);if(i>n+cd)throw new pe("future-metadata",`${e} metadata is generated in the future`,e);if(o<=n)throw new pe("expired",`${e} metadata expired at ${s.expires}`,e);(o<=i||o-i>ld[e])&&Q(`${e} metadata lifetime exceeds its role policy`,e)}function fd(t,e){let n=me(t,`key ${e}`),s=me(n.keyval,`key ${e}.keyval`);ke(n,["keytype","scheme","keyval"],`key ${e}`),ke(s,["public"],`key ${e}.keyval`),(n.keytype!=="ed25519"||n.scheme!=="ed25519")&&Q(`key ${e} must use Ed25519`),(typeof s.public!="string"||s.public.length<32||s.public.length>8192)&&Q(`key ${e} has an invalid public key`);let i;try{i=pa(s.public)}catch{Q(`key ${e} is not a valid public key`)}i.asymmetricKeyType!=="ed25519"&&Q(`key ${e} is not an Ed25519 key`),ud(n)!==e&&Q(`key ${e} does not match its content-derived key id`)}function md(t){let e=me(t,"root.keys","root");(Object.keys(e).length<6||Object.keys(e).length>64)&&Q("root.keys must contain between 6 and 64 keys","root");for(let[n,s]of Object.entries(e))Jt.test(n)||Q(`root key id ${n} is not a SHA-256 digest`,"root"),fd(s,n);return e}function pd(t,e,n,s,i){(typeof t!="string"||!Object.hasOwn(n,t))&&Q(`${e} references an unknown key`,"root"),s.has(t)&&Q(`${e} contains a duplicate key id`,"root"),s.add(t);let o=i.get(t);if(o!==void 0)throw new pe("role-separation",`key ${t} is assigned to both ${o} and ${e}`,"root");i.set(t,e)}function hd(t,e,n,s){let i=me(t,`root.roles.${e}`,"root");ke(i,["keyids","threshold"],`root.roles.${e}`,"root");let o=ws(i.threshold,`root.roles.${e}.threshold`,"root");(!Array.isArray(i.keyids)||i.keyids.length===0)&&Q(`root.roles.${e}.keyids must be a non-empty array`,"root"),i.keyids.length>64&&Q(`${e} contains too many key ids`,"root"),o>i.keyids.length&&Q(`${e} threshold exceeds its key count`,"root"),(e==="root"||e==="targets")&&o<2&&Q(`${e} requires a production threshold of at least two`,"root");let r=new Set;for(let c of i.keyids)pd(c,e,n,r,s)}function fa(t,e){Ss(t,"root",e),ke(t,["_type","specVersion","version","generatedAt","expires","consistentSnapshot","keys","roles"],"root signed payload","root"),t.consistentSnapshot!==!0&&Q("root must require consistent snapshots","root");let n=md(t.keys),s=me(t.roles,"root.roles","root"),i=new Map;for(let r of An)hd(s[r],r,n,i);let o=Object.keys(s).filter(r=>!An.includes(r));o.length>0&&Q(`root contains unsupported roles: ${o.join(", ")}`,"root")}function gd(t,e){let n=me(t,`${e} signature`,e);return ke(n,["keyid","sig"],`${e} signature`,e),(typeof n.keyid!="string"||typeof n.sig!="string")&&Q(`${e} signature requires keyid and sig strings`,e),n}function yd(t,e,n,s,i){if(!s.has(t.keyid))return"ignored";(t.sig.length!==88||!ad.test(t.sig))&&Q(`${n} signature is not canonical Ed25519 base64`,n);let o=Buffer.from(t.sig,"base64");o.byteLength!==64&&Q(`${n} Ed25519 signature must be 64 bytes`,n);let r=e.keys[t.keyid];return id(null,i,pa(r.keyval.public),o)?"valid":"invalid"}function Zt(t,e,n){Zi(t,n);let s=e.roles[n],i=new Set(s.keyids),o=new Set,r=Buffer.from(je(t.signed)),c=0,a=!1;for(let l of t.signatures){let u=gd(l,n);o.has(u.keyid)&&Q(`${n} contains a duplicate signature`,n),o.add(u.keyid);let f=yd(u,e,n,i,r);f==="valid"&&(c+=1),f==="invalid"&&(a=!0)}if(c<s.threshold)throw a?new pe("invalid-signature",`${n} contains an invalid signature`,n):new pe("insufficient-signatures",`${n} has ${c} valid signature(s); ${s.threshold} required`,n)}function ya(t,e,n){let s=me(t,e,n);ke(s,["version","length","hashes"],e,n),ws(s.version,`${e}.version`,n),ga(s.length,`${e}.length`,n);let i=me(s.hashes,`${e}.hashes`,n);ke(i,["sha256"],`${e}.hashes`,n),(typeof i.sha256!="string"||!Jt.test(i.sha256))&&Q(`${e}.hashes.sha256 must be a lowercase SHA-256 digest`,n)}function bd(t,e){let n=me(t,`target ${e}`,"targets");ke(n,["length","hashes","custom"],`target ${e}`,"targets"),ga(n.length,`target ${e}.length`,"targets");let s=me(n.hashes,`target ${e}.hashes`,"targets");ke(s,["sha256"],`target ${e}.hashes`,"targets"),(typeof s.sha256!="string"||!Jt.test(s.sha256))&&Q(`target ${e} requires a lowercase SHA-256 digest`,"targets");let i=me(n.custom,`target ${e}.custom`,"targets");ke(i,["version","channel","sourceCommit","provenanceSha256","sbomSha256","sbomAttestationSha256","releaseAttestationSha256"],`target ${e}.custom`,"targets"),(typeof i.version!="string"||i.version.length>128||!od.test(i.version))&&Q(`target ${e} requires a semantic version`,"targets"),(typeof i.channel!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(i.channel))&&Q(`target ${e} has an invalid channel`,"targets"),(typeof i.sourceCommit!="string"||!rd.test(i.sourceCommit))&&Q(`target ${e} requires a full source commit`,"targets");for(let o of["provenanceSha256","sbomSha256","sbomAttestationSha256","releaseAttestationSha256"])i[o]!==void 0&&(typeof i[o]!="string"||!Jt.test(i[o]))&&Q(`target ${e}.${o} must be a lowercase SHA-256 digest`,"targets")}function wd(t,e){Ss(t,"targets",e),ke(t,["_type","specVersion","version","generatedAt","expires","targets"],"targets signed payload","targets");let n=me(t.targets,"targets.targets","targets");(Object.keys(n).length===0||Object.keys(n).length>1e3)&&Q("targets metadata must contain between 1 and 1000 targets","targets");for(let[s,i]of Object.entries(n))(s.length===0||s.length>512||s.startsWith("/")||s.includes("\\")||s.split("/").some(o=>o===""||o==="."||o===".."))&&Q(`unsafe target path: ${s}`,"targets"),bd(i,s)}function Sd(t,e){Ss(t,"snapshot",e),ke(t,["_type","specVersion","version","generatedAt","expires","meta"],"snapshot signed payload","snapshot");let n=me(t.meta,"snapshot.meta","snapshot");(Object.keys(n).length!==1||n["targets.json"]===void 0)&&Q("snapshot must describe exactly targets.json","snapshot"),ya(n["targets.json"],"snapshot.meta.targets.json","snapshot")}function Ed(t,e){Ss(t,"timestamp",e),ke(t,["_type","specVersion","version","generatedAt","expires","meta"],"timestamp signed payload","timestamp");let n=me(t.meta,"timestamp.meta","timestamp");(Object.keys(n).length!==1||n["snapshot.json"]===void 0)&&Q("timestamp must describe exactly snapshot.json","timestamp"),ya(n["snapshot.json"],"timestamp.meta.snapshot.json","timestamp")}function ma(t,e,n){let s=dd(e);if(t.version!==s.version||t.length!==s.length||t.hashes.sha256!==s.hashes.sha256)throw new pe("mix-and-match",`${n} does not match its signed descriptor`)}function bs(t){return{version:t.signed.version,sha256:Fn(t)}}function kd(t){let e=me(t,"previous trusted state");ke(e,An,"previous trusted state");for(let n of An){let s=me(e[n],`previous trusted state.${n}`,n);ke(s,["version","sha256"],`previous trusted state.${n}`,n),ws(s.version,`previous trusted state.${n}.version`,n),(typeof s.sha256!="string"||!Jt.test(s.sha256))&&Q(`previous trusted state.${n}.sha256 must be a lowercase SHA-256 digest`,n)}}function vd(t,e){if(e){kd(e);for(let n of An){if(t[n].version<e[n].version)throw new pe("rollback",`${n} version moved backwards`,n);if(t[n].version===e[n].version&&t[n].sha256!==e[n].sha256)throw new pe("equivocation",`${n} changed without increasing its version`,n)}}}function Ji(t,e,n,s){Jt.test(n)||Q("trusted root pin must be a lowercase SHA-256 digest","root"),Zi(e,"root"),fa(e.signed,s),Zt(e,e.signed,"root");let i=Fn(e);if(!ha(Buffer.from(i,"hex"),Buffer.from(n,"hex")))throw new pe("untrusted-root","trusted root does not match its independent pin","root");Zi(t,"root"),fa(t.signed,s);let o=Fn(t);if(t.signed.version<e.signed.version)throw new pe("rollback","root version moved backwards","root");if(t.signed.version===e.signed.version){if(o!==i)throw new pe("equivocation","trusted root changed without rotation","root");return t.signed}if(t.signed.version!==e.signed.version+1)throw new pe("root-rotation","root rotations must be applied one version at a time","root");return Zt(t,e.signed,"root"),Zt(t,t.signed,"root"),t.signed}function Qi(t,e,n,s=new Date){let i=s.getTime();Number.isFinite(i)||Q("verification time must be valid");let o=t,r=e;Ji(o,o,r,i);for(let c of n)Ji(c,o,r,i),o=c,r=Fn(c);return o}function Es(t,e){let n=(e.now??new Date).getTime();Number.isFinite(n)||Q("verification time must be valid");let s=Ji(t.root,e.trustedRoot,e.trustedRootSha256,n);wd(t.targets.signed,n),Sd(t.snapshot.signed,n),Ed(t.timestamp.signed,n),Zt(t.targets,s,"targets"),Zt(t.snapshot,s,"snapshot"),Zt(t.timestamp,s,"timestamp"),ma(t.timestamp.signed.meta["snapshot.json"],t.snapshot,"snapshot metadata"),ma(t.snapshot.signed.meta["targets.json"],t.targets,"targets metadata");let i={root:bs(t.root),targets:bs(t.targets),snapshot:bs(t.snapshot),timestamp:bs(t.timestamp)};vd(i,e.previous);let o=t.targets.signed.targets[e.targetPath];if(!o)throw new pe("target-not-found",`targets metadata does not authorize ${e.targetPath}`,"targets");return{targetPath:e.targetPath,target:o,root:s,rootEnvelope:t.root,state:i}}function ks(t,e){if(t.byteLength!==e.length)throw new pe("artifact-mismatch",`artifact length ${t.byteLength} does not match signed length ${e.length}`);let n=Yi("sha256").update(t).digest(),s=Buffer.from(e.hashes.sha256,"hex");if(n.byteLength!==s.byteLength||!ha(n,s))throw new pe("artifact-mismatch","artifact SHA-256 does not match signed metadata")}var to=["public-npm","docusign-artifactory","github-saas","homebrew","ghes"],Qt=/^[a-f0-9]{64}$/,wa=/^[a-f0-9]{128}$/,Sa=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,no=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Rd=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,255}$/,$d=/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/,_d=/^\d{1,32}$/,Ad=/^1\.[4-6]$/,so=512*1024*1024,Yt=16*1024*1024,Fd={"public-npm":"registry.npmjs.org","docusign-artifactory":"artifactory-corp.docusignhq.com","github-saas":"github.com",homebrew:"github.com",ghes:"github.docusignhq.com"};function ee(t){throw new Error(`invalid release attestation: ${t}`)}function ze(t,e){return(t===null||typeof t!="object"||Array.isArray(t))&&ee(`${e} must be an object`),t}function rt(t,e,n){let s=new Set(e);for(let i of Object.keys(t))s.has(i)||ee(`${n} contains unsupported field ${i}`)}function he(t,e,n=1024){return(typeof t!="string"||t.length===0||t.length>n)&&ee(`${e} must be a non-empty bounded string`),t}function en(t,e,n=Number.MAX_SAFE_INTEGER){return(!Number.isSafeInteger(t)||t<0||t>n)&&ee(`${e} must be a bounded non-negative integer`),t}function io(t,e){let n=he(t,e,64),s=new Date(n);return(!Number.isFinite(s.getTime())||s.toISOString()!==n)&&ee(`${e} must be a canonical UTC instant`),n}function Ln(t,e){return xd(t).update(e).digest("hex")}function _t(t,e){let n=Buffer.from(t,"hex"),s=Buffer.from(e,"hex");return n.byteLength===s.byteLength&&Td(n,s)}function vs(t,e,n){t instanceof Uint8Array||ee(`${e} must be bytes`),(t.byteLength===0||t.byteLength>n)&&ee(`${e} exceeds its non-empty byte budget`)}function eo(t,e){try{return ze(JSON.parse(Buffer.from(t).toString("utf-8")),e)}catch(n){if(n instanceof Error&&n.message.startsWith("invalid release attestation:"))throw n;return ee(`${e} must be valid JSON`)}}function Nn(t,e){return(!Rd.test(t)||t==="."||t==="..")&&ee(`${e} must be a safe file name`),t}function Ea(t,e){let n=he(t,e,2048),s;try{s=new URL(n)}catch{return ee(`${e} must be an HTTPS URL`)}return(s.protocol!=="https:"||s.username!==""||s.password!==""||s.hash!==""||s.port!=="")&&ee(`${e} must be a canonical HTTPS URL without credentials, a fragment, or a port`),s.search!==""&&ee(`${e} must not contain a query that could disclose credentials`),s.toString()}function Ld(t,e,n){let s=ze(t,`${n} verification`);rt(s,["verified","attestationId","attestationUrl","issuer","identity","verifiedAt"],`${n} verification`),typeof t.verified!="boolean"&&ee(`${n} verified must be boolean`);let i=he(t.attestationId,`${n} attestation ID`,256),o=new URL(Ea(t.attestationUrl,`${n} attestation URL`)),r=`/${e.repository}/attestations/${encodeURIComponent(i)}`;(o.hostname!=="github.com"||o.pathname!==r)&&ee(`${n} attestation URL does not match its repository and attestation ID`),t.issuer!=="https://token.actions.githubusercontent.com"&&ee(`${n} has an unapproved signature issuer`);let c=`https://github.com/${e.repository}/${e.workflow}@${e.workflowRef}`;t.identity!==c&&ee(`${n} signature identity does not match build`),io(t.verifiedAt,`${n} verification time`)}function Nd(t,e){let n=ze(t,"build");return rt(n,["repository","workflow","workflowRef","runId","runAttempt"],"build"),$d.test(t.repository)||ee("build repository must be an owner/name slug"),/^\.github\/workflows\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.ya?ml$/.test(t.workflow)||ee("build workflow must be a repository workflow path"),t.workflowRef!==`refs/tags/${e}`&&ee("build workflow ref must equal the release tag"),_d.test(t.runId)||ee("build run ID must be decimal"),en(t.runAttempt,"build run attempt",1e3),t.runAttempt<1&&ee("build run attempt must be positive"),{...t}}function Cd(t,e,n,s,i,o){let r=[];e||r.push("build provenance signature is not verified"),n||r.push("SBOM signature is not verified");let c=!1;for(let a of to){let l=t[a];if(l.status==="missing"&&r.push(`${a}: channel evidence is missing`),l.status==="mismatch"){c=!0;let u="channel evidence is malformed";l.artifactLength!==s.length||!l.artifactSha256||!_t(l.artifactSha256,s.sha256)?u="artifact digest or length differs":l.version!==i?u="version differs":l.sourceCommit!==o&&(u="source commit differs"),r.push(`${a}: ${u}`)}}return{status:Od(c,r),failures:r}}function Od(t,e){return t?"quarantined":e.length===0?"verified":"incomplete"}function At(t,e,n){let s=he(t,e,n===wa?128:64);return n.test(s)||ee(`${e} must be a lowercase digest`),s}function Id(t){let e=ze(t,"artifact");rt(e,["name","length","sha256","sha512","npmIntegrity"],"artifact");let n=At(e.sha512,"artifact SHA-512",wa),s=he(e.npmIntegrity,"npm integrity",256),i=`sha512-${Buffer.from(n,"hex").toString("base64")}`;return s!==i&&ee("npm integrity does not match artifact SHA-512"),{name:Nn(he(e.name,"artifact name",256),"artifact name"),length:en(e.length,"artifact length",so),sha256:At(e.sha256,"artifact SHA-256",Qt),sha512:n,npmIntegrity:s}}function Md(t,e,n,s,i){let o=ze(t,`${e} channel`);if(rt(o,["status","artifactLength","artifactSha256","version","sourceCommit","publishedAt","location"],`${e} channel`),o.status==="missing")return Object.keys(o).length!==1&&ee(`${e} missing evidence contains observations`),{status:"missing"};o.status!=="verified"&&o.status!=="mismatch"&&ee(`${e} has an invalid status`);let r=Ea(o.location,`${e} location`);new URL(r).hostname!==Fd[e]&&ee(`${e} location must use its approved host`);let c={status:o.status,artifactLength:en(o.artifactLength,`${e} artifact length`,so),artifactSha256:At(o.artifactSha256,`${e} artifact SHA-256`,Qt),version:he(o.version,`${e} version`,128),sourceCommit:he(o.sourceCommit,`${e} source commit`,64),publishedAt:io(o.publishedAt,`${e} publication time`),location:r};no.test(c.version??"")||ee(`${e} channel version must be semantic`),Sa.test(c.sourceCommit??"")||ee(`${e} channel source commit must be a full lowercase digest`);let a=c.artifactLength===n.length&&_t(c.artifactSha256??"",n.sha256)&&c.version===s&&c.sourceCommit===i;return c.status==="verified"!==a&&ee(`${e} status does not match its artifact, version, and source evidence`),c}function ba(t,e,n){let s=ze(t,`${n} verification`);return Ld(s,e,n),{...s}}function Pd(t){t.schemaVersion!==1&&ee("schema version must be 1");let e=he(t.version,"version",128);no.test(e)||ee("version must be a semantic version");let n=he(t.tag,"tag",129);n!==`v${e}`&&ee("tag must equal v plus the semantic version");let s=he(t.sourceCommit,"source commit",64);Sa.test(s)||ee("source commit must be a full lowercase digest");let i=io(t.generatedAt,"generation time"),o=Nd(ze(t.build,"build"),n),r=Id(t.artifact);return r.name!==`knodin-${e}.tgz`&&ee("artifact name does not match version"),{version:e,tag:n,sourceCommit:s,generatedAt:i,build:o,artifact:r}}function oo(t,e){let n=ze(t,"release attestation");rt(n,["schemaVersion","status","version","tag","sourceCommit","generatedAt","build","artifact","provenance","sbom","channels","rollback","failures"],"release attestation");let{version:s,tag:i,sourceCommit:o,generatedAt:r,build:c,artifact:a}=Pd(n),l=ze(n.provenance,"provenance");rt(l,["path","length","sha256","verification"],"provenance");let u={path:Nn(he(l.path,"provenance path",256),"provenance path"),length:en(l.length,"provenance length",Yt),sha256:At(l.sha256,"provenance SHA-256",Qt),verification:ba(l.verification,c,"build provenance")},f=ze(n.sbom,"SBOM");rt(f,["format","specVersion","path","length","sha256","attestationPath","attestationLength","attestationSha256","verification"],"SBOM"),f.format!=="CycloneDX"&&ee("SBOM format must be CycloneDX");let m={format:"CycloneDX",specVersion:he(f.specVersion,"SBOM specification version",16),path:Nn(he(f.path,"SBOM path",256),"SBOM path"),length:en(f.length,"SBOM length",Yt),sha256:At(f.sha256,"SBOM SHA-256",Qt),attestationPath:Nn(he(f.attestationPath,"SBOM attestation path",256),"SBOM attestation path"),attestationLength:en(f.attestationLength,"SBOM attestation length",Yt),attestationSha256:At(f.attestationSha256,"SBOM attestation SHA-256",Qt),verification:ba(f.verification,c,"SBOM")};Ad.test(m.specVersion)||ee("SBOM must use a supported CycloneDX specification version"),vs(e.artifact,"artifact",so),vs(e.provenance,"provenance",Yt),vs(e.sbom,"SBOM",Yt),vs(e.sbomAttestation,"SBOM attestation",Yt),(e.artifact.byteLength!==a.length||!_t(Ln("sha256",e.artifact),a.sha256)||!_t(Ln("sha512",e.artifact),a.sha512))&&ee("artifact digest or length mismatch"),(e.provenance.byteLength!==u.length||!_t(Ln("sha256",e.provenance),u.sha256))&&ee("provenance digest or length mismatch"),(e.sbom.byteLength!==m.length||!_t(Ln("sha256",e.sbom),m.sha256))&&ee("SBOM digest or length mismatch"),(e.sbomAttestation.byteLength!==m.attestationLength||!_t(Ln("sha256",e.sbomAttestation),m.attestationSha256))&&ee("SBOM attestation digest or length mismatch");let d=eo(e.sbom,"SBOM");(d.bomFormat!==m.format||d.specVersion!==m.specVersion)&&ee("SBOM format metadata does not match its bytes"),eo(e.provenance,"provenance"),eo(e.sbomAttestation,"SBOM attestation");let y=ze(n.channels,"channels");rt(y,to,"channels");let g={};for(let v of to)v in y||ee(`channels is missing ${v}`),g[v]=Md(y[v],v,a,s,o);let h=ze(n.rollback,"rollback");rt(h,["version","targetPath","artifactSha256"],"rollback");let w={version:he(h.version,"rollback version",128),targetPath:Nn(he(h.targetPath,"rollback target path",256),"rollback target path"),artifactSha256:At(h.artifactSha256,"rollback artifact SHA-256",Qt)};(!no.test(w.version)||w.version===s)&&ee("rollback version must be a different semantic version"),(!Array.isArray(n.failures)||n.failures.length>100)&&ee("failures must be a bounded array");let k=n.failures.map((v,S)=>he(v,`failure ${S}`,512)),_=Cd(g,u.verification.verified,m.verification.verified,a,s,o);return n.status!==_.status&&ee("attestation status does not match its evidence"),(k.length!==_.failures.length||k.some((v,S)=>v!==_.failures[S]))&&ee("attestation failures do not match its evidence"),{schemaVersion:1,status:_.status,version:s,tag:i,sourceCommit:o,generatedAt:r,build:c,artifact:a,provenance:u,sbom:m,channels:g,rollback:w,failures:k}}var Dd=2e3,jd=1e4,lo=512*1024,tn=16*1024*1024,zd=4*1024*1024,ao=512*1024*1024,ka=32,Bd=4,Hd=/^[a-f0-9]{64}$/,Ud=/^[A-Za-z0-9._/{}-]+$/;function Lw(t,e=process.env){if(e.MISE_DATA_DIR||e.MISE_ENV)return"mise";if(e.VOLTA_HOME)return"volta";if(e.NVM_BIN||e.NVM_DIR)return"nvm";if(e.FNM_DIR||e.FNM_MULTISHELL_PATH)return"fnm";if(e.ASDF_DIR||e.ASDF_DATA_DIR)return"asdf";if(e.HOMEBREW_PREFIX)return"homebrew";let n=t.join(" ").toLowerCase();return n.includes("/homebrew/")||n.includes("/cellar/")?"homebrew":n.includes("/.local/share/mise/")?"mise":n.includes("/.volta/")?"volta":n.includes("/.nvm/")?"nvm":n.includes("/fnm")?"fnm":n.includes("/.asdf/")?"asdf":n.includes("node_modules/knodin/")?"npm":"unknown"}function gt(t){let e=t??process.env.XDG_STATE_HOME??ae.join($a.homedir(),".local","state");return ae.join(e,"knodin","trusted-update-state.json")}function _a(t){return ae.join(ae.dirname(gt(t)),"update-check.lock")}function Wd(t){let e=t??process.env.XDG_CONFIG_HOME??ae.join($a.homedir(),".config");return ae.join(e,"knodin","update.json")}function xs(t,e){se.mkdirSync(ae.dirname(t),{recursive:!0,mode:448});try{se.chmodSync(ae.dirname(t),448)}catch{}let n=`${t}.${process.pid}.${Date.now()}.tmp`;se.writeFileSync(n,`${JSON.stringify(e)}
99
+ `,{mode:384,flag:"wx"}),se.renameSync(n,t);try{se.chmodSync(t,384)}catch{}}function uo(t,e=lo){try{return se.statSync(t).size>e?null:JSON.parse(se.readFileSync(t,"utf-8"))}catch{return null}}function $s(t){let e=uo(gt(t),zd);return!e||typeof e!="object"||e.schemaVersion!==1?null:e}function Nw(t){let e=Cn(t),n=t.env??process.env;if(!e||!e.enabled||e.offline||n.KNODIN_UPDATE_CHECK==="0"||n.KNODIN_OFFLINE==="1")return!1;let s=t.now?.()??new Date,i=$s(t.stateHome)?.checkedAt;if(i&&s.getTime()-Date.parse(i)<e.checkIntervalHours*36e5)return!1;let o=_a(t.stateHome);se.mkdirSync(ae.dirname(o),{recursive:!0,mode:448});try{return se.writeFileSync(o,`${process.pid} ${s.toISOString()}
100
+ `,{flag:"wx",mode:384}),!0}catch(r){if(r.code!=="EEXIST")return!1;try{let c=se.readFileSync(o,"utf-8").trim().split(/\s+/,2)[1],a=c?Date.parse(c):Number.NaN;return s.getTime()-(Number.isFinite(a)?a:se.statSync(o).mtimeMs)<=Math.max(e.timeoutMs*4,6e4)?!1:(se.unlinkSync(o),se.writeFileSync(o,`${process.pid} ${s.toISOString()}
101
+ `,{flag:"wx",mode:384}),!0)}catch{return!1}}}function Cw(t){try{se.unlinkSync(_a(t))}catch(e){if(e.code!=="ENOENT")throw e}}function Ts(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qd(t){if(!Ts(t)||t.schemaVersion!==1||!Ts(t.policy))return null;let e=t;if(typeof e.enabled!="boolean"||typeof e.offline!="boolean"||typeof e.metadataBaseUrl!="string"||typeof e.trustedRootPath!="string"||!Hd.test(e.trustedRootSha256)||typeof e.targetPathTemplate!="string"||!Ud.test(e.targetPathTemplate)||!e.targetPathTemplate.includes("{version}")||typeof e.channel!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(e.channel)||!Number.isFinite(e.checkIntervalHours)||e.checkIntervalHours<1||!Number.isInteger(e.timeoutMs)||e.timeoutMs<100||e.timeoutMs>jd||!["notify-only","download-verify-only","apply-patch","apply-minor"].includes(e.policy.mode)||!Number.isFinite(e.policy.minimumReleaseAgeHours)||e.policy.minimumReleaseAgeHours<0||!Array.isArray(e.policy.approvedChannels)||!e.policy.approvedChannels.every(n=>typeof n=="string"))return null;try{fo(e.targetPathTemplate,"0.0.0");let n=new URL(e.metadataBaseUrl);if(n.protocol!=="https:"||!n.pathname.endsWith("/")||n.username!==""||n.password!==""||n.search!==""||n.hash!=="")return null;let s=new Set(e.approvedMirrorOrigins??[]);if(e.enterpriseMirrorOnly&&!s.has(n.origin)||(e.crossCheckMetadataBaseUrls?.length??0)>Bd)return null;for(let i of e.crossCheckMetadataBaseUrls??[]){let o=new URL(i);if(o.protocol!=="https:"||!o.pathname.endsWith("/")||o.username!==""||o.password!==""||o.search!==""||o.hash!==""||e.enterpriseMirrorOnly&&!s.has(o.origin))return null}for(let i of e.policy.maintenanceWindows??[])if(!Array.isArray(i.days)||i.days.length===0||!i.days.every(o=>Number.isInteger(o)&&o>=0&&o<=6)||!/^([01]\d|2[0-3]):[0-5]\d$/.test(i.startUtc)||!/^([01]\d|2[0-3]):[0-5]\d$/.test(i.endUtc)||i.startUtc>=i.endUtc)return null}catch{return null}return e}function Cn(t){return t.config?qd(t.config):(uo(Wd(t.configHome)),null)}function Rs(t){return t.installMethod??"unknown"}function _e(t,e){return{schemaVersion:1,status:e,installedVersion:t.currentVersion,installMethod:Rs(t),networkUsed:!1}}function nn(t){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(t);if(!e)return null;let n=e[4]?.split(".")??null;return n?.some(s=>s===""||/^\d+$/.test(s)&&s.length>1&&s.startsWith("0"))?null:{core:[Number(e[1]),Number(e[2]),Number(e[3])],prerelease:n}}function _s(t,e){let n=nn(t),s=nn(e);if(!n||!s)return Aa(t,e);let i=Gd(n,s);return i===0?Vd(n.prerelease,s.prerelease):i}function Aa(t,e){return t===e?0:t<e?-1:1}function Gd(t,e){for(let n=0;n<3;n++){let s=(t.core[n]??0)-(e.core[n]??0);if(s!==0)return s}return 0}function Vd(t,e){if(t===null)return e===null?0:1;if(e===null)return-1;for(let n=0;n<Math.max(t.length,e.length);n++){let s=Kd(t[n],e[n]);if(s!==0)return s}return 0}function Kd(t,e){return t===void 0?e===void 0?0:-1:e===void 0?1:t===e?0:Xd(t,e)}function Xd(t,e){let n=/^\d+$/.test(t),s=/^\d+$/.test(e);return n&&s?Number(t)-Number(e):n!==s?n?-1:1:Aa(t,e)}function fo(t,e){if(!nn(e))throw new Error("signed target version is not valid SemVer");let n=t.replaceAll("{version}",e);if(n.startsWith("/")||n.includes("\\")||n.split("/").some(s=>s===""||s==="."||s===".."))throw new Error("configured target template produced an unsafe path");return n}function Zd(t,e){let s=Object.entries(t.targets.signed.targets).filter(([,i])=>i.custom.channel===e.channel).filter(([,i])=>nn(i.custom.version)!==null).filter(([i,o])=>i===fo(e.targetPathTemplate,o.custom.version)).sort(([,i],[,o])=>_s(o.custom.version,i.custom.version))[0];if(!s)throw new Error(`signed targets contain no ${e.channel} release`);return s[0]}async function Jd(t,e){let n=await fetch(t,{signal:e.signal,redirect:"error",headers:{accept:"application/octet-stream, application/json"}});if(!n.ok)throw new Error(`update source returned HTTP ${n.status}`);let s=Number(n.headers.get("content-length"));if(Number.isFinite(s)&&s>e.maxBytes)throw new Error("update response exceeds byte limit");if(!n.body)return new Uint8Array;let i=[],o=0,r=n.body.getReader();for(;;){let{done:c,value:a}=await r.read();if(c)break;if(o+=a.byteLength,o>e.maxBytes)throw await r.cancel(),new Error("update response exceeds byte limit");i.push(a)}return Buffer.concat(i.map(c=>Buffer.from(c)),o)}function at(t,e){let n=new URL(t),s=new URL(e,n);if(s.protocol!=="https:"||s.origin!==n.origin||!s.pathname.startsWith(n.pathname))throw new Error("update URL escaped the approved HTTPS origin/path");return s.href}async function ct(t,e,n,s){let i=new AbortController,o;try{let r=new Promise((a,l)=>{o=setTimeout(()=>{i.abort(),l(new Error("update request exceeded its timeout"))},e.timeoutMs||Dd)}),c=await Promise.race([(t.fetchBytes??Jd)(n,{signal:i.signal,maxBytes:s}),r]);if(c.byteLength>s)throw new Error("update response exceeds byte limit");return c}finally{o&&clearTimeout(o)}}function As(t,e){try{return JSON.parse(Buffer.from(t).toString("utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}}async function va(t,e,n){let s={},i={};for(let o of["timestamp","snapshot","targets","root"]){let r=await ct(t,e,at(n,`${o}.json`),lo);s[o]=As(r,`${o}.json`),i[o]=Ie("sha256").update(r).digest("hex")}return{bundle:s,digests:i}}function ro(t,e){if(!Ts(t)||!Ts(t.signed))throw new Error(`${e} has no signed root`);let n=t.signed.version;if(!Number.isSafeInteger(n)||Number(n)<=0)throw new Error(`${e} has an invalid root version`);return Number(n)}async function xa(t,e,n,s,i){let o=ro(s,"trusted root"),r=ro(i,"root.json"),c=r-o;if(c>ka)throw new Error(`root rotation gap ${c} exceeds the per-check limit ${ka}`);let a=[],l={};for(let u=o+1;u<=r;u++){let f=`${u}.root.json`,m=await ct(t,e,at(n,f),lo),d=As(m,f);if(ro(d,f)!==u)throw new Error(`${f} has the wrong root version`);a.push(d),l[f]=Ie("sha256").update(m).digest("hex")}if(r===o){let u=Ie("sha256").update(je(i)).digest("hex"),f=Ie("sha256").update(je(s)).digest("hex");if(u!==f)throw new Error("root.json disagrees with the pinned root at the same version")}else if(Ie("sha256").update(je(a.at(-1))).digest("hex")!==Ie("sha256").update(je(i)).digest("hex"))throw new Error(`root.json disagrees with ${r}.root.json`);return{roots:a,digests:l}}async function Yd(t,e,n,s,i){let o=await va(t,e,e.metadataBaseUrl),r=await xa(t,e,e.metadataBaseUrl,n,o.bundle.root);Object.assign(o.digests,r.digests);for(let a of e.crossCheckMetadataBaseUrls??[]){let l=await va(t,e,a),u=await xa(t,e,a,n,l.bundle.root);Object.assign(l.digests,u.digests);let f=new Set([...Object.keys(o.digests),...Object.keys(l.digests)]);for(let m of f)if(l.digests[m]!==o.digests[m])throw new Error(`cross-channel metadata mismatch for ${m}`)}let c=Qi(n,s,r.roots,i);return{bundle:o.bundle,recoveredRoot:c,rootChain:r.roots}}function Fa(t){let e=uo(ae.resolve(t.trustedRootPath));if(!e)throw new Error("trusted root is missing or unreadable");return e}function Qd(t,e){return Math.max(0,(e.getTime()-Date.parse(t.targets.signed.generatedAt))/36e5)}async function La(t){let e=Cn(t);if(!e)return _e(t,"trust-unconfigured");let n=t.env??process.env;if(!e.enabled||n.KNODIN_UPDATE_CHECK==="0")return _e(t,"disabled");if(e.offline||n.KNODIN_OFFLINE==="1")return _e(t,"offline");let s=t.now?.()??new Date,i=$s(t.stateHome);try{let o=Fa(e),{bundle:r,recoveredRoot:c,rootChain:a}=await Yd(t,e,o,e.trustedRootSha256,s),l=Zd(r,e),u=Es(r,{trustedRoot:c,trustedRootSha256:Ie("sha256").update(je(c)).digest("hex"),targetPath:l,previous:i?.trustedMetadata,now:s}),f=Qd(r,s),m=u.target.custom.version,d={schemaVersion:1,installedVersion:t.currentVersion,latestTrustedVersion:m,channel:u.target.custom.channel,checkedAt:s.toISOString(),releaseGeneratedAt:r.targets.signed.generatedAt,targetPath:l,trustedMetadata:u.state,trustedRoot:u.rootEnvelope,rollback:i?.rollback,lastApplied:i?.lastApplied};return xs(gt(t.stateHome),d),{config:e,bundle:r,recoveredRoot:c,rootChain:a,target:u.target,targetPath:l,state:d,result:{..._e(t,_s(m,t.currentVersion)>0?"update-available":"up-to-date"),latestTrustedVersion:m,channel:u.target.custom.channel,releaseAgeHours:f,checkedAt:s.toISOString(),networkUsed:!0,acknowledged:e.acknowledgedVersion===m}}}catch(o){return{..._e(t,"check-failed"),latestTrustedVersion:i?.latestTrustedVersion,channel:i?.channel,checkedAt:s.toISOString(),networkUsed:!0,error:{code:o instanceof Error&&"code"in o?String(o.code):"verification-failed",message:o instanceof Error?o.message:String(o)}}}}function mo(t){let e=Cn(t);if(!e)return _e(t,"trust-unconfigured");if(!e.enabled)return _e(t,"disabled");if(e.offline)return _e(t,"offline");let n=$s(t.stateHome);if(!n)return _e(t,"never-checked");let s=t.now?.()??new Date;return{..._e(t,_s(n.latestTrustedVersion,t.currentVersion)>0?"update-available":"up-to-date"),latestTrustedVersion:n.latestTrustedVersion,channel:n.channel,releaseAgeHours:Math.max(0,(s.getTime()-Date.parse(n.releaseGeneratedAt))/36e5),checkedAt:n.checkedAt,acknowledged:e.acknowledgedVersion===n.latestTrustedVersion}}async function Ow(t){let e=await La(t);return"result"in e?e.result:e}function Iw(t){let e=Cn(t);return{...mo(t),networkUsed:!1,policy:e?.policy??{mode:"notify-only",minimumReleaseAgeHours:0,approvedChannels:[]},metadataBaseUrl:e?new URL(e.metadataBaseUrl).origin:null,enterpriseMirrorOnly:e?.enterpriseMirrorOnly===!0,guarantees:["unsigned sources are never eligible","metadata and artifacts are bounded, signed, and digest-verified","repository identity, source paths, and usage data are never sent","manager-owned files are changed only through their owning package manager"],limitations:["production use remains unavailable until the offline root ceremony installs a trust anchor","Homebrew activation is recommendation-only until a signed bottle rollback adapter is certified"]}}function ef(t,e,n,s,i){if(!t.policy.approvedChannels.includes(t.channel))return"release channel is not approved";if(s<t.policy.minimumReleaseAgeHours)return"release has not reached the minimum age";if(t.policy.mode==="notify-only")return"policy is notify-only";if(t.policy.mode==="download-verify-only")return null;let o=nn(e),r=nn(n);if(!o||!r||_s(n,e)<=0)return"release is not a monotonic semantic version update";if(o.core[0]!==r.core[0])return"major updates require manual approval";if(t.policy.mode==="apply-patch"&&o.core[1]!==r.core[1])return"policy permits patch releases only";let c=t.policy.maintenanceWindows;if(c&&c.length>0){let a=`${String(i.getUTCHours()).padStart(2,"0")}:${String(i.getUTCMinutes()).padStart(2,"0")}`;if(!c.some(l=>l.days.includes(i.getUTCDay())&&a>=l.startUtc&&a<l.endUtc))return"outside the configured maintenance window"}return null}function Na(t){let e={provenance:t.provenanceSha256,sbom:t.sbomSha256,sbomAttestation:t.sbomAttestationSha256,releaseAttestation:t.releaseAttestationSha256};for(let[n,s]of Object.entries(e))if(!s)throw new Error(`signed ${n} digest is required before apply`);return e}function Ca(t,e){for(let n of Object.keys(e))if(Ie("sha256").update(t[n]).digest("hex")!==e[n])throw new Error(`${n} digest mismatch`)}function tf(t,e){let n=ae.resolve(e),s=se.realpathSync(n);for(let[i,o]of Object.entries(t)){if(!o.startsWith(`${n}${ae.sep}`))throw new Error(`${i} rollback evidence is outside quarantine`);let r=ae.join(s,ae.relative(n,o));if(se.realpathSync(o)!==r)throw new Error(`${i} rollback evidence traverses a quarantine symlink`);let c=se.lstatSync(o);if(!c.isFile()||c.isSymbolicLink())throw new Error(`${i} rollback evidence is not a regular file`);let a=i==="artifact"?ao:tn;if(c.size===0||c.size>a)throw new Error(`${i} rollback evidence exceeds its byte budget`)}}async function Ta(t,e,n,s,i){let o=fo(e.targetPathTemplate,i),r=Es(n,{trustedRoot:s,trustedRootSha256:Ie("sha256").update(je(s)).digest("hex"),targetPath:o,now:t.now?.()??new Date}),c=Na(r.target.custom),a=await ct(t,e,at(e.metadataBaseUrl,o),ao);ks(a,r.target);let l={provenance:`${o}.provenance.json`,sbom:`${o}.sbom.cdx.json`,sbomAttestation:`${o}.sbom.attestation.json`,releaseAttestation:`${o}.release-attestation.json`},u={provenance:await ct(t,e,at(e.metadataBaseUrl,l.provenance),tn),sbom:await ct(t,e,at(e.metadataBaseUrl,l.sbom),tn),sbomAttestation:await ct(t,e,at(e.metadataBaseUrl,l.sbomAttestation),tn),releaseAttestation:await ct(t,e,at(e.metadataBaseUrl,l.releaseAttestation),tn)};Ca(u,c);let f=oo(As(u.releaseAttestation,"release attestation"),{artifact:a,provenance:u.provenance,sbom:u.sbom,sbomAttestation:u.sbomAttestation});if(f.status!=="verified")throw new Error(`release attestation is ${f.status}; apply requires verified`);if(f.version!==r.target.custom.version||f.sourceCommit!==r.target.custom.sourceCommit)throw new Error("release attestation version or source commit mismatch");if(f.provenance.path!==ae.basename(l.provenance)||f.sbom.path!==ae.basename(l.sbom)||f.sbom.attestationPath!==ae.basename(l.sbomAttestation))throw new Error("release attestation evidence path mismatch");for(let R of e.crossCheckMetadataBaseUrls??[]){let v=await ct(t,e,at(R,o),ao);ks(v,r.target);for(let[S,E]of Object.entries(l)){let $=await ct(t,e,at(R,E),tn),p=Ie("sha256").update(u[S]).digest("hex");if(Ie("sha256").update($).digest("hex")!==p)throw new Error(`cross-channel ${S} mismatch`)}}let m=ae.join(ae.dirname(gt(t.stateHome)),"quarantine");se.mkdirSync(m,{recursive:!0,mode:448});let d=se.lstatSync(m);if(!d.isDirectory()||d.isSymbolicLink())throw new Error("quarantine root is not a private directory");try{se.chmodSync(m,448)}catch{}let y=se.mkdtempSync(ae.join(m,`${i}-`));try{se.chmodSync(y,448)}catch{}let g=ae.join(y,ae.basename(o)),h=`${g}.provenance.json`,w=`${g}.sbom.cdx.json`,k=`${g}.sbom.attestation.json`,_=`${g}.release-attestation.json`;return se.writeFileSync(g,a,{mode:384,flag:"wx"}),se.writeFileSync(h,u.provenance,{mode:384,flag:"wx"}),se.writeFileSync(w,u.sbom,{mode:384,flag:"wx"}),se.writeFileSync(k,u.sbomAttestation,{mode:384,flag:"wx"}),se.writeFileSync(_,u.releaseAttestation,{mode:384,flag:"wx"}),{artifactPath:g,provenancePath:h,sbomPath:w,sbomAttestationPath:k,releaseAttestationPath:_,targetPath:o,attestedRollback:f.rollback}}function nf(t,e,n){let s=Ie("sha256").update(se.readFileSync(n.artifactPath)).digest("hex");if(t.attestedRollback.version!==e||t.attestedRollback.targetPath!==n.targetPath||t.attestedRollback.artifactSha256!==s)throw new Error("release attestation rollback target mismatch")}function co(t,e){return t==="npm"?["npm","install","--global","--ignore-scripts",e]:null}async function Ra(t,e,n){let s=t.runManager;if(!s)throw new Error("owning package manager adapter is unavailable");if((await s(e)).status!==0)throw new Error(n);if(!await(t.healthCheck??(async()=>!1))())throw new Error("automatic rollback completed but the restored installation is unhealthy");return"rolled-back"}async function sf(t,e,n){let s=t.runManager;if(!s)throw new Error("owning package manager adapter is unavailable");return(await s(e)).status!==0?Ra(t,n,"package manager activation and automatic rollback both failed"):await(t.healthCheck??(async()=>!1))()?"applied":Ra(t,n,"health check failed and automatic rollback failed")}async function Mw(t){let e=await La(t);if(!("result"in e))return e;if(e.result.status!=="update-available")return e.result;let n=t.now?.()??new Date,s=ef(e.config,t.currentVersion,e.target.custom.version,e.result.releaseAgeHours??0,n);if(s)return{...e.result,status:"policy-blocked",remediation:s};try{let i=await Ta(t,e.config,e.bundle,e.recoveredRoot,e.target.custom.version);if(e.config.policy.mode==="download-verify-only")return{...e.result,status:"downloaded",artifactPath:i.artifactPath};let o=await Ta(t,e.config,e.bundle,e.recoveredRoot,t.currentVersion);if(nf(i,t.currentVersion,o),!await(t.smokeTest??(async()=>!1))(i.artifactPath))return{...e.result,status:"policy-blocked",error:{code:"smoke-failed",message:"quarantined artifact failed its smoke test"}};let r=co(Rs(t),i.artifactPath);if(!r||!t.runManager)return{...e.result,status:"manager-action-required",artifactPath:i.artifactPath,remediation:"Use the owning package manager with the exact verified quarantined artifact."};let{attestedRollback:c,...a}=o,l={...e.state,rollback:{version:t.currentVersion,...a,bundle:e.bundle,rootChain:e.rootChain}};xs(gt(t.stateHome),l);let u=co(Rs(t),o.artifactPath);if(!u)throw new Error("owning package manager cannot consume rollback artifact");return await sf(t,r,u)==="rolled-back"?{...e.result,status:"rolled-back",artifactPath:o.artifactPath}:(xs(gt(t.stateHome),{...l,installedVersion:e.target.custom.version,lastApplied:{version:e.target.custom.version,artifactPath:i.artifactPath,appliedAt:n.toISOString()}}),{...e.result,status:"applied",artifactPath:i.artifactPath})}catch(i){return{...e.result,status:"policy-blocked",error:{code:"apply-refused",message:i instanceof Error?i.message:String(i)}}}}function of(t,e,n){let s=n.rollback;if(!s)return!1;let i=ae.join(ae.dirname(gt(t.stateHome)),"quarantine");try{let o={artifact:ae.resolve(s.artifactPath),provenance:ae.resolve(s.provenancePath),sbom:ae.resolve(s.sbomPath),sbomAttestation:ae.resolve(s.sbomAttestationPath),releaseAttestation:ae.resolve(s.releaseAttestationPath)};tf(o,i);let r=Fa(e),c=Qi(r,e.trustedRootSha256,s.rootChain,new Date(n.checkedAt)),a=Es(s.bundle,{trustedRoot:c,trustedRootSha256:Ie("sha256").update(je(c)).digest("hex"),targetPath:s.targetPath,now:new Date(n.checkedAt)});if(a.target.custom.version!==s.version)return!1;let l={artifact:se.readFileSync(o.artifact),provenance:se.readFileSync(o.provenance),sbom:se.readFileSync(o.sbom),sbomAttestation:se.readFileSync(o.sbomAttestation),releaseAttestation:se.readFileSync(o.releaseAttestation)};ks(l.artifact,a.target);let u=Na(a.target.custom);Ca({provenance:l.provenance,sbom:l.sbom,sbomAttestation:l.sbomAttestation,releaseAttestation:l.releaseAttestation},u);let f=oo(As(l.releaseAttestation,"release attestation"),{artifact:l.artifact,provenance:l.provenance,sbom:l.sbom,sbomAttestation:l.sbomAttestation});return f.status==="verified"&&f.version===a.target.custom.version&&f.sourceCommit===a.target.custom.sourceCommit}catch{return!1}}async function Pw(t){let e=$s(t.stateHome),n=Cn(t);if(!n)return _e(t,"trust-unconfigured");if(!e?.rollback||!of(t,n,e))return _e(t,"rollback-unavailable");let s=co(Rs(t),e.rollback.artifactPath);return!s||!t.runManager?{..._e(t,"manager-action-required"),artifactPath:e.rollback.artifactPath}:(await t.runManager(s)).status!==0||!await(t.healthCheck??(async()=>!1))()?{..._e(t,"rollback-unavailable"),error:{code:"rollback-failed",message:"owning package manager or health check rejected rollback"}}:(xs(gt(t.stateHome),{...e,installedVersion:e.rollback.version}),{..._e(t,"rolled-back"),artifactPath:e.rollback.artifactPath})}import rf from"node:child_process";import yt from"node:fs";import af from"node:os";import ve from"node:path";function cf(t,e,n={}){let s=rf.spawnSync(t,e,{encoding:"utf-8",input:n.input,timeout:5e3,stdio:["pipe","pipe","pipe"]});return{status:s.status,stdout:s.stdout??"",stderr:s.stderr??s.error?.message??""}}function lf(t,e){let n=[["mise",e.MISE_DATA_DIR??e.MISE_ENV,"MISE_DATA_DIR or MISE_ENV is set"],["volta",e.VOLTA_HOME,"VOLTA_HOME is set"],["nvm",e.NVM_BIN??e.NVM_DIR,"NVM_BIN or NVM_DIR is set"],["fnm",e.FNM_DIR??e.FNM_MULTISHELL_PATH,"FNM_DIR or FNM_MULTISHELL_PATH is set"],["asdf",e.ASDF_DIR??e.ASDF_DATA_DIR,"ASDF_DIR or ASDF_DATA_DIR is set"],["homebrew",e.HOMEBREW_PREFIX,"HOMEBREW_PREFIX is set"]];for(let[i,o,r]of n)if(o)return{name:i,confidence:"high",evidence:[r]};let s=t.toLowerCase();for(let[i,o]of[["/.local/share/mise/","mise"],["/.volta/","volta"],["/.nvm/","nvm"],["/fnm","fnm"],["/.asdf/","asdf"],["/homebrew/","homebrew"]])if(s.includes(i))return{name:o,confidence:"medium",evidence:[`resolved executable path contains ${i}; path heuristic only`]};return{name:"unknown",confidence:"low",evidence:["no manager-owned environment evidence; executable path alone is inconclusive"]}}function uf(t){let e=[ve.resolve(t)];for(let n=0;n<16;n++){let s=e.at(-1);if(!s)break;try{if(!yt.lstatSync(s).isSymbolicLink()){let r=yt.realpathSync(s);r!==s&&e.push(r);break}let i=yt.readlinkSync(s),o=ve.resolve(ve.dirname(s),i);if(e.includes(o))break;e.push(o)}catch{break}}return e}function df(t){let e=[];for(let n of(t.PATH??"").split(ve.delimiter)){if(!n)continue;let s=ve.join(n,process.platform==="win32"?"knodin.cmd":"knodin");try{yt.accessSync(s,yt.constants.X_OK);let i=yt.realpathSync(s);e.includes(i)||e.push(i)}catch{}}return e}function ff(t){let[e,...n]=t;if(!e)return"";let s=ve.basename(e).toLowerCase();if(s==="node"||s==="node.exe"||s==="bun"||s==="tsx"||s==="tsx.cmd"){let i=new Set(["--import","--loader","--experimental-loader","--require","-r"]);for(let o=0;o<n.length;o++){let r=n[o];if(i.has(r)){o++;continue}if(!r.startsWith("-"))return r}}return e}function mf(t){let e=t.trim();try{let n=new URL(e);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return"unknown"}}function On(t,e){try{let n=yt.readFileSync(e,"utf-8");if(t==="claude"&&ve.basename(e)===".claude.json"){let o=n.includes('"knodin"');return{agent:t,file:e,present:o,command:o?"knodin":null,args:["serve"]}}if(e.endsWith(".toml")){let o=n.indexOf('[mcp_servers."knodin"]'),r=o>=0?n.slice(o):"",c=r.indexOf(`
102
+ [`,1),a=c>=0?r.slice(0,c):r,l=/^[ \t]*command[ \t]*=[ \t]*"([^"\r\n]+)"/m.exec(a)?.[1],u=/^[ \t]*args[ \t]*=[ \t]*\[([^\]]*)\]/m.exec(a)?.[1]?.split(",").map(f=>f.trim().replace(/^"|"$/g,"")).filter(Boolean);return{agent:t,file:e,present:o>=0,command:l??null,args:u??[]}}let i=JSON.parse(n).mcpServers?.knodin;return{agent:t,file:e,present:i!==void 0,command:typeof i?.command=="string"?i.command:null,args:Array.isArray(i?.args)?i.args.filter(o=>typeof o=="string"):[]}}catch{return{agent:t,file:e,present:!1,command:null,args:[]}}}function pf(t){return[{agent:"claude",file:".mcp.json"},{agent:"codex",file:".codex/config.toml"},{agent:"gemini",file:".gemini/settings.json"},{agent:"antigravity",file:".agents/mcp_config.json"}].map(({agent:n,file:s})=>On(n,ve.join(t,s)))}function hf(t){return[On("claude",ve.join(t,".claude.json")),On("codex",ve.join(t,".codex","config.toml")),On("gemini",ve.join(t,".gemini","settings.json")),On("antigravity",ve.join(t,".agents","mcp_config.json"))]}function gf(t){let e=ve.dirname(t);for(let n=0;n<6;n++){try{let i=JSON.parse(yt.readFileSync(ve.join(e,"package.json"),"utf-8"));if(i.name==="knodin"&&typeof i.version=="string")return i.version}catch{}let s=ve.dirname(e);if(s===e)break;e=s}return"unknown"}function yf(t,e){return t==="mise"?`mise use --global npm:knodin@${e}`:t==="volta"?`volta install knodin@${e}`:t==="homebrew"?"brew update && brew upgrade knodin":t==="nvm"?`nvm use 24 && npm install --global --ignore-scripts knodin@${e}`:t==="fnm"?`fnm use 24 && npm install --global --ignore-scripts knodin@${e}`:t==="asdf"?`asdf set nodejs 24 && npm install --global --ignore-scripts knodin@${e}`:`npm install --global --ignore-scripts knodin@${e}`}function bf(t){let e=t.split(/\r?\n/).filter(Boolean).flatMap(c=>{try{return[JSON.parse(c)]}catch{return[]}}),n=e.find(({id:c})=>c===1),s=e.find(({id:c})=>c===2),i=n?.result,r=(s?.result?.tools??[]).flatMap(({name:c})=>typeof c=="string"?[c]:[]);return{initialize:i?.serverInfo?"ok":"failed",toolsList:r.length>0?"ok":"failed",serverVersion:typeof i?.serverInfo?.version=="string"?i.serverInfo.version:void 0,toolNames:r}}function wf(t,e){let n=[JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2025-11-25",capabilities:{},clientInfo:{name:"knodin-doctor",version:"1"}}}),JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized",params:{}}),JSON.stringify({jsonrpc:"2.0",id:2,method:"tools/list",params:{}}),""].join(`
103
+ `),[s,...i]=t;if(!s)return{initialize:"failed",toolsList:"failed",toolNames:[],stderr:"no command"};let o=e(s,i,{input:n});return{...bf(o.stdout),stderr:o.status===0?void 0:o.stderr}}async function Gw(t,e){let n=ve.resolve(t),s=e.env??process.env,i=e.run??cf,o=ff(e.runtimeCommand),r=uf(o),c=df(s),a=i("npm",["config","get","prefix"]),l=i("npm",["config","get","registry"]),u=wf(e.runtimeCommand,i),f=u.serverVersion,m=Xt(n),d=Fr(),y=pf(n),g=hf(e.homeDir??af.homedir()),h=y.filter(({agent:_})=>e.client===void 0||e.client===_).map(_=>{let R=g.find(({agent:S})=>S===_.agent),v=_.present||R?.present===!0;return{client:_.agent,detected:d.includes(_.agent),repository:_,personal:R,server:{initialize:u.initialize,toolsList:u.toolsList,toolNames:u.toolNames},activeSessionExposure:"unknown",note:_.agent==="claude"?".mcp.json is Claude project configuration, not a universal MCP registration.":"Configuration presence does not prove that the active client session loaded it.",remediation:v?"Restart or reload the client, then verify its active tools list.":`Run \`knodin configure --scope personal\` or \`knodin configure --scope team\` for ${_.agent}.`}}),w=lf(r.at(-1)??o,s),k=gf(r.at(-1)??o);return{schemaVersion:1,status:e.graph.status==="healthy"&&u.initialize==="ok"&&u.toolsList==="ok"&&c.length<=1?"healthy":"attention-required",versions:{package:k,cli:f??"unknown",source:e.currentVersion,agree:f===e.currentVersion&&(k==="unknown"||k===e.currentVersion)},runtime:{node:process.version,platform:process.platform,arch:process.arch},npm:{prefix:a.status===0?a.stdout.trim():"unknown",registry:l.status===0?mf(l.stdout):"unknown"},manager:w,executable:{resolved:r.at(-1)??o,chain:r,candidates:c,conflicts:c.filter(_=>_!==r.at(-1))},agents:{detected:d,configuredCommands:y,clients:h},mcp:u,lifecycle:m,graph:e.graph,update:mo({currentVersion:e.currentVersion,stateHome:e.cacheHome,installMethod:w.name,env:s}),remediation:{manager:yf(w.name,e.currentVersion),duplicates:c.length>1?"Remove only the unintended manager-owned installation, then rerun `knodin doctor`.":null,graph:e.graph.status==="healthy"?null:"Run `knodin repair`, then `knodin status --deep`."}}}import Sf from"node:child_process";import Ft from"node:fs";import ho from"node:path";function Oa(t){return ho.join(ho.resolve(t),".knodin","index-activity.json")}var po=2e3,Ef=10080*60*1e3,kf=new Set(["starting","collecting-files","indexing-files","embedding-model","embedding-symbols","finalizing","verifying","completed"]);function vf(t){try{return process.kill(t,0),!0}catch{return!1}}function xf(t){if(t===process.pid)return Date.now()-process.uptime()*1e3;if(process.platform==="win32")return null;try{let e=Sf.execFileSync("ps",["-o","lstart=","-p",String(t)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),n=Date.parse(e.trim());return Number.isFinite(n)?n:null}catch{return null}}function Jw(t){let e=Oa(t),n=new Date().toISOString(),s=i=>{Ft.mkdirSync(ho.dirname(e),{recursive:!0});let o=`${e}.${process.pid}.tmp`;try{Ft.writeFileSync(o,`${JSON.stringify(i)}
104
+ `,"utf8"),Ft.renameSync(o,e)}finally{Ft.rmSync(o,{force:!0})}};return{start(){s({pid:process.pid,startedAt:n,updatedAt:n,phase:"starting",phaseCompleted:0,message:"Opening local graph database"})},update(i){s({pid:process.pid,startedAt:n,updatedAt:new Date().toISOString(),phase:i.phase,phaseCompleted:i.phaseCompleted,...i.phaseTotal===void 0?{}:{phaseTotal:i.phaseTotal},message:i.message})},stop(){try{JSON.parse(Ft.readFileSync(e,"utf8")).pid===process.pid&&Ft.unlinkSync(e)}catch{}}}}function Ia(t){try{let e=JSON.parse(Ft.readFileSync(Oa(t),"utf8"));if(!Number.isInteger(e.pid)||e.pid<=0||!vf(e.pid))return null;let n=Date.now(),s=Date.parse(e.startedAt),i=Date.parse(e.updatedAt);if(!Number.isFinite(s)||!Number.isFinite(i)||s>n+po||i<s||i>n+po||n-s>Ef||!kf.has(e.phase)||!Number.isFinite(e.phaseCompleted)||e.phaseCompleted<0||e.phaseTotal!==void 0&&(!Number.isFinite(e.phaseTotal)||e.phaseTotal<0||e.phaseCompleted>e.phaseTotal)||typeof e.message!="string")return null;let o=xf(e.pid);return o!==null&&o>s+po?null:e}catch{return null}}import Tf from"node:fs";import{createRequire as Rf}from"node:module";import In from"node:path";import{fileURLToPath as $f}from"node:url";var _f=Rf(import.meta.url),sn=In.dirname($f(import.meta.url));for(;!Tf.existsSync(In.join(sn,"package.json"))&&sn!==In.parse(sn).root;)sn=In.dirname(sn);var Ma=_f(In.join(sn,"package.json")),Mn=typeof Ma.version=="string"?Ma.version:"0.0.0";import st from"node:child_process";import gn from"node:crypto";import q from"node:fs";import{createRequire as gm}from"node:module";import P from"node:path";import{fileURLToPath as ym}from"node:url";import bm from"chokidar";import we from"web-tree-sitter";import bt from"node:fs";import xe from"node:path";var go=new Set([".ts",".tsx",".js",".jsx",".mts",".cts"]);function lt(t,e,n){return{pattern:t,target:e,count:0,results:[],adapter:"none",available:!1,readOnly:!0,reason:n}}function Af(t,e){let n=e.match(/^(.*?)(?::(\d+):(\d+))?$/);if(!n?.[1])return;let s=n[1].replaceAll("\\","/"),i=xe.resolve(t,s),o=xe.relative(t,i);if(!(o.startsWith("..")||xe.isAbsolute(o))&&n[2]===void 0==(n[3]===void 0))return{file:o.replaceAll(xe.sep,"/"),absoluteFile:i,...n[2]?{line:Number(n[2]),column:Number(n[3])}:{}}}function Ff(t,e){let n=r=>{try{let c=xe.relative(t,bt.realpathSync(r));return!c.startsWith("..")&&!xe.isAbsolute(c)}catch{return!1}},s=e.findConfigFile(t,e.sys.fileExists,"tsconfig.json");if(s){let r=e.readConfigFile(s,e.sys.readFile);if(!r.error)return e.parseJsonConfigFileContent(r.config,e.sys,xe.dirname(s)).fileNames.filter(a=>go.has(xe.extname(a))&&n(a))}let i=[],o=r=>{for(let c of bt.readdirSync(r,{withFileTypes:!0})){if(c.name==="node_modules"||c.name===".git"||c.name===".knodin")continue;let a=xe.join(r,c.name);c.isDirectory()?o(a):c.isFile()&&go.has(xe.extname(c.name))&&i.push(a)}};return o(t),i}function Lf(t,e,n){let s=new Map(e.map(o=>[o,"0"])),i={target:n.ScriptTarget.ES2022,module:n.ModuleKind.NodeNext,moduleResolution:n.ModuleResolutionKind.NodeNext,strict:!0,skipLibCheck:!0};return n.createLanguageService({getCompilationSettings:()=>i,getScriptFileNames:()=>e,getScriptVersion:o=>s.get(o)??"0",getScriptSnapshot:o=>{try{return n.ScriptSnapshot.fromString(bt.readFileSync(o,"utf-8"))}catch{return}},getCurrentDirectory:()=>t,getDefaultLibFileName:o=>n.getDefaultLibFilePath(o),fileExists:n.sys.fileExists,readFile:n.sys.readFile,readDirectory:n.sys.readDirectory,directoryExists:n.sys.directoryExists,getDirectories:n.sys.getDirectories})}function Pa(t,e){return xe.relative(t,e).replaceAll(xe.sep,"/")}function Nf(t,e,n){if(!Number.isInteger(e)||!Number.isInteger(n)||e<1||n<1)return;let s=t.split(`
105
+ `);if(!(e>s.length||n>s[e-1].length+1))return s.slice(0,e-1).reduce((i,o)=>i+o.length+1,0)+n-1}function Cf(t,e,n){let s=e.file,i=s&&e.start!==void 0?s.getLineAndCharacterOfPosition(e.start):void 0;return{file:s?Pa(t,s.fileName):void 0,line:i?i.line+1:void 0,column:i?i.character+1:void 0,kind:n.DiagnosticCategory[e.category].toLowerCase(),message:n.flattenDiagnosticMessageText(e.messageText,`
106
+ `),code:e.code}}function Of(t,e,n){return(e??[]).map(s=>{let i=bt.readFileSync(s.fileName,"utf-8"),o=n.createSourceFile(s.fileName,i,n.ScriptTarget.Latest).getLineAndCharacterOfPosition(s.textSpan.start);return{file:Pa(t,s.fileName),line:o.line+1,column:o.character+1,kind:s.kind,symbol:"name"in s?s.name:void 0}})}async function Da(t,e,n){let s;try{s=await import("typescript")}catch{return lt(t,e,"No local TypeScript language-service adapter is installed; install TypeScript to enable this read-only query.")}let i;try{i=bt.realpathSync(n)}catch{return lt(t,e,"Repository path must be an accessible directory.")}let o=Af(n,e);if(!o||!bt.existsSync(o.absoluteFile))return lt(t,e,"Target must be an existing repo-relative file, optionally with :line:column.");if(!go.has(xe.extname(o.absoluteFile)))return lt(t,e,`No local LSP adapter is installed for ${xe.extname(o.absoluteFile)||"this file type"}.`);let r;try{r=bt.realpathSync(o.absoluteFile);let l=xe.relative(i,r);if(l.startsWith("..")||xe.isAbsolute(l))return lt(t,e,"Target must resolve inside the repository.")}catch{return lt(t,e,"Target must be a readable regular file.")}if(t!=="lsp_diagnostics"&&(o.line===void 0||o.column===void 0))return lt(t,e,"Navigation queries require target syntax file:line:column.");let c=Ff(i,s);c.includes(r)||c.push(r);let a=Lf(i,c,s);try{let l;if(t==="lsp_diagnostics")l=[...a.getSyntacticDiagnostics(r),...a.getSemanticDiagnostics(r)].map(u=>Cf(i,u,s));else{let u=o.line,f=o.column;if(u===void 0||f===void 0)return lt(t,e,"Navigation queries require target syntax file:line:column.");let m=Nf(bt.readFileSync(r,"utf-8"),u,f);if(m===void 0)return lt(t,e,"Target line and column must identify a position inside the source file.");l=Of(i,t==="lsp_implementations"?a.getImplementationAtPosition(r,m):a.getDefinitionAtPosition(r,m),s)}return{pattern:t,target:e,count:l.length,results:l.slice(0,100),hasMore:l.length>100||void 0,adapter:"typescript-language-service",available:!0,readOnly:!0}}finally{a.dispose()}}import If from"node:os";import on from"node:path";var Fs=null,ja=null,Ls=new Set,za=!1,Ba=384,Mf="https://huggingface.co/";function Pf(t={}){let e=t.env??process.env,n=e.KNODIN_MODEL_CACHE?.trim();if(n)return on.resolve(n);let s=t.platform??process.platform,i=t.home??If.homedir();return s==="win32"?on.join(e.LOCALAPPDATA||on.join(i,"AppData","Local"),"knodin","models"):s==="darwin"?on.join(i,"Library","Caches","knodin","models"):on.join(e.XDG_CACHE_HOME||on.join(i,".cache"),"knodin","models")}function Df(t=process.env){let e=t.KNODIN_MODEL_HOST?.trim()||Mf,n;try{n=new URL(e)}catch{throw new Error(`KNODIN_MODEL_HOST must be an absolute HTTP(S) URL: ${e}`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`KNODIN_MODEL_HOST must use HTTP(S): ${e}`);return n.hash="",n.search="",n.href.endsWith("/")?n.href:`${n.href}/`}var jf=0;function zf(t){return ja?(t?.({status:"ready",name:"local test embedder"}),Promise.resolve(ja)):(t&&za?t({status:"ready",name:"Xenova/all-MiniLM-L6-v2"}):t&&Ls.add(t),Fs||(Fs=(async()=>{try{let{env:e,pipeline:n}=await import("@huggingface/transformers");e.cacheDir=Pf(),e.remoteHost=Df();let s=o=>{for(let r of Ls)try{r(o)}catch{}};s({status:"loading",name:"Xenova/all-MiniLM-L6-v2"});let i=await n("feature-extraction","Xenova/all-MiniLM-L6-v2",{progress_callback:s});return jf++,za=!0,s({status:"ready",name:"Xenova/all-MiniLM-L6-v2"}),Ls.clear(),i}catch(e){throw Fs=null,Ls.clear(),console.error("Failed to initialize Hugging Face embedding pipeline:",e),e}})()),Fs)}async function Ns(t,e){if(t.length===0)return[];let s=await(await zf(e))([...t],{pooling:"mean",normalize:!0}),i=s.data instanceof Float32Array?s.data:Float32Array.from(s.data),o=s.dims;if(o?.length!==2||o[0]!==t.length||o[1]!==Ba)throw new Error(`Unexpected batched embedding shape: expected [${t.length}, ${Ba}], got ${JSON.stringify(o)}`);let r=o[1];if(i.length!==t.length*r)throw new Error(`Unexpected batched embedding data length: expected ${t.length*r}, got ${i.length}`);return t.map((c,a)=>i.slice(a*r,(a+1)*r))}async function yo(t){return(await Ns([t]))[0]}function Cs(t,e){if(t.length!==e.length)throw new Error(`Embedding dimension mismatch: query has ${t.length} dims, target has ${e.length}`);let n=0,s=t.length;for(let i=0;i<s;i++)n+=t[i]*e[i];return n}var Hf=16,Uf=200,Wf=200,qf=2654435769;function Gf(t){let e=t>>>0;return()=>{e|=0,e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var bo=class{nodes=[];entryPoint=-1;maxLevel=-1;M;Mmax0;efConstruction;mL;rand;constructor(e){this.M=e.M??Hf,this.Mmax0=this.M*2,this.efConstruction=e.efConstruction??Uf,this.mL=1/Math.log(this.M),this.rand=Gf(e.seed??qf)}get size(){return this.nodes.length}randomLevel(){return Math.floor(-Math.log(this.rand()||Number.MIN_VALUE)*this.mL)}sim(e,n){return Cs(e,n)}insert(e,n){let s=this.randomLevel(),i=this.nodes.length,o={id:e,vec:n,level:s,neighbors:Array.from({length:s+1},()=>[])};if(this.nodes.push(o),this.entryPoint===-1){this.entryPoint=i,this.maxLevel=s;return}let r=this.entryPoint;for(let c=this.maxLevel;c>s;c--)r=this.greedyDescend(n,r,c).node;for(let c=Math.min(s,this.maxLevel);c>=0;c--){let a=this.searchLayer(n,[r],this.efConstruction,c).candidates,l=c===0?this.Mmax0:this.M,u=this.selectNeighbors(a,l);o.neighbors[c]=u.slice();for(let f of u){let m=this.nodes[f];m.neighbors[c].push(i);let d=c===0?this.Mmax0:this.M;if(m.neighbors[c].length>d){let y=m.neighbors[c].map(g=>({idx:g,score:this.sim(m.vec,this.nodes[g].vec)}));y.sort((g,h)=>h.score-g.score),m.neighbors[c]=y.slice(0,d).map(g=>g.idx)}}r=a.length>0?a[0].idx:r}s>this.maxLevel&&(this.maxLevel=s,this.entryPoint=i)}greedyDescend(e,n,s){let i=n,o=this.sim(e,this.nodes[i].vec),r=1,c=!0;for(;c;){c=!1;for(let a of this.nodes[i].neighbors[s]??[]){let l=this.sim(e,this.nodes[a].vec);r++,l>o&&(o=l,i=a,c=!0)}}return{node:i,distanceComputations:r}}searchLayer(e,n,s,i){let o=new Set,r=[],c=[],a=0;for(let u of n){if(o.has(u))continue;o.add(u);let f=this.sim(e,this.nodes[u].vec);a++,r.push({idx:u,score:f}),c.push({idx:u,score:f})}for(r.sort((u,f)=>f.score-u.score),c.sort((u,f)=>u.score-f.score);r.length>0;){let u=r.shift();if(!u)break;let f=c[0];if(f&&u.score<f.score&&c.length>=s)break;for(let m of this.nodes[u.idx].neighbors[i]??[]){if(o.has(m))continue;o.add(m);let d=this.sim(e,this.nodes[m].vec);a++;let y=c[0];(c.length<s||y&&d>y.score)&&(Ha(r,{idx:m,score:d},!0),Ha(c,{idx:m,score:d},!1),c.length>s&&c.shift())}}return{candidates:c.slice().sort((u,f)=>f.score-u.score),visited:a}}selectNeighbors(e,n){return e.slice().sort((s,i)=>i.score-s.score).slice(0,n).map(s=>s.idx)}search(e,n,s){if(this.entryPoint===-1)return{results:[],stats:{visited:0}};let i=Math.max(n,s),o=this.entryPoint,r=0;for(let u=this.maxLevel;u>0;u--){let f=this.greedyDescend(e,o,u);o=f.node,r+=f.distanceComputations}let{candidates:c,visited:a}=this.searchLayer(e,[o],i,0);return r+=a,{results:c.slice(0,s).map(u=>({id:this.nodes[u.idx].id,score:u.score})),stats:{visited:r}}}};function Ha(t,e,n){let s=0,i=t.length;for(;s<i;){let o=s+i>>1;(n?t[o].score>e.score:t[o].score<e.score)?s=o+1:i=o}t.splice(s,0,e)}function Ua(t,e={}){let n=new bo(e);for(let s of t)n.insert(s.id,s.vec);return n}function wo(){return process.env.KNODIN_ANN==="1"}function Wa(){let t=process.env.KNODIN_ANN_EF;if(t){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Wf}import Jf from"node:fs";import Ka from"node:path";import qa from"node:path";var Kf=new Set(["node_modules",".git",".knodin",".gitnexus",".codegraph",".code-review-graph",".aider.tags.cache.v4","dist","build","coverage",".next",".turbo",".svelte-kit","vendor","__pycache__"]);function Xf(t){return Kf.has(t)}function Zf(t,e){return t[e]===".claude"&&t[e+1]==="worktrees"}function Ga(t){for(let e=0;e<t.length;e++)if(Xf(t[e])||Zf(t,e))return!0;return!1}function Lt(t){return!Ga(t.split(/[/\\]/))}function Va(t){return e=>{let n=qa.relative(t,e);return n===""||n.startsWith("..")?!1:Ga(n.split(qa.sep))}}function Xa(t,e){return t<e?-1:t>e?1:0}function Pn(t,e={}){let s=[{absolute:Ka.resolve(t),relative:""}],i=[];for(;s.length>0;){let o=s.pop();if(!o)break;let r;try{r=Jf.readdirSync(o.absolute,{withFileTypes:!0})}catch{continue}r.sort((c,a)=>Xa(c.name,a.name));for(let c of r){let a=o.relative?`${o.relative}/${c.name}`:c.name;if(!Lt(a))continue;let l=Ka.join(o.absolute,c.name);c.isDirectory()?s.push({absolute:l,relative:a}):c.isFile()&&(e.accept?.(a)??!0)&&i.push(a)}}return i.sort(Xa),e.limit===void 0?i:i.slice(0,Math.max(0,e.limit))}import Yf from"node:child_process";import Eo from"node:path";var Os=Object.freeze({maxCommits:250,maxFiles:25,maxRelatedFiles:100,timeoutMs:2e3}),Qf=8*1024*1024,em=8,rn=new Map,Ja="Co-change and coupling are bounded historical correlation, not evidence of causation, defects, ownership, or required remediation.";function Is(t,e,n,s){let i=t??e;if(!Number.isSafeInteger(i)||i<1||i>s)throw new Error(`git history ${n} must be an integer between 1 and ${s}`);return i}function tm(t){return{maxCommits:Is(t.maxCommits,Os.maxCommits,"maxCommits",1e4),maxFiles:Is(t.maxFiles,Os.maxFiles,"maxFiles",1e3),maxRelatedFiles:Is(t.maxRelatedFiles,Os.maxRelatedFiles,"maxRelatedFiles",1e4),timeoutMs:Is(t.timeoutMs,Os.timeoutMs,"timeoutMs",3e4)}}function nm(t){let e=t.replaceAll("\\","/").replace(/^\.\//,"");if(!e||Eo.isAbsolute(e)||e===".."||e.startsWith("../"))throw new Error(`git history file must be repo-relative: ${t}`);return e}function Za(t){let e=t;if(e.code==="ENOENT")return"git-unavailable";if(e.code==="ETIMEDOUT"||e.signal==="SIGTERM"||e.killed)return"timeout";let n=`${String(e.message??t)}
107
+ ${String(e.stderr??"")}`;return/not a git repository/i.test(n)?"not-a-repository":"history-command-failed"}function sm(t){let e=t,n=`${String(e.message??t)}
108
+ ${String(e.stderr??"")}`;return/needed a single revision|ambiguous argument ['"]?HEAD|unknown revision or path/i.test(n)}function So(t,e,n,s,i=[]){return{availability:t,bounds:e,commands:n,commitsAnalyzed:0,filesAnalyzed:i.length,truncated:!1,churn:i.map(o=>({file:o,commitCount:0,commits:[]})),coChange:[],coupling:[],omissions:[s],interpretation:Ja,confidence:t==="unborn"?"exact-bounded-git-history":"unavailable"}}function im(t){let e=[];for(let n of t.split("").slice(1)){let s=n.split("\0").filter(Boolean),[i,...o]=s;if(!i)continue;let[r,c=""]=i.split(""),a=[];for(let l=0;l<o.length;){let u=(o[l++]??"").trim();if(/^[RC]/.test(u)){let f=o[l++],m=o[l++];f&&m&&a.push({status:u,oldPath:f,path:m})}else{let f=o[l++];f&&a.push({status:u,path:f})}}e.push({hash:r,parents:c.split(" ").filter(Boolean),changes:a})}return e}function Ya(t,e,n={}){let s=tm(n),i=[...new Set(e.map(nm))].sort(),o=i.slice(0,s.maxFiles),r=[];i.length>o.length&&r.push({reason:"file-limit",detail:`${i.length-o.length} requested file(s) omitted by maxFiles=${s.maxFiles}`});let c=0,a=v=>(c++,Yf.execFileSync("git",v,{cwd:Eo.resolve(t),encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:s.timeoutMs,maxBuffer:Qf})),l;try{l=a(["rev-parse","--verify","HEAD"]).trim()}catch(v){let S=Za(v);return S==="history-command-failed"&&sm(v)?So("unborn",s,c,{reason:"unborn-repository",detail:"HEAD does not exist; no historical facts are available"},o):So(S==="git-unavailable"?"git-unavailable":S==="not-a-repository"?"not-a-repository":S==="timeout"?"timeout":"unavailable",s,c,{reason:S,detail:"Git HEAD probe failed; history signals were omitted"})}let u=!1;try{u=a(["rev-parse","--is-shallow-repository"]).trim()==="true"}catch{}u&&r.push({reason:"shallow-history",detail:"Only commits present in the shallow clone contribute facts"});let f=`${Eo.resolve(t)}\0${l}\0${i.join("\0")}\0${JSON.stringify(s)}`;if(!u){let v=rn.get(f);if(v)return structuredClone({...v,commands:c})}let m;try{let v=a(["log",`--max-count=${s.maxCommits+1}`,"--find-renames","--name-status","-z","--format=%x1e%H%x1f%P%x00","--no-decorate"]);m=im(v)}catch(v){let S=Za(v);return So(S==="timeout"?"timeout":"unavailable",s,c,{reason:S,detail:"Bounded Git log failed; history signals were omitted"})}m.length>s.maxCommits&&(m=m.slice(0,s.maxCommits),r.push({reason:"commit-limit",detail:`Older commits omitted by maxCommits=${s.maxCommits}`}));let d=new Map(o.map(v=>[v,new Set([v])])),y=new Map(o.map(v=>[v,new Set])),g=new Map;for(let v of m){for(let S of v.changes)if(S.oldPath)for(let E of d.values())S.status.startsWith("R")&&E.has(S.path)&&E.add(S.oldPath);for(let S of o){let E=d.get(S)??new Set;if(v.changes.some(p=>[p.path,p.oldPath].some(F=>F&&E.has(F)))){y.get(S)?.add(v.hash);for(let p of v.changes)for(let F of[p.path,p.oldPath]){if(!F||E.has(F))continue;let L=`${S}\0${F}`,T=g.get(L);T||(T=new Set,g.set(L,T)),T.add(v.hash)}}}}let h=[...g.entries()].map(([v,S])=>{let[E,$]=v.split("\0");return{file:E,relatedFile:$,sharedCommitCount:S.size,commits:[...S].sort()}}).sort((v,S)=>S.sharedCommitCount-v.sharedCommitCount||v.file.localeCompare(S.file)||v.relatedFile.localeCompare(S.relatedFile)),w=h.slice(0,s.maxRelatedFiles);w.length<h.length&&r.push({reason:"related-file-limit",detail:`${h.length-w.length} co-change fact(s) omitted by maxRelatedFiles=${s.maxRelatedFiles}`});let k=o.map(v=>{let S=[...y.get(v)??[]].sort();return{file:v,commitCount:S.length,commits:S}}),_=w.map(v=>{let S=y.get(v.file)?.size??0;return{file:v.file,relatedFile:v.relatedFile,sharedCommitCount:v.sharedCommitCount,fileCommitCount:S,ratio:S===0?0:Number((v.sharedCommitCount/S).toFixed(4))}}),R={availability:u?"shallow":"available",bounds:s,commands:c,commitsAnalyzed:m.length,filesAnalyzed:o.length,truncated:r.some(v=>v.reason.endsWith("limit")),churn:k,coChange:w,coupling:_,omissions:r,interpretation:Ja,confidence:"exact-bounded-git-history"};if(!u)for(rn.set(f,structuredClone(R));rn.size>em;){let v=rn.keys().next().value;if(v===void 0)break;rn.delete(v)}return R}function Qa(){rn.clear()}import Ds from"node:fs";import ut from"node:path";var vo={maxBytes:64*1024*1024,maxFiles:1e4,maxFacts:25e4,timeoutMs:3e4},om=new TextDecoder("utf-8",{fatal:!0}),js=Number.POSITIVE_INFINITY,zs=0;function ie(t){throw js=Number.POSITIVE_INFINITY,zs=0,new Error(`knodin SCIP import: ${t}`)}function ec(){performance.now()>js&&ie(`import exceeded ${zs} ms limit`)}function Nt(t,e){let n=0,s=0;for(let i=0;i<10&&e<t.length;i++){let o=t[e++];if(s<53&&(n+=(o&127)*2**s),(o&128)===0)return[n,e];s+=7}return ie("malformed protobuf varint")}function Bs(t,e){let n=0;for(;n<t.length;){ec();let s;[s,n]=Nt(t,n);let i=Math.floor(s/8),o=s&7;if(i<1&&ie("malformed protobuf field number"),o===0){let r;[r,n]=Nt(t,n),e(i,o,r)}else if(o===2){let r;[r,n]=Nt(t,n),(!Number.isSafeInteger(r)||r<0||n+r>t.length)&&ie("malformed protobuf length"),e(i,o,t.subarray(n,n+r)),n+=r}else o===1?n+=8:o===5?n+=4:ie(`unsupported protobuf wire type ${o}`);n>t.length&&ie("truncated protobuf field")}}function Ms(t,e,n){let s=0,i=0;for(;i<t.length;){ec();let o;[o,i]=Nt(t,i);let r=Math.floor(o/8),c=o&7;if(r<1&&ie("malformed protobuf field number"),c===0)[,i]=Nt(t,i);else if(c===2){let a;if([a,i]=Nt(t,i),(!Number.isSafeInteger(a)||a<0||i+a>t.length)&&ie("malformed protobuf length"),r===e&&++s>n)return s;i+=a}else c===1?i+=8:c===5?i+=4:ie(`unsupported protobuf wire type ${c}`);i>t.length&&ie("truncated protobuf field")}return s}function wt(t,e){let n=[];return Bs(t,(s,i,o)=>{s===e&&i===2&&n.push(om.decode(o))}),n}function St(t,e){let n=[];return Bs(t,(s,i,o)=>{s===e&&i===2&&n.push(o)}),n}function Me(t,e){let n=0,s=!1;return Bs(t,(i,o,r)=>{!s&&i===e&&o===0&&(n=r,s=!0)}),n}function rm(t,e){let n=[];return Bs(t,(s,i,o)=>{if(s===e&&(i===0&&n.push(o),i===2)){let r=o,c=0;for(;c<r.length;){let a;[a,c]=Nt(r,c),n.push(a)}}}),n}function ko(t){t.length!==3&&t.length!==4&&ie("range must contain three or four integers");let[e,n]=t,s=t.length===3?e:t[2],i=t.length===3?t[2]:t[3];return[e,n,s,i].some(o=>!Number.isSafeInteger(o))&&ie("range contains an unsafe integer"),(s<e||s===e&&i<n)&&ie("range is reversed"),{startLine:e,startCol:n,endLine:s,endCol:i}}function am(t){let e=St(t,8)[0],n=St(t,9)[0],s=wt(t,2)[0]??"",i;if(e){let o=Me(e,1);i=ko([o,Me(e,2),Me(e,3)])}else n?i=ko([Me(n,1),Me(n,2),Me(n,3),Me(n,4)]):i=ko(rm(t,1));return s||ie("occurrence is missing its symbol"),{range:i,symbol:s,roles:Me(t,3)}}function cm(t){let e=wt(t,1)[0]??"";return e||ie("symbol information is missing its symbol"),{symbol:e,displayName:wt(t,6)[0]??"",kind:Me(t,5),relationships:St(t,4).map(n=>({symbol:wt(n,1)[0]??"",isReference:Me(n,2)!==0,isImplementation:Me(n,3)!==0,isTypeDefinition:Me(n,4)!==0,isDefinition:Me(n,5)!==0}))}}function lm(t,e){(!e||e.includes("\0")||ut.isAbsolute(e))&&ie(`hostile document path ${JSON.stringify(e)}`);let n=e.replaceAll("\\","/");n.split("/").some(r=>r===".."||r==="")&&ie(`hostile document path ${JSON.stringify(e)}`);let s=ut.resolve(t,n),i=ut.relative(t,s);(i.startsWith("..")||ut.isAbsolute(i))&&ie(`document escapes repository: ${e}`);let o;try{o=Ds.lstatSync(s)}catch{return ie(`document is missing: ${n}`)}return(!o.isFile()||o.isSymbolicLink())&&ie(`document is not a regular repository file: ${n}`),n}function Ps(t,e){if(e.trim())return e.trim();if(t.startsWith("local "))return t;let n=t.trim().split(/\s+/).at(-1)??t;return(n.replace(/\([^)]*\)\.$|[#/.:!]$/,"").split(/[/#]/).at(-1)??n).replaceAll("`","")||t}function um(t){return"SCIP_Symbol"}function dm(t){let e=St(t,1)[0];if(!e)return[];let n=St(e,2)[0];if(!n)return[];let s=wt(n,1)[0],i=wt(n,2)[0];return s?[`${s}${i?`@${i}`:""}`]:[]}function tc(t,e){let n=performance.now(),s={...vo,...e};for(let[_,R]of Object.entries(s))_!=="path"&&(!Number.isSafeInteger(R)||R<1)&&ie(`${_} must be a positive integer`);zs=s.timeoutMs,js=n+s.timeoutMs;let i=ut.resolve(t),o=ut.resolve(i,e.path),r=ut.relative(i,o);(r.startsWith("..")||ut.isAbsolute(r))&&ie("input path escapes repository");let c;try{c=Ds.lstatSync(o)}catch{return ie(`input is missing: ${r}`)}(!c.isFile()||c.isSymbolicLink())&&ie("input must be a regular repository file"),c.size>s.maxBytes&&ie(`input exceeds ${s.maxBytes} byte limit`);let a=Ds.readFileSync(o),l=new Uint8Array(a.buffer,a.byteOffset,a.byteLength),u=[],f=0;Ms(l,2,s.maxFiles)>s.maxFiles&&ie(`index exceeds ${s.maxFiles} file limit`);for(let _ of St(l,2)){let R=lm(i,wt(_,1)[0]??"");Ds.statSync(ut.join(i,R)).mtimeMs>c.mtimeMs+1&&ie(`input is stale for ${R}`);let S=Ms(_,2,s.maxFacts-f);f+=S,f>s.maxFacts&&ie(`index exceeds ${s.maxFacts} fact limit`);let E=Ms(_,3,s.maxFacts-f);f+=E,f>s.maxFacts&&ie(`index exceeds ${s.maxFacts} fact limit`);let $=St(_,2),p=St(_,3);for(let F of p){let L=Math.floor((s.maxFacts-f)/4);f+=Ms(F,4,L)*4,f>s.maxFacts&&ie(`index exceeds ${s.maxFacts} fact limit`)}u.push({filePath:R,language:wt(_,4)[0]??"unknown",occurrences:$.map(am),symbols:p.map(cm)}),performance.now()-n>s.timeoutMs&&ie(`import exceeded ${s.timeoutMs} ms limit`)}let d=(_,R)=>R.startsWith("local ")?`${_.filePath}\0${R}`:`\0${R}`,y=new Map;for(let _ of u){let R=new Map(_.symbols.map(v=>[v.symbol,v]));for(let v of _.occurrences){let S=d(_,v.symbol);(v.roles&1)!==0&&!y.has(S)&&y.set(S,{document:_,occurrence:v,info:R.get(v.symbol)})}}let g=[...y.values()].map(_=>({symbol:_.occurrence.symbol,name:Ps(_.occurrence.symbol,_.info?.displayName??""),kind:um(_.info?.kind??0),filePath:_.document.filePath,startLine:_.occurrence.range.startLine+1,endLine:_.occurrence.range.endLine+1,startCol:_.occurrence.range.startCol+1,endCol:_.occurrence.range.endCol+1})),h=[];for(let _ of u){for(let R of _.occurrences){if((R.roles&1)!==0)continue;let v=y.get(d(_,R.symbol));v&&h.push({callerSymbol:null,callerFile:_.filePath,calleeSymbol:Ps(R.symbol,v.info?.displayName??""),calleeFile:v.document.filePath,line:R.range.startLine+1,column:R.range.startCol+1,kind:"scip_reference"})}for(let R of _.symbols){let v=y.get(d(_,R.symbol));if(v)for(let S of R.relationships){let E=y.get(d(_,S.symbol));if(!E)continue;let $=[];S.isReference&&$.push("scip_relationship_reference"),S.isImplementation&&$.push("scip_implementation"),S.isTypeDefinition&&$.push("scip_type_definition"),S.isDefinition&&$.push("scip_definition");for(let p of $)h.push({callerSymbol:Ps(R.symbol,R.displayName),callerFile:v.document.filePath,calleeSymbol:Ps(S.symbol,E.info?.displayName??""),calleeFile:E.document.filePath,line:v.occurrence.range.startLine+1,column:v.occurrence.range.startCol+1,kind:p})}}}let w=g.length+h.length;w>s.maxFacts&&ie(`index exceeds ${s.maxFacts} fact limit`),performance.now()-n>s.timeoutMs&&ie(`import exceeded ${s.timeoutMs} ms limit`);let k={inputPath:r.replaceAll("\\","/"),bytes:c.size,files:u.length,facts:w,languages:[...new Set(u.map(_=>_.language))].sort(),indexers:dm(l).sort(),symbols:g.sort((_,R)=>_.filePath.localeCompare(R.filePath)||_.startLine-R.startLine),references:h.sort((_,R)=>_.callerFile.localeCompare(R.callerFile)||_.line-R.line||_.calleeSymbol.localeCompare(R.calleeSymbol)),elapsedMs:Math.round((performance.now()-n)*1e3)/1e3};return js=Number.POSITIVE_INFINITY,zs=0,k}import nc from"node:path";var fm=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py",".cls",".trigger",".page",".component",".app",".cmp",".design",".docs",".evt",".intf",".svg",".sql",".pkb",".pks",".prisma",".java",".cs",".go",".rs",".clp",".ws",".xml",".tf",".tfvars",".hcl",".dockerfile",".lsif"]);function mm(t){return/^force-app\/main\/default\/lwc\/([A-Za-z][A-Za-z0-9_]*)\/\1\.(?:html|css)$/.test(t)||/^force-app\/main\/default\/aura\/([A-Za-z][A-Za-z0-9_]*)\/\1\.(?:css)$/.test(t)}function pm(t){return t==="lwr.config.json"||/^force-app\/main\/default\/experiences\/[A-Za-z][A-Za-z0-9_]*\/(?:routes|views|themes)\/[^/]+\.json$/.test(t)}function Ct(t){if(!Lt(t))return!1;let e=t.replaceAll("\\","/"),n=nc.posix.basename(e);return n==="Dockerfile"?!0:e.endsWith(".json")?n==="manifest.json"||pm(e):e.endsWith(".html")||e.endsWith(".css")?mm(e):fm.has(nc.posix.extname(e))}import{DatabaseSync as hm}from"node:sqlite";function Hs(t){return t.length===1&&Array.isArray(t[0])?t[0]:t}var Us=class{stmt;constructor(e){this.stmt=e}all(...e){return this.stmt.all(...Hs(e))}get(...e){return this.stmt.get(...Hs(e))??null}run(...e){return this.stmt.run(...Hs(e))}finalize(){}},an=class{db;constructor(e,n={}){this.db=new hm(e,{readOnly:n.readonly===!0})}query(e){return new Us(this.db.prepare(e))}prepare(e){return new Us(this.db.prepare(e))}run(e,...n){return n.length===0?(this.db.exec(e),{changes:0,lastInsertRowid:0}):this.db.prepare(e).run(...Hs(n))}exec(e){this.db.exec(e)}close(){this.db.close()}};var Dn="symbolId NOT IN (SELECT id FROM symbols)";function sc(t){t.run(`DELETE FROM symbol_embeddings WHERE ${Dn}`)}function ye(t,e){t.run("DELETE FROM symbol_embeddings WHERE symbolId IN (SELECT id FROM symbols WHERE filePath = ?)",[e]),t.run("DELETE FROM symbols WHERE filePath = ?",[e])}function ic(t,e){t.run("DELETE FROM symbol_embeddings WHERE symbolId IN (SELECT id FROM symbols WHERE filePath LIKE ?)",[e]),t.run("DELETE FROM symbols WHERE filePath LIKE ?",[e])}function oc(t){t.run("DELETE FROM symbol_embeddings;"),t.run("DELETE FROM symbols;")}var wm=ym(import.meta.url),Tc=P.dirname(wm),un=Tc;for(;!q.existsSync(P.join(un,"package.json"))&&un!=="/";)un=P.resolve(un,"..");var xo=un==="/"?P.resolve(Tc,"../../"):un,Sm=gm(import.meta.url);function nt(t){return Sm.resolve(t)}var KS=["dead_code","large_functions","large_files","import_cycles","flows","stats","knowledge_gaps","surprising_connections","suggested_questions","architecture_overview","batch_outline","project_overview","community","federated_repos","mcp_tools","api_contract_mismatches"],jn=t=>{let e=t.trim().match(/^(["'`])([\s\S]*?)\1$/);return e&&!(e[1]==="`"&&e[2].includes("${"))?e[2]:void 0};function Ve(t,e){let n="",s=!1,i=!1;for(let o=0;o<e;o++){let r=t[o],c=t[o+1];if(s){r===`
109
+ `&&(s=!1);continue}if(i){r==="*"&&c==="/"&&(i=!1,o++);continue}if(n){r==="\\"?o++:r===n&&(n="");continue}r==="/"&&c==="/"?(s=!0,o++):r==="/"&&c==="*"?(i=!0,o++):(r==='"'||r==="'"||r.charCodeAt(0)===96)&&(n=r)}return!n&&!s&&!i}function Pt(t){let e=[],n=0,s=0,i="";for(let o=0;o<t.length;o++){let r=t[o];if(i){r==="\\"?o++:r===i&&(i="");continue}"\"'`".includes(r)?i=r:"({[".includes(r)?s++:")}]".includes(r)?s--:r===","&&s===0&&(e.push(t.slice(n,o).trim()),n=o+1)}return e.push(t.slice(n).trim()),e}function Rc(t,e,n){let s=t.replace(/\/\*[\s\S]*?\*\//g,d=>d.replace(/[^\n]/g," ")).replace(/(^|\n)\s*\/\/[^\n]*/g,d=>d.replace(/[^\n]/g," ")),i=[],o=new Set,r=[],c=[];if(n){let d=y=>{y.type==="call_expression"&&(o.add(y.startIndex),r.push(t.slice(y.startIndex,y.endIndex))),(y.type==="function_declaration"||y.type==="lexical_declaration")&&/(?:Tools|\btools\b)/.test(t.slice(y.startIndex,y.endIndex))&&c.push(t.slice(y.startIndex,y.endIndex));for(let g of y.namedChildren)d(g)};d(n)}let a=/\b(?:tool|registerTool)\s*\(/g;for(let d=a.exec(s);d;d=a.exec(s)){if(!Ve(t,d.index)||n&&![...o].some(E=>E<=d.index&&d.index-E<200))continue;let y=1,g="",h=d.index+d[0].length;for(;h<s.length&&y>0;h++){let E=s[h];g?E==="\\"?h++:E===g&&(g=""):"\"'`".includes(E)?g=E:E==="("?y++:E===")"&&y--}if(y!==0)continue;let w=Pt(s.slice(d.index+d[0].length,h-1)),k=d[0].startsWith("registerTool"),_=jn(w[0]??"")??"<dynamic>",R,v,S;if(k)R=jn(w[1]?.match(/description\s*:\s*([^,}]+)/)?.[1]??""),v=w[1]?.match(/inputSchema\s*:\s*([\w$]+)/)?.[1]??(w[1]?.match(/inputSchema\s*:\s*\{/)?"inline":void 0),S=w[2]?.match(/^[\w$]+/)?.[0];else{let E=jn(w[1]??"")!==void 0;R=E?jn(w[1]??""):void 0;let $=w[E?2:1];v=$?.match(/^[\w$]+/)?.[0]??($?.startsWith("{")?"inline":void 0),S=w.at(-1)?.match(/^[\w$]+/)?.[0]}i.push({name:_,description:R,schemaSymbol:v,handlerSymbol:S,file:e,line:s.slice(0,d.index).split(`
110
+ `).length,confidence:_==="<dynamic>"||!S||!v?"heuristic":"exact"}),a.lastIndex=h}let l=n?r.find(d=>/setRequestHandler\s*\(\s*CallToolRequestSchema/.test(d)):s;if(l&&/setRequestHandler\s*\(\s*CallToolRequestSchema/.test(l)){let d=l.match(/\bname\s*!==?\s*(["'`])([^"'`]+)\1/)?.[2],y=l.match(/await\s+([\w$]*(?:handle|dispatch)[\w$]*)\s*\(\s*args/i)?.[1],g=t.match(/setRequestHandler\s*\(\s*ListToolsRequestSchema[\s\S]*?tools\s*:\s*(\w*Tools)\s*\(/)?.[1];d&&y&&i.push({name:d,handlerSymbol:y,file:e,line:s.slice(0,s.indexOf(y)).split(`
111
+ `).length,confidence:"heuristic",associationKey:g??`file:${e}`})}let f=s.match(/(?:export\s+)?function\s+(\w*Tools)\s*\([^)]*\)\s*:\s*Tool\[\]\s*\{([\s\S]*?)\n\}/)?.[2],m=n?[...r.filter(d=>/setRequestHandler\s*\(\s*ListToolsRequestSchema/.test(d)),...c]:f?[f]:[];for(let d of m){let y=d.match(/function\s+(\w*Tools)\b/)?.[1]??d.match(/tools\s*:\s*(\w*Tools)\s*\(/)?.[1]??`file:${e}`;for(let g of d.matchAll(/\bname\s*:\s*(["'`])([^"'`]+)\1\s*,([\s\S]{0,30000}?)\binputSchema\s*:/g)){let h=jn(g[3].match(/\bdescription\s*:\s*((?:["'`])[^"'`]*(?:["'`]))/)?.[1]??"");i.push({name:g[2],description:h,schemaSymbol:"inline",file:e,line:s.slice(0,s.indexOf(d)+g.index).split(`
112
+ `).length,confidence:"heuristic",associationKey:y})}}return i}function Em(t){let e=t.replaceAll("\\","/").split("/"),n=P.extname(t).toLowerCase(),s=e.some(o=>o==="force-app"||o.startsWith("force-app-"))||[".cls",".trigger",".page",".component"].includes(n)||/\.[a-z]+-meta\.xml$/i.test(t),i={classes:"apex",triggers:"apex-triggers",flows:"flow",flowDefinitions:"flow-definitions",workflows:"workflow",lwc:"lwc",aura:"aura",pages:"visualforce",components:"visualforce",objects:"objects",permissionsets:"permission-sets",permissionsetgroups:"permission-set-groups",profiles:"profiles",flexipages:"lightning-pages",quickActions:"quick-actions",approvalProcesses:"approval-processes",customMetadata:"custom-metadata",platformEventSubscribers:"platform-events",experiences:"experience-cloud",networks:"experience-cloud",digitalExperiences:"experience-cloud"};if(s)for(let o of e){let r=i[o];if(r)return r}return[".json",".toml",".yaml",".yml"].includes(n)?"config":Lt(t)?"source":"other"}function $c(t){try{let e=st.execFileSync("git",["config","--get","remote.origin.url"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return P.resolve(t)}function be(t,e){if("identity"in e&&typeof e.identity=="string"&&e.identity)return e.identity;let n=`${$c(t)}\0${e.filePath}\0${e.kind}\0${e.name}`;return`sym_${gn.createHash("sha256").update(n).digest("hex").slice(0,24)}`}var ci=400;function km(t){return t===void 0?void 0:[...new Set(t)].sort()}function _c(t,e){if(e===void 0)return t.query("SELECT * FROM symbols ORDER BY filePath, startLine, kind, name").all();let n=[];for(let s=0;s<e.length;s+=ci){let i=e.slice(s,s+ci);if(i.length===0)continue;let o=i.map(()=>"?").join(", ");n.push(...t.query(`SELECT * FROM symbols WHERE filePath IN (${o}) ORDER BY filePath, startLine, kind, name`).all(...i))}return n}function vm(t,e){let n='SELECT * FROM "references"';if(e===void 0)return t.query(n).all();let s=new Map;for(let i=0;i<e.length;i+=ci){let o=e.slice(i,i+ci);if(o.length===0)continue;let r=o.map(()=>"?").join(", ");for(let c of t.query(`${n} WHERE callerFile IN (${r}) OR calleeFile IN (${r})`).all(...o,...o))s.set(c.id,c)}return[...s.values()]}function zt(t,e,n){let s=km(n),i=_c(t,s),o=t.query("UPDATE symbols SET identity = ? WHERE id = ?"),r=$c(e),c=new Map,a=new Map;for(let u of i){let f=c.get(u.filePath)??[];f.push(u),c.set(u.filePath,f)}let l=new Map;t.run("SAVEPOINT persist_symbol_identities;");try{for(let u of i){let f=`${r}\0${u.filePath}\0${u.kind}\0${u.name}`,m=`sym_${gn.createHash("sha256").update(f).digest("hex").slice(0,24)}`,d=a.get(u.filePath);if(!d){try{d=q.readFileSync(P.join(e,u.filePath),"utf8").split(/\r?\n/)}catch{d=[]}a.set(u.filePath,d)}let y=d.slice(Math.max(0,u.startLine-1),u.endLine).join(`
113
+ `).split(/\r?\n/,1)[0].replace(/\s*=>.*$/,"").replace(/\s*\{.*$/,"").replace(/:\s*(?:#.*)?$/,"").replace(/\s+/g," ").trim()||`${u.kind}:${u.name}`,g=(c.get(u.filePath)??[]).filter(_=>_.id!==u.id&&["class","interface","object"].includes(_.kind)&&_.startLine<=u.startLine&&_.endLine>=u.endLine).sort((_,R)=>_.endLine-_.startLine-(R.endLine-R.startLine))[0],h=`sym_${gn.createHash("sha256").update(`${m}\0${g?.name??""}\0${y}`).digest("hex").slice(0,24)}`,w=l.get(h)??0;l.set(h,w+1);let k=w===0?h:`${h}_${w+1}`;u.identity!==k&&o.run(k,u.id)}o.finalize(),xm(t,s),t.run("RELEASE persist_symbol_identities;")}catch(u){throw o.finalize(),t.run("ROLLBACK TO persist_symbol_identities;"),t.run("RELEASE persist_symbol_identities;"),u}}function xm(t,e){let n=vm(t,e);if(n.length===0)return;let s=e===void 0?void 0:[...new Set(n.flatMap(u=>[u.callerFile,...u.calleeFile?[u.calleeFile]:[]]))],i=_c(t,s),o=t.query('UPDATE "references" SET callerIdentity = ?, calleeIdentity = ? WHERE id = ?'),r=new Map,c=new Map;for(let u of i){let f=`${u.filePath}\0${u.name}`,m=r.get(f)??[];if(m.push(u),r.set(f,m),["class","interface","object"].includes(u.kind)){let d=c.get(u.filePath)??[];d.push(u),c.set(u.filePath,d)}}let a=(u,f,m)=>{if(!u)return;let d=r.get(`${f}\0${u}`)??[];if(d.length<2)return d[0];if(m!==void 0){let y=d.filter(h=>h.startLine<=m&&h.endLine>=m).sort((h,w)=>h.endLine-h.startLine-(w.endLine-w.startLine));if(y[0])return y[0];let g=(c.get(f)??[]).filter(h=>h.startLine<=m&&h.endLine>=m).sort((h,w)=>h.endLine-h.startLine-(w.endLine-w.startLine))[0];if(g){let h=d.filter(w=>w.startLine>=g.startLine&&w.endLine<=g.endLine);if(h.length===1)return h[0]}}return d.sort((y,g)=>g.startLine-y.startLine)[0]},l=(u,f,m)=>{let d=r.get(`${f}\0${u}`)??[];if(d.length<2)return d[0];let y=(c.get(f)??[]).filter(h=>h.startLine<=m&&h.endLine>=m).sort((h,w)=>h.endLine-h.startLine-(w.endLine-w.startLine))[0];if(!y)return;let g=d.filter(h=>h.startLine>=y.startLine&&h.endLine<=y.endLine);return g.length===1?g[0]:void 0};for(let u of n){let f=a(u.callerSymbol,u.callerFile,u.line),m=u.calleeFile?l(u.calleeSymbol,u.calleeFile,u.line):void 0,d=f?.identity??null,y=m?.identity??null;(u.callerIdentity!==d||u.calleeIdentity!==y)&&o.run(d,y,u.id)}o.finalize()}function To(t,e,n,s={}){let i=t.query("SELECT * FROM symbols WHERE name = ?").all(n);return s.file&&(i=i.filter(o=>o.filePath===s.file)),s.kind&&(i=i.filter(o=>o.kind===s.kind)),s.identity&&(i=i.filter(o=>Lo(be(e,o),s.identity??""))),i.sort((o,r)=>o.filePath.localeCompare(r.filePath)||o.startLine-r.startLine||o.kind.localeCompare(r.kind)),i.length===1?{selected:i[0]}:i.length<2?{}:{ambiguity:{kind:"ambiguous_symbol",message:`Ambiguous symbol "${n}" matches ${i.length} definitions; select one by identity, file, or kind.`,candidates:i.map((o,r)=>({identity:be(e,o),symbol:o.name,file:o.filePath,kind:o.kind,line:o.startLine,rank:r+1}))}}}function Lo(t,e){return e.endsWith("*")?t.startsWith(e.slice(0,-1)):t===e}var Mt=new Map,No=new Map,li=new Map,rc=50,ui=new Map;var ne=0,zn=new Map,Bn=new Map,Tm=32,Wn=new Map,Rm=16,Co=new Map,Ro=new Map,Ac=16;function $m(t,e){let n=JSON.stringify([e,t.map(m=>m.path)]),s=Co.get(n);if(s&&s.generation===ne)return s.snapshot;let i=Xe(e),o=Yo(t,i),r=[],c=[],a=new Map,l=new Map;for(let m of t){for(let d of m.db.query("SELECT name, kind, filePath FROM symbols ORDER BY filePath, startLine").all()){let y=i(m.path,d.filePath);a.set(d.name,(a.get(d.name)??0)+1),l.has(d.name)||l.set(d.name,y),r.push({...d,filePath:y,repo:m.path})}for(let d of m.db.query('SELECT callerSymbol, callerFile, calleeSymbol, calleeFile, kind FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all())c.push({...d,callerFile:i(m.path,d.callerFile),calleeFile:i(m.path,d.calleeFile??""),repo:m.path})}let u=new Map;for(let m of o){let d=new Set(m.files??[]);for(let y of m.symbols??[]){if(a.get(y)!==1)continue;let g=l.get(y);g&&d.has(g)&&u.set(vt(y,g),m.name)}}let f={communities:o,symbols:r,references:c,communityBySymbolFile:u};return ft(Co,n,{generation:ne,snapshot:f},Ac),f}function _m(t,e,n){if(t.hotspots)return t.hotspots;let s=Xe(n);return t.hotspots={hubs:Wc(e,s,15),bridges:qc(e,s,15)},t.hotspots}function ft(t,e,n,s){for(t.has(e)&&t.delete(e),t.set(e,n);t.size>s;){let i=t.keys().next().value;if(i===void 0)break;t.delete(i)}}function Oo(t,e,n=15,s){let i=[...s??[]].sort(),o=JSON.stringify([e,t.map(a=>a.path),Math.max(15,n),i]),r=Wn.get(o);if(r&&r.generation===ne)return r.result;let c=Ue("graph_analytics",async()=>{let a=Xe(e),l=Yo(t,a,i),u=Qo(l),f=Wc(t,a,Math.max(15,n),i),m=qc(t,a,Math.max(15,n),i),d=Gc(t,u,!0);return{communities:l,symbolCommunity:u,hubs:f,bridges:m,aggregate:d}});return c.catch(()=>{Wn.get(o)?.result===c&&Wn.delete(o)}),ft(Wn,o,{generation:ne,result:c},Rm),c}var cn=new Map,Ws=new Map,Am=16;function Fm(t){return[t,`${t}-wal`].map(e=>{try{let n=q.statSync(e);return`${n.size}:${n.mtimeMs}`}catch{return"missing"}}).join("|")}var Io=new Map,Lm=8;function vt(t,e){return`${t}\0${e}`}function Nm(t,e){let n=Io.get(t);if(n&&n.generation===ne)return n.snapshot;let s=re("traversal_snapshot",()=>{let i=e.query('SELECT callerSymbol, callerFile, calleeSymbol, calleeFile, kind, line, confidence FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all(),o=new Map,r=new Map;for(let c of e.query("SELECT identity, name, kind, filePath, startLine FROM symbols").all()){let a=vt(c.name,c.filePath);r.has(a)||r.set(a,c)}for(let c=0;c<i.length;c++){let a=i[c],l=c+1,u=vt(a.callerSymbol,a.callerFile),f=vt(a.calleeSymbol,a.calleeFile),m=o.get(u);m?m.push(l):o.set(u,[l]);let d=o.get(f);d?d.push(-l):o.set(f,[-l])}return{edges:i,definitions:r,adjacency:o}});return ft(Io,t,{generation:ne,snapshot:s},Lm),s}var Cm=6,ac=50,Om=200,Mo=new Map,Po=new Map,Im=8,Do=new Map,jo=new Map,zo=new Map,Hn=new Map,Mm=256;function $o(t,e){let n=Hn.get(t);if(n?.generation===ne)return n.result;let s=e();for(Hn.set(t,{generation:ne,result:s});Hn.size>Mm;){let i=Hn.keys().next().value;if(i===void 0)break;Hn.delete(i)}return s}var Pm=8,Dm=8,xt={metadataBuilds:0,metadataCacheHits:0,vectorScores:0,hydratedRows:0,sourceReads:0,callerQueries:0,communityLookupBuilds:0,communityLookupCacheHits:0};function jm(t,e){let n=P.resolve(t),s=jo.get(n);if(s&&s.generation===ne)return xt.metadataCacheHits++,s.snapshot;xt.metadataBuilds++;let i=re("search_row_fetch_decode",()=>{let r=e.query(`
114
+ SELECT s.id, s.identity, s.name, s.kind, s.filePath, s.startLine, s.endLine, se.embedding
115
+ FROM symbols s
116
+ JOIN symbol_embeddings se ON s.id = se.symbolId
117
+ `),c=r.all();return r.finalize(),c.map(a=>{let{embedding:l,...u}=a;try{return{...u,vector:eh(l)}}catch(f){return console.error(`Skipping corrupt embedding for symbol ${a.id}:`,f),{...u,vector:null}}})}),o={rows:i,rowById:new Map(i.map(r=>[r.id,r]))};return ft(jo,n,{generation:ne,snapshot:o},Pm),o}function cc(t,e){let n=JSON.stringify([e,t.map(r=>r.path)]),s=zo.get(n);if(s&&s.generation===ne)return xt.communityLookupCacheHits++,s.lookup;xt.communityLookupBuilds++;let i=new Map,o=Yo(t,Xe(e));for(let r of o)for(let c of r.files??[])i.set(c,r.name);return ft(zo,n,{generation:ne,lookup:i},Dm),i}function zm(t,e){let n=Do.get(t);if(n&&n.generation===ne)return n.index;let s=[];for(let l of e)l.vector&&s.push({id:l.id,vec:l.vector});let i=new Map;for(let l of s)i.set(l.vec.length,(i.get(l.vec.length)??0)+1);let o=0,r=-1;for(let[l,u]of i)u>r&&(o=l,r=u);let c=[];for(let l of s)l.vec.length===o?c.push(l):console.error(`Skipping corrupt embedding for symbol ${l.id}: dimension mismatch (expected ${o}, got ${l.vec.length})`);let a=Ua(c);return Do.set(t,{generation:ne,index:a}),a}function qn(t,e){let n=Mo.get(e);if(n&&n.generation===ne)return n.result;let s=t.query(`SELECT callerSymbol, calleeSymbol, calleeFile, line FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL AND kind = 'call'`).all(),i=new Map;for(let h of s){let w=i.get(h.callerSymbol);w||(w=[],i.set(h.callerSymbol,w)),w.push({callee:h.calleeSymbol,calleeFile:h.calleeFile,line:h.line})}let o=new Set(t.query('SELECT DISTINCT calleeSymbol FROM "references"').all().map(h=>h.calleeSymbol)),r=t.query("SELECT name, kind, filePath, startLine FROM symbols").all(),c=new Map;for(let h of r){let w=`${h.name}\0${h.filePath}`;c.has(w)||c.set(w,h.startLine)}let a=new Map,l=(h,w)=>{let k=a.get(h);if(k===void 0){try{k=q.readFileSync(P.join(e,h),"utf-8")}catch{k=null}a.set(h,k)}if(!k)return!1;let _=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\bexport\\s+(?:default\\s+)?(?:function|class|const|let|var|type|interface|enum)\\s+${_}\\b`).test(k)},u=h=>i.get(h)?.length??0,f=new Set,m=[];for(let h of r){let w=h.kind==="endpoint",k=h.kind==="function"&&!o.has(h.name)&&l(h.filePath,h.name);!w&&!k||f.has(h.name)||(f.add(h.name),m.push({name:h.name,file:h.filePath,line:h.startLine}))}m.sort((h,w)=>u(w.name)-u(h.name)||h.name.localeCompare(w.name));let d=m.slice(0,Om),y=[];for(let h of d){let w=new Set([h.name]),k=[{symbol:h.name,file:h.file,line:h.line,depth:0}],_=new Set([h.file]),R=[{name:h.name,depth:0}];for(;R.length>0;){let $=R.shift();if(!($.depth>=Cm)){if(k.length>=ac)break;for(let p of i.get($.name)??[]){if(k.length>=ac)break;if(w.has(p.callee))continue;w.add(p.callee);let F=$.depth+1,L=c.get(`${p.callee}\0${p.calleeFile}`)??p.line;k.push({symbol:p.callee,file:p.calleeFile,line:L,depth:F}),_.add(p.calleeFile),R.push({name:p.callee,depth:F})}}}let v=k.length,S=k.reduce(($,p)=>Math.max($,p.depth),0),E=_.size;y.push({entrySymbol:h.name,entryFile:h.file,entryLine:h.line,nodeCount:v,depth:S,fileCount:E,criticality:v*E,steps:k,files:_})}let g=y.reduce((h,w)=>Math.max(h,w.criticality),0);for(let h of y)h.criticality=g>0?h.criticality/g:0;return Mo.set(e,{generation:ne,result:y}),y}function Bm(t,e){let n=Po.get(e);if(n&&n.generation===ne)return n.result;let s=new Map;for(let i of qn(t,e))for(let o of i.files){let r=s.get(o);r?r.push(i.entrySymbol):s.set(o,[i.entrySymbol])}return ft(Po,e,{generation:ne,result:s},Im),s}var lc=!1,Ks=null,Xs=null,Zs=null,Js=null,Ys=null,Qs=null,ei=null,ti=null,ni=null,si=null,ii=null,oi=null,di=!1;async function Hm(t,e){let n=async()=>{if(di)return yo(t);let s=await Ue("model_load",()=>yo(t));return di=!0,s};return e?Ue("embedding_inference_write",n):n()}async function Um(t,e,n){let s=async()=>{if(di)return Ns(t,n);let i=await Ue("model_load",()=>Ns(t,n));return di=!0,i};return e?Ue("embedding_inference_write",s):s()}async function Wm(){lc||(await Ue("parser_wasm_init",()=>we.init({locateFile:()=>nt("web-tree-sitter/tree-sitter.wasm")})),lc=!0)}async function Kn(t){await Wm();let e=P.extname(t).toLowerCase();return e===".ts"||e===".mts"||e===".cts"?(Ks||(Ks=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-typescript.wasm"))),Ks):e===".tsx"?(Xs||(Xs=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-tsx.wasm"))),Xs):e===".js"||e===".jsx"||e===".mjs"||e===".cjs"?(Zs||(Zs=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-javascript.wasm"))),Zs):e===".py"?(Js||(Js=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-python.wasm"))),Js):e===".cls"||e===".trigger"?(Ys||(Ys=await we.Language.load(nt("web-tree-sitter-sfapex/tree-sitter-apex.wasm"))),Ys):e===".page"||e===".component"||e===".xml"||e===".clp"||e===".ws"?(Qs||(Qs=await we.Language.load(P.join(xo,"tree-sitter-xml.wasm"))),Qs):e===".sql"||e===".pkb"||e===".pks"?(ei||(ei=await we.Language.load(P.join(xo,"tree-sitter-sql.wasm"))),ei):e===".prisma"?(ti||(ti=await we.Language.load(P.join(xo,"tree-sitter-prisma.wasm"))),ti):e===".java"?(ni||(ni=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-java.wasm"))),ni):e===".cs"?(si||(si=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-c_sharp.wasm"))),si):e===".go"?(ii||(ii=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-go.wasm"))),ii):e===".rs"?(oi||(oi=await we.Language.load(nt("tree-sitter-wasms/out/tree-sitter-rust.wasm"))),oi):null}async function qm(t){let e=await Kn(t);return e?e===Ks||e===Xs?"typescript":e===Zs?"javascript":e===Js?"python":e===Ys?"apex":e===Qs?"xml":e===ei?"sql":e===ti?"prisma":e===ni?"java":e===si?"csharp":e===ii?"go":e===oi?"rust":"other":"other"}function dn(){let t=new Map;return async e=>{let n=P.extname(e).toLowerCase(),s=t.get(n);return s===void 0&&(s=await qm(e),t.set(n,s)),s}}function Ae(t){let e=t;for(;e.parent&&e.parent.startPosition.row===e.startPosition.row;)e=e.parent;let n=e.previousSibling,s=0;for(;n&&s<5&&!(n.type==="comment"||n.type==="hash_comment"||n.type==="block_comment"||n.type==="line_comment");)n=n.previousSibling,s++;if(n&&(n.type==="comment"||n.type==="hash_comment"||n.type==="block_comment"||n.type==="line_comment")){let i=n.text.trim();return i.startsWith("/*")?i=i.replace(/^\/\*+\s*/,"").replace(/\*+\/$/,"").split(`
118
+ `).map(o=>o.trim().replace(/^\*\s*/,"")).join(`
119
+ `).trim():i.startsWith("//")&&(i=i.split(`
120
+ `).map(o=>o.trim().replace(/^\/\/+\s*/,"")).join(`
121
+ `).trim()),i}return null}function uc(t){let e=t.childForFieldName("body");if(e&&e.childCount>0){let n=e.child(0);if(n&&n.type==="expression_statement"){let s=n.child(0);if(s&&s.type==="string")return s.text.replace(/^["']{3}|["']{3}$/g,"").trim()}}return null}function dt(t){if(t.type==="identifier"||t.type==="type_identifier")return t.text;if(t.type==="generic_type"){let e=t.namedChild(0);return e?dt(e):null}return t.type==="member_expression"||t.type==="nested_type_identifier"?(t.childForFieldName("property")??t.namedChild(t.namedChildCount-1)??null)?.text??null:t.type==="attribute"?(t.childForFieldName("attribute")??t.namedChild(t.namedChildCount-1)??null)?.text??null:null}function Gm(t){let e=t.parent;for(;e;){switch(e.type){case"statement_block":case"function_declaration":case"function_expression":case"generator_function_declaration":case"arrow_function":case"method_definition":case"class_body":return!1}e=e.parent}return!0}function Bo(t,e,n,s,i,o,r,c){let a=n,l=a.indexOf("?");l!==-1&&(a=a.substring(0,l)),a.startsWith("/")||(a=`/${a}`),t.some(u=>u.name===a&&u.kind==="endpoint")||t.push({name:a,kind:"endpoint",startLine:i,endLine:o,startCol:r,endCol:c,summary:`HTTP Endpoint: ${a}`}),s&&!e.some(u=>u.callerSymbol===a&&u.calleeSymbol===s&&u.line===i)&&e.push({callerSymbol:a,calleeSymbol:s,line:i,column:r})}function ln(t,e,n="(",s=")"){let i=0,o="";for(let r=e;r<t.length;r++){let c=t[r];if(o){c==="\\"?r++:c===o&&(o="");continue}if(c==='"'||c==="'"||c==="`")o=c;else if(c===n)i++;else if(c===s&&--i===0)return r}return null}function Fc(t){let e=new Set;for(let n of Pt(t)){let s=n.match(/^\s*(?:["']([^"']+)["']|([A-Za-z_$][\w$]*))\s*(?::|,|$)/),i=s?.[1]??s?.[2]??n.match(/^\s*([A-Za-z_$][\w$]*)\s*$/)?.[1];i&&i!=="..."&&!i.startsWith("...")&&e.add(i)}return[...e]}function Vm(t){let e=new Set,n=0,s="",i=!0;for(let o=0;o<t.length;o++){let r=t[o];if(s){r==="\\"?o++:r===s&&(s="");continue}if(r==='"'||r==="'"||r==="`"){s=r;continue}if("{[(".includes(r)){n++,i=!1;continue}if("})]".includes(r)){n--;continue}if(n===0&&r===","){i=!0;continue}if(n!==0||!i||/\s/.test(r))continue;let c=t.slice(o).match(/^(?:["']([^"']+)["']|([A-Za-z_$][\w$]*))\s*:/);c&&(e.add(c[1]??c[2]),i=!1)}return[...e]}function Km(t){let e=new Map;for(let n of t.matchAll(/\b(?:type|interface)\s+([A-Za-z_$][\w$]*)[^={]*(?:=\s*)?\{([\s\S]*?)\}/g)){let s=[...n[2].matchAll(/(?:^|[;,\n])\s*(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*[?:]/g)].map(i=>i[1]);s.length>0&&e.set(n[1],s)}return e}function Lc(t,e){let n=new Set;for(let i of t.matchAll(/\b[A-Za-z_$][\w$]*\b/g))for(let o of e.get(i[0])??[])n.add(o);let s=t.match(/\{([\s\S]*)\}/);if(s)for(let i of Fc(s[1]))n.add(i);return[...n]}function dc(t,e){let n=t.trim(),s=null,i=!1,o=n.match(/^(["'])([\s\S]*?)\1$/);if(o)s=o[2];else{let c=n.match(/^`([\s\S]*)`$/);c&&e?s=c[1].replace(/\$\{\s*([A-Za-z_$][\w$]*)\s*\}/g,"{$1}"):i=!0}if(s===null)return{path:"<dynamic>",origin:null,unresolved:!0};if(s.includes("${"))return{path:"<dynamic>",origin:null,unresolved:!0};try{if(/^[a-z][a-z0-9+.-]*:\/\//i.test(s)){let c=new URL(s);return{path:c.pathname||"/",origin:c.origin,unresolved:i}}}catch{return{path:"<dynamic>",origin:null,unresolved:!0}}let r=s.split("?")[0]||"/";return{path:r.startsWith("/")?r:`/${r}`,origin:null,unresolved:i}}function fc(t,e,n){let s=e.find(i=>i.name===n);return s?t.split(`
122
+ `).slice(s.startLine-1,s.endLine).join(`
123
+ `):""}function Xm(t){let e=/\.(?:json|send)\s*\(\s*\{/g.exec(t);if(!e)return{fields:[],known:!1};let n=t.indexOf("{",e.index),s=ln(t,n,"{","}");return s===null?{fields:[],known:!1}:{fields:Fc(t.slice(n+1,s)),known:!0}}function Zm(t,e){let n=[...t.matchAll(/\b(?:Response|Reply)\s*<\s*([^>]+)>/g)];return n.length===0?[]:Lc(n[0][1],e)}function Jm(t,e,n){let s=[],i=Km(t),o=t.replace(/\/\*[\s\S]*?\*\//g,c=>c.replace(/[^\n]/g," ")).replace(/(^|\s)\/\/.*$/gm,(c,a)=>a+" ".repeat(c.length-a.length));for(let c of o.matchAll(/\b([A-Za-z_$][\w$]*)\.(get|post|put|patch|delete)\s*\(/gi)){let a=c[1].toLowerCase();if(!new Set(["app","router","route","fastify","server"]).has(a))continue;let l=(c.index??0)+c[0].length-1,u=ln(o,l);if(u===null)continue;let f=Pt(o.slice(l+1,u)),m=dc(f[0]??"",!1),d=f.slice(1).map(v=>v.trim()).filter(v=>/^[A-Za-z_$][\w$]*$/.test(v)),y=d.at(-1)??(f.some(v=>/=>/.test(v))?"<inline>":null),g=y?d.slice(0,-1):d,h=y&&fc(t,e,y)||o.slice(l,u+1),w=/\bproperties\s*:\s*\{/.exec(o.slice(l,u+1)),k=[];if(w){let v=l+1+(w.index??0)+w[0].lastIndexOf("{"),S=ln(o,v,"{","}");S!==null&&(k=Vm(o.slice(v+1,S)))}let _=Ke(t,c.index??0);m.unresolved||Bo(e,n,m.path,y??"",_.line,_.line,_.column,_.column+c[0].length);let R=Xm(h);s.push({kind:"endpoint",framework:a==="fastify"||a==="server"?"fastify":"express",method:c[2].toUpperCase(),path:m.path,origin:m.origin,handler:y,middleware:g,responseFields:[...new Set([...k,...R.fields])],responseKnown:w!==null||R.known,declaredResponseFields:Zm(h,i),accessedFields:[],unresolved:m.unresolved,line:_.line,confidence:m.unresolved?0:1,evidence:t.split(`
124
+ `)[_.line-1]?.trim()??""})}let r=(c,a,l,u)=>{let f=dc(u[0]??"",!0);if(c==="fetch"){let v=(u[1]??"").match(/\bmethod\s*:\s*["'](get|post|put|patch|delete)["']/i);v&&(a=v[1].toUpperCase())}let m=Ke(t,l),d=e.find(v=>m.line>=v.startLine&&m.line<=v.endLine&&/^(function|method)$/.test(v.kind)),y=d?.name??null,g=d?fc(t,e,d.name):"",h=t.lastIndexOf(`
125
+ `,l)+1,w=t.slice(h,l).match(/(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*await\s*$/)?.[1],k=w?c==="fetch"?new RegExp(`(?:const|let)\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*\\(\\s*await\\s+${w}\\.json\\(\\)\\s*\\)\\s+as\\s+([^;\\n]+)`).exec(g):new RegExp(`(?:const|let)\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*${w}\\.data\\s+as\\s+([^;\\n]+)`).exec(g):null,_=k?.[1],R=_?[...g.matchAll(new RegExp(`\\b${_}\\.([A-Za-z_$][\\w$]*)`,"g"))].map(v=>v[1]):[];s.push({kind:"client",framework:c,method:a,path:f.path,origin:f.origin,handler:y,middleware:[],responseFields:[],responseKnown:!1,declaredResponseFields:k?Lc(k[2],i):[],accessedFields:[...new Set(R)],unresolved:f.unresolved,line:m.line,confidence:f.unresolved||!y?.5:1,evidence:t.split(`
126
+ `)[m.line-1]?.trim()??""}),!f.unresolved&&y&&n.push({callerSymbol:y,calleeSymbol:f.path,line:m.line,column:m.column})};for(let c of o.matchAll(/\bfetch\s*\(/g)){let a=(c.index??0)+c[0].length-1,l=ln(o,a);l!==null&&r("fetch","GET",c.index??0,Pt(o.slice(a+1,l)))}for(let c of o.matchAll(/\baxios\.(get|post|put|patch|delete)\s*\(/gi)){let a=(c.index??0)+c[0].length-1,l=ln(o,a);l!==null&&r("axios",c[1].toUpperCase(),c.index??0,Pt(o.slice(a+1,l)))}for(let c of o.matchAll(/\baxios\s*\(/g)){let a=(c.index??0)+c[0].length-1,l=ln(o,a);l!==null&&r("axios","GET",c.index??0,Pt(o.slice(a+1,l)))}return s}function Ym(t,e,n=!1,s=""){let i=[],o=[],r=[],c=[],a=[],l=[],u=new Map,f=new Map,m=s.endsWith(".java"),d=s.endsWith(".cs"),y=s.endsWith(".go"),g=s.endsWith(".rs");function h(){return l.length>0?l[l.length-1]:null}function w(p){let F=!1,L=null;if(e){if(p.type==="function_definition"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,F=!0,i.push({name:x,kind:"function",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:uc(p)||Ae(p)})}}else if(p.type==="class_definition"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,i.push({name:x,kind:"class",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:uc(p)||Ae(p)});let I=p.childForFieldName("superclasses");if(I)for(let M of I.namedChildren){if(M.type==="keyword_argument")continue;let b=dt(M);b&&o.push({callerSymbol:x,calleeSymbol:b,line:I.startPosition.row+1,column:I.startPosition.column,kind:"extends"})}}}}else if(m){if(p.type==="class_declaration"||p.type==="interface_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;if(L=x,i.push({name:x,kind:"class",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:`Java Class/Interface: ${x}`}),p.type==="class_declaration"){let I=p.childForFieldName("superclass");if(I)for(let b of I.namedChildren){let A=dt(b);A&&o.push({callerSymbol:x,calleeSymbol:A,line:I.startPosition.row+1,column:I.startPosition.column,kind:"extends"})}let M=p.childForFieldName("interfaces");if(M){let b=M.namedChildren.find(A=>A.type==="type_list")??M;for(let A of b.namedChildren){let C=dt(A);C&&o.push({callerSymbol:x,calleeSymbol:C,line:M.startPosition.row+1,column:M.startPosition.column,kind:"implements"})}}}}}else if(p.type==="method_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,F=!0,i.push({name:x,kind:"method",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}}else if(d){if(p.type==="class_declaration"||p.type==="interface_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;if(L=x,i.push({name:x,kind:"class",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:`C# Class/Interface: ${x}`}),p.type==="class_declaration"){let I=p.children.find(M=>M.type==="base_list");if(I)for(let M of I.namedChildren){let b=dt(M);b&&o.push({callerSymbol:x,calleeSymbol:b,line:I.startPosition.row+1,column:I.startPosition.column,kind:"extends"})}}}}else if(p.type==="method_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,F=!0,i.push({name:x,kind:"method",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}}else if(y||g){let T=y?new Set(["function_declaration","method_declaration"]):new Set(["function_item"]),x=y?new Map([["type_spec","type"]]):new Map([["struct_item","struct"],["enum_item","enum"],["trait_item","trait"]]);if(T.has(p.type)){let I=p.childForFieldName("name");I&&(L=I.text,F=!0,i.push({name:L,kind:p.type.includes("method")?"method":"function",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)}))}else if(x.has(p.type)){let I=p.childForFieldName("name");I&&(L=I.text,i.push({name:L,kind:x.get(p.type)??"type",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)}))}}else if(n){if(p.type==="class_declaration"){let T=p.childForFieldName("name")||p.children.find(x=>x.type==="identifier");if(T){let x=T.text;L=x,i.push({name:x,kind:"class",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)});let I=p.childForFieldName("superclass");if(I)for(let b of I.namedChildren){let A=dt(b);A&&o.push({callerSymbol:x,calleeSymbol:A,line:I.startPosition.row+1,column:I.startPosition.column,kind:"extends"})}let M=p.childForFieldName("interfaces");if(M){let b=M.namedChildren.find(A=>A.type==="type_list")??M;for(let A of b.namedChildren){let C=dt(A);C&&o.push({callerSymbol:x,calleeSymbol:C,line:M.startPosition.row+1,column:M.startPosition.column,kind:"implements"})}}}}else if(p.type==="trigger_declaration"){let T=p.childForFieldName("name")||p.children.find(x=>x.type==="identifier");if(T){let x=T.text;L=x,i.push({name:x,kind:"trigger",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}else if(p.type==="method_declaration"){let T=p.childForFieldName("name")||p.children.find(x=>x.type==="identifier");if(T){let x=T.text;L=x,F=!0,i.push({name:x,kind:"method",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}}else if(p.type==="function_declaration"||p.type==="generator_function_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,F=!0,i.push({name:x,kind:"function",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}else if(p.type==="class_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,i.push({name:x,kind:"class",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)});let I=p.children.find(M=>M.type==="class_heritage");if(I)for(let M of I.children){let b=M.type==="extends_clause"?"extends":M.type==="implements_clause"?"implements":null;if(b)for(let A of M.namedChildren){let C=dt(A);C&&o.push({callerSymbol:x,calleeSymbol:C,line:M.startPosition.row+1,column:M.startPosition.column,kind:b})}}}}else if(p.type==="method_definition"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,F=!0,i.push({name:x,kind:"method",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}else if(p.type==="interface_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,i.push({name:x,kind:"interface",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}else if(p.type==="type_alias_declaration"){let T=p.childForFieldName("name");if(T){let x=T.text;L=x,i.push({name:x,kind:"type",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)})}}else if(p.type==="variable_declarator"){let T=p.childForFieldName("name"),x=p.childForFieldName("value");if(T&&T.type==="identifier"){let I=T.text;L=I;let M=x&&(x.type==="arrow_function"||x.type==="function_expression");if(M&&(F=!0),(M||Gm(p))&&i.push({name:I,kind:M?"function":"variable",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:Ae(p)}),x?.type==="object"||x?.type==="object_pattern"){let A=p.namedChildren.find(O=>O.type==="type_annotation")?.namedChild(0),C=A?dt(A):null;C&&o.push({callerSymbol:I,calleeSymbol:C,line:p.startPosition.row+1,column:p.startPosition.column,kind:"structural_implements"})}}}if(!e&&!n){if(p.type==="import_statement"||p.type==="import_declaration"){let T=p.childForFieldName("source");if(T&&T.type==="string"){let x=T.text.replace(/^['"`]|['"`]$/g,"");r.push(x);for(let I of p.descendantsOfType(["import_specifier","namespace_import","identifier"]))if(I.type==="import_specifier"){let M=I.childForFieldName("alias"),b=I.childForFieldName("name"),A=b?.text,C=(M??b)?.text;A&&u.set(A,x),C&&A&&C!==A&&f.set(C,A)}else if(I.type==="namespace_import"){let M=I.children.find(b=>b.type==="identifier");M&&u.set(M.text,x)}else I.type==="identifier"&&I.parent?.type==="import_clause"&&u.set(I.text,x)}}}else if(e&&(p.type==="import_from_statement"||p.type==="import_statement")){let T=p.type==="import_from_statement",x=T?p.childForFieldName("module_name"):null,I=x?.text;T&&I&&r.push(I);for(let M of p.namedChildren)if(M&&M!==x){if(M.type==="dotted_name")u.set(M.text,T&&I?I:M.text);else if(M.type==="aliased_import"){let b=M.childForFieldName("alias"),A=M.childForFieldName("name"),C=(b??A)?.text;C&&u.set(C,T&&I?I:A?.text??C)}}}if(n){if(p.type==="method_invocation"){let T=p.childForFieldName("name")||p.children.find(x=>x.type==="identifier");if(T){let x=T.text;o.push({callerSymbol:h(),calleeSymbol:x,line:p.startPosition.row+1,column:p.startPosition.column})}}else if(p.type==="object_creation_expression"){let T=p.childForFieldName("type")||p.children.find(x=>x.type==="type_identifier"||x.type==="identifier");if(T){let x=T.text;o.push({callerSymbol:h(),calleeSymbol:x,line:p.startPosition.row+1,column:p.startPosition.column})}}else if(p.type==="query_expression"){let T=p.text,x=[...T.matchAll(/from\s+([a-zA-Z0-9_]+)/gi)];for(let M of x){let b=M[1];b&&c.push(b)}let I=[...T.matchAll(/returning\s+([a-zA-Z0-9_]+)/gi)];for(let M of I){let b=M[1];b&&c.push(b)}}}else if(e){if(p.type==="call"){let T=p.childForFieldName("function");if(T){let x=null;if(T.type==="identifier")x=T.text;else if(T.type==="attribute"){let I=T.childForFieldName("attribute");I&&(x=I.text)}x&&o.push({callerSymbol:h(),calleeSymbol:x,line:p.startPosition.row+1,column:p.startPosition.column})}}}else if(m){if(p.type==="method_invocation"){let T=p.childForFieldName("name");T&&o.push({callerSymbol:h(),calleeSymbol:T.text,line:p.startPosition.row+1,column:p.startPosition.column})}else if(p.type==="object_creation_expression"){let T=p.childForFieldName("type");T&&o.push({callerSymbol:h(),calleeSymbol:T.text,line:p.startPosition.row+1,column:p.startPosition.column})}}else if(d){if(p.type==="invocation_expression"){let T=p.childForFieldName("function");if(T){let x=null;if(T.type==="identifier")x=T.text;else if(T.type==="member_access_expression"){let I=T.childForFieldName("name");I&&(x=I.text)}x&&o.push({callerSymbol:h(),calleeSymbol:x,line:p.startPosition.row+1,column:p.startPosition.column})}}else if(p.type==="object_creation_expression"){let T=p.childForFieldName("type");T&&o.push({callerSymbol:h(),calleeSymbol:T.text,line:p.startPosition.row+1,column:p.startPosition.column})}}else{if(p.type==="call_expression"){let T=p.childForFieldName("function");if(T){let x=null;if(T.type==="identifier")x=f.get(T.text)??T.text;else if(T.type==="member_expression"){let I=T.childForFieldName("property");I&&(x=I.text)}if(x){let I=T.type==="member_expression"?T.childForFieldName("object"):null;o.push({callerSymbol:h(),calleeSymbol:x,line:p.startPosition.row+1,column:p.startPosition.column,calleeModule:I?.type==="identifier"?u.get(I.text)??null:T.type==="member_expression"?null:void 0})}}}else if(p.type==="new_expression"){let T=p.childForFieldName("constructor");if(T){let x=null;if(T.type==="identifier")x=f.get(T.text)??T.text;else if(T.type==="member_expression"){let I=T.childForFieldName("property");I&&(x=I.text)}if(x){let I=T.type==="member_expression"?T.childForFieldName("object"):null;o.push({callerSymbol:h(),calleeSymbol:x,line:p.startPosition.row+1,column:p.startPosition.column,calleeModule:I?.type==="identifier"?u.get(I.text)??null:T.type==="member_expression"?null:void 0})}}}if(!e&&!n&&!m&&!d&&p.type==="call_expression"){let T=p.childForFieldName("function")||p.children.find(x=>x.type==="identifier");if(T&&["pgTable","sqliteTable","mysqlTable"].includes(T.text)){let x=p.childForFieldName("arguments")||p.children.find(I=>I.type==="arguments");if(x&&x.childCount>0){let I=x.child(0);if(I&&I.text==="("&&(I=x.child(1)),I){let M=I.text.replace(/['"`]/g,""),b=[],A=x.child(2);if(A&&A.text===","&&(A=x.child(3)),A&&A.type==="object")for(let C=0;C<A.childCount;C++){let O=A.child(C);if(O&&O.type==="pair"){let N=O.childForFieldName("key")||O.child(0);N&&b.push(N.text.replace(/['"`]/g,""))}}i.push({name:M,kind:"table",startLine:p.startPosition.row+1,endLine:p.endPosition.row+1,startCol:p.startPosition.column,endCol:p.endPosition.column,summary:`Drizzle Table "${M}" with columns: ${b.join(", ")}`}),c.push(M)}}}}}F&&L&&l.push(L);for(let T=0;T<p.childCount;T++){let x=p.child(T);x&&w(x)}F&&L&&l.pop()}w(t);let k=t.text,_=Jm(k,i,o),R=/(?:pgTable|sqliteTable|mysqlTable)\s*\(\s*['"`]([a-zA-Z0-9_]+)['"`]/g,v=R.exec(k);for(;v!==null;){let p=v[1];c.includes(p)||c.push(p),i.some(F=>F.name===p)||i.push({name:p,kind:"table",startLine:1,endLine:1,startCol:0,endCol:p.length,summary:`Drizzle Table: ${p}`}),v=R.exec(k)}if(e){let p=/__tablename__\s*=\s*['"`]([a-zA-Z0-9_]+)['"`]/g,F=p.exec(k);for(;F!==null;){let x=F[1];a.push({to:x,kind:"orm-relation"}),F=p.exec(k)}let L=/db_table\s*=\s*['"`]([a-zA-Z0-9_]+)['"`]/g,T=L.exec(k);for(;T!==null;){let x=T[1];a.push({to:x,kind:"orm-relation"}),T=L.exec(k)}}if(m){let p=/@Table\s*\(\s*name\s*=\s*['"`]([a-zA-Z0-9_]+)['"`]\s*\)/gi,F=p.exec(k);for(;F!==null;){let L=F[1];a.push({to:L,kind:"orm-relation"}),F=p.exec(k)}}if(d){let p=/\.ToTable\s*\(\s*['"`]([a-zA-Z0-9_]+)['"`]\s*\)/g,F=p.exec(k);for(;F!==null;){let L=F[1];a.push({to:L,kind:"orm-relation"}),F=p.exec(k)}}let S=t.text;S=S.replace(/\/\*[\s\S]*?\*\//g,p=>p.replace(/[^\n]/g," ")),S=S.replace(/(^|\s)(\/\/|#).*$/gm,(p,F)=>F+" ".repeat(p.length-F.length));let E=S,$=[{regex:/@(?:Get|Post|Put|Delete|Patch)\s*\(\s*['"`]([^'"`]+)['"`]\)/gi,handlerGroup:null},{regex:/@(?:app|router)\.(get|post|put|delete|patch|route)\s*\(\s*['"`]([^'"`]+)['"`]/gi,handlerGroup:null}];for(let p of $)for(p.regex.lastIndex=0;;){let F=p.regex.exec(E);if(F===null)break;let L=F[p.handlerGroup===3?2:1];if(!L)continue;let{line:T,column:x}=Ke(E,F.index),I="";if(p.handlerGroup&&F[p.handlerGroup])I=F[p.handlerGroup];else{let A=E.substring(p.regex.lastIndex).match(/^\s*(?:async\s+)?(?:function|def)\s+([a-zA-Z0-9_]+)\b|^\s*(?:@Get|@Post|@Put|@Delete|@Patch|@app|@router|private|public|protected|async|static|\s)*\s*([a-zA-Z0-9_]+)\s*\(/i);A&&(I=A[1]||A[2])}let M=I&&I.split(".").pop()||"";Bo(i,o,L,M,T,T,x,x+F[0].length)}if(m){let p=b=>{let A=null;for(let C of i){if(b<C.startLine||b>C.endLine)continue;let O=C.kind==="method"||C.kind==="function",N=A?.kind==="method"||A?.kind==="function";(!A||O&&!N)&&(A=C)}return A},F="@Scheduled",L=/@Scheduled\b/g;for(let b=L.exec(E);b!==null;b=L.exec(E)){let{line:A,column:C}=Ke(E,b.index),O=p(A);O&&(O.kind==="method"||O.kind==="function")&&o.push({callerSymbol:F,calleeSymbol:O.name,line:A,column:C,kind:"schedules"})}let T=/@EventListener\b\s*(?:\([^)]*\))?\s*(?:(?:public|private|protected|static|final|abstract|synchronized|default)\s+)*[A-Za-z_][\w.<>[\]]*\s+\w+\s*\(\s*(?:final\s+)?(?:@\w+(?:\([^)]*\))?\s+)*([A-Za-z_][\w.]*)/g;for(let b=T.exec(E);b!==null;b=T.exec(E)){let{line:A,column:C}=Ke(E,b.index),O=p(A),N=b[1];O&&N&&o.push({callerSymbol:O.name,calleeSymbol:N,line:A,column:C,kind:"listens"})}let x=/\.\s*publishEvent\s*\(\s*(?:new\s+)?([A-Za-z_][\w.]*)/g;for(let b=x.exec(E);b!==null;b=x.exec(E)){let{line:A,column:C}=Ke(E,b.index),O=p(A),N=b[1];O&&N&&o.push({callerSymbol:O.name,calleeSymbol:N,line:A,column:C,kind:"publishes"})}let I=/@Value\s*\(\s*["']\s*\$\{\s*([^}:]+?)\s*(?::[^}]*)?\}\s*["']\s*\)/g;for(let b=I.exec(E);b!==null;b=I.exec(E)){let{line:A,column:C}=Ke(E,b.index),O=p(A),N=b[1];O&&N&&o.push({callerSymbol:O.name,calleeSymbol:N,line:A,column:C,kind:"consumes"})}let M=/@(?:RequestMapping|GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping)\s*\(([^)]*)\)/g;for(let b=M.exec(E);b!==null;b=M.exec(E)){let{line:A,column:C}=Ke(E,b.index),O=p(A);if(!O||O.kind!=="method"&&O.kind!=="function")continue;let N=b[1],j=N.match(/^\s*["']([^"']+)["']/),z=N.match(/\bvalue\s*=\s*["']([^"']+)["']/),D=j?.[1]??z?.[1];D&&Bo(i,o,D,O.name,A,A,C,C+b[0].length)}}return{definitions:i,references:o,apiContracts:_,fileDependencies:r,tableDependencies:c,ormDependencies:a,importBindings:u}}function Qm(t){if(t.length>1e6)return!0;if(t.length<2e4)return!1;let e=0;for(let n=0;n<t.length;n++)t.charCodeAt(n)===10&&e++;return t.length/(e+1)>2e3}function ep(t){return t.replace(/\$([A-Za-z0-9_]*)\$[\s\S]*?\$\1\$/g,"''")}var mc=[".ts",".tsx",".js",".jsx",".py",".mts",".cts",".mjs",".cjs"],pc={".js":[".ts",".tsx",".js"],".jsx":[".tsx",".jsx"],".mjs":[".mts",".mjs"],".cjs":[".cts",".cjs"]};function fi(t,e,n){if(!e.startsWith("."))return null;let s=P.dirname(P.resolve(n,t)),i=P.resolve(s,e),o=[i],r=P.extname(i);if(pc[r]){let c=i.slice(0,-r.length);for(let a of pc[r])o.push(c+a)}for(let c of mc)o.push(i+c);for(let c of o)if(q.existsSync(c)&&q.statSync(c).isFile())return P.relative(n,c);for(let c of mc){let a=P.join(i,`index${c}`);if(q.existsSync(a))return P.relative(n,a)}return null}var Ho=new Map;function tp(t){let e=Ho.get(t);if(e)return e;let n=new Map;for(let s of Pn(t,{accept:i=>P.posix.basename(i)==="package.json"}))try{let i=JSON.parse(q.readFileSync(P.join(t,s),"utf-8"));if(i&&typeof i.name=="string"){let o=P.posix.dirname(s);n.set(i.name,{dir:o,entryFile:np(t,o,i)})}}catch{}return Ho.set(t,n),n}function np(t,e,n){let s=[n.source,n.module,n.main].filter(i=>typeof i=="string");for(let i of s){let o=fi(P.join(e,"index.ts"),`./${i}`.replace(/^\.\/\.\//,"./"),t);if(o&&!o.includes("dist"))return o}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js"]){let o=P.join(e,i);if(q.existsSync(P.join(t,o)))return o}return null}function Xn(t,e,n){if(e.startsWith("."))return fi(t,e,n);let s=tp(n),i=null;for(let[r,c]of s)(e===r||e.startsWith(`${r}/`))&&(!i||r.length>i.name.length)&&(i={name:r,...c});if(!i)return null;let o=e.slice(i.name.length);return o===""||o==="/"?i.entryFile:fi(P.join(i.dir,"index.ts"),`.${o}`,n)}var Uo=new Map;function Nc(t,e){let n=`${t}\0${e}`,s=Uo.get(n);if(s)return s;let i=new Map,o=[];try{let c=q.readFileSync(P.join(t,e),"utf-8");for(let a of c.matchAll(/export\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g)){let l=a[2];for(let u of a[1].split(",")){let f=u.trim();if(!f)continue;let m=f.split(/\s+as\s+/),d=(m[1]??m[0]).trim();d&&i.set(d,l)}}for(let a of c.matchAll(/export\s*\*\s*from\s*['"]([^'"]+)['"]/g))o.push(a[1])}catch{}let r={named:i,stars:o};return Uo.set(n,r),r}function Wo(t,e,n,s=0,i=new Set){if(s>=8||i.has(e))return e;i.add(e);let{named:o,stars:r}=Nc(t,e),c=o.get(n);if(c){let a=Xn(e,c,t);if(a)return Wo(t,a,n,s+1,i)}for(let a of r){let l=Xn(e,a,t);if(!(!l||i.has(l))&&Cc(t,l,n,i))return Wo(t,l,n,s+1,i)}return e}function Cc(t,e,n,s){let{named:i,stars:o}=Nc(t,e);if(i.has(n))return!0;try{let r=q.readFileSync(P.join(t,e),"utf-8"),c=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b(?:function|class|const|let|var|type|interface|enum)\\s+${c}\\b`).test(r))return!0}catch{}for(let r of o){let c=Xn(e,r,t);if(c&&!s.has(c)&&(s.add(c),Cc(t,c,n,s)))return!0}return!1}function Ke(t,e){let n=1,s=0;for(let i=0;i<e;i++)t[i]===`
127
+ `?(n++,s=0):s++;return{line:n,column:s}}function sp(t,e){return Pn(e,{accept:n=>P.posix.basename(n)===`${t}.cls`,limit:1})[0]??null}function Zn(t,e){let n=Pn(e,{accept:s=>P.posix.basename(s)===`${t}.cls`,limit:2});return n.length===1?n[0]:null}function Oc(t){let e=t.replaceAll("\\","/");if(e==="lwr.config.json")return{type:"lwrConfig"};let n=e.match(/^(force-app\/main\/default\/experiences\/[A-Za-z][A-Za-z0-9_]*?)\/(routes|views|themes|assets)\/[^/]+\.(json|svg)$/);if(!n)return null;let s=n[2];return s==="routes"&&n[3]==="json"?{type:"route",sitePath:n[1]}:s==="views"&&n[3]==="json"?{type:"view",sitePath:n[1]}:s==="themes"&&n[3]==="json"?{type:"theme",sitePath:n[1]}:s==="assets"?{type:"asset",sitePath:n[1]}:null}function qo(t){return typeof t!="string"||t.includes("{!")||t.includes("${")?null:/^[A-Za-z0-9_./-]+$/.test(t)&&!t.includes("..")?t:null}function qs(t,e,n,s){let i=qo(n);if(!i)return null;let o=i.startsWith(`${e}/`)?i.slice(e.length+1):i;if(!o||o.includes("/"))return null;let c=`${t}/${e}/${o}${e==="assets"?"":".json"}`;return q.existsSync(P.join(s,c))?c:null}function ip(t,e){if(typeof t!="string")return null;let n=t.match(/^c:([A-Za-z][A-Za-z0-9_]*)$/)?.[1];return n?Xo(n,e)??(()=>{let s=`force-app/main/default/aura/${n}/${n}.cmp`;return q.existsSync(P.join(e,s))?s:null})():null}function op(t){let n=t.replaceAll("\\","/").match(/^(force-app\/main\/default\/lwc\/)([A-Za-z][A-Za-z0-9_]*?)\/\2\.(js|html|css|js-meta\.xml)$/);return n?{bundlePath:`${n[1]}${n[2]}`,componentName:n[2],extension:n[3]}:null}function rp(t){let n=t.replaceAll("\\","/").match(/^(force-app\/main\/default\/aura\/)([A-Za-z][A-Za-z0-9_]*?)\/\2\.(app|cmp|css|design|docs|evt|intf|js|svg)$/);return n?{bundlePath:`${n[1]}${n[2]}`,componentName:n[2],extension:n[3]}:null}function ap(t,e,n){let s=P.dirname(P.dirname(t)),i=P.join(s,e,`${e}.js`);return q.existsSync(P.join(n,i))?i:null}function Ic(t,e,n){let s=Zn(t,n);if(!s)return null;try{let i=q.readFileSync(P.join(n,s),"utf-8").replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm,"").replace(/'(?:\\.|[^'])*'|"(?:\\.|[^"])*"/g,""),o=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:public|protected|private|global)\\s+(?:(?:static|virtual|override|webService)\\s+)*[A-Za-z_][\\w<>,.?\\[\\]\\s]*?\\s${o}\\s*\\(`).test(i)?s:null}catch{return null}}function cp(t){return!t.includes("__")&&/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)?$/.test(t)}function lp(t){let e=t.replaceAll("\\","/");if(!e.startsWith("force-app/main/default/"))return null;let s=e.match(/^force-app\/main\/default\/objects\/([A-Za-z][A-Za-z0-9_]*)\/\1\.object-meta\.xml$/);return s?{type:"object",object:s[1]}:(s=e.match(/^force-app\/main\/default\/objects\/([A-Za-z][A-Za-z0-9_]*)\/fields\/([A-Za-z][A-Za-z0-9_]*)\.field-meta\.xml$/),s?{type:"field",object:s[1],field:s[2]}:(s=e.match(/^force-app\/main\/default\/objects\/([A-Za-z][A-Za-z0-9_]*)\/recordTypes\/([A-Za-z][A-Za-z0-9_]*)\.recordType-meta\.xml$/),s?{type:"recordType",object:s[1],recordType:s[2]}:(s=e.match(/^force-app\/main\/default\/permissionSets\/([A-Za-z][A-Za-z0-9_]*)\.permissionSet-meta\.xml$/),s?{type:"permissionSet",name:s[1]}:(s=e.match(/^force-app\/main\/default\/flows\/([A-Za-z][A-Za-z0-9_]*)\.flow-meta\.xml$/),s?{type:"flow",name:s[1]}:(s=e.match(/^force-app\/main\/default\/workflows\/([A-Za-z][A-Za-z0-9_]*)\.workflow-meta\.xml$/),s?{type:"workflow",object:s[1]}:(s=e.match(/^force-app\/main\/default\/approvalProcesses\/([A-Za-z][A-Za-z0-9_]*)\.([A-Za-z][A-Za-z0-9_]*)\.approvalProcess-meta\.xml$/),s?{type:"approval",object:s[1],name:s[2]}:null))))))}function tt(t,e){let n=t.replace(/<!--[\s\S]*?-->/g,""),s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`<${s}>([^<]+)</${s}>`,"g"),o=[];for(let r of n.matchAll(i)){let c=r[1].trim();c&&!c.includes("{!")&&o.push({value:c,evidence:r[0].trim()})}return o}function Un(t){return t.split(".").every(e=>{if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))return!1;let n=(e.match(/__/g)??[]).length;return n===0||n===1&&e.endsWith("__c")})}function Xo(t,e){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))return null;let n=`force-app/main/default/lwc/${t}/${t}.js`;return q.existsSync(P.join(e,n))?n:null}function up(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return ri(t,new RegExp(`\\b(?:public|protected|private|global)\\s+(?:(?:static|virtual|override|webService)\\s+)*[A-Za-z_][\\w<>,.?\\[\\]\\s]*?\\s${n}\\s*\\(`,"gi"))!==null}function ri(t,e){for(let n of t.matchAll(e))if(Ve(t,n.index??0))return n;return null}function dp(t,e){let n=1,s="";for(let i=e+1;i<t.length;i++){let o=t[i];if(s){o==="\\"?i++:o===s&&(s="");continue}if("\"'`".includes(o))s=o;else if(o==="(")n++;else if(o===")"&&--n===0)return i}return null}function fp(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|[,\\s])${n}(?=\\s|,|<|$)`,"i").test(t)}function mp(t,e){let n=[],s=(c,a,l)=>{n.push({to:c,kind:a,sourceEvidence:l})},i=ri(t,/\bclass\s+([A-Za-z][A-Za-z0-9_]*)\b/gi)?.[1],o=ri(t,/@RestResource\s*\(\s*urlMapping\s*=\s*(["'])([^"']+)\1\s*\)/gi);if(o)for(let c of t.matchAll(/@Http(Get|Post|Put|Patch|Delete)\b[\s\S]{0,300}?\b(?:global|public)\s+static\s+[^({;]+?\s+[A-Za-z][A-Za-z0-9_]*\s*\(/gi)){if(!Ve(t,c.index??0))continue;let a=c[0].match(/^@Http(?:Get|Post|Put|Patch|Delete)/i)?.[0];a&&s(`REST ${c[1].toUpperCase()} ${o[2]}`,"apex_rest_entry",`${o[0].trim()}; ${a}`)}if(i){for(let a of t.matchAll(/\b(?:global|public)\s+static\s+webService\s+[^({;]+?\s+([A-Za-z][A-Za-z0-9_]*)\s*\(/gi))Ve(t,a.index??0)&&s(`SOAP ${i}.${a[1]}`,"apex_soap_entry",a[0].trim());for(let a of t.matchAll(/@InvocableMethod\b[\s\S]{0,300}?\b(?:global|public)\s+static\s+[^({;]+?\s+([A-Za-z][A-Za-z0-9_]*)\s*\(/gi))Ve(t,a.index??0)&&s(`ApexAction ${i}.${a[1]}`,"apex_invocable_entry",a[0].trim());for(let a of t.matchAll(/@future\b[\s\S]{0,300}?\b(?:global|public)\s+static\s+[^({;]+?\s+([A-Za-z][A-Za-z0-9_]*)\s*\(/gi))Ve(t,a.index??0)&&s(`${i}.${a[1]}`,"apex_async_callback",a[0].trim());let c=ri(t,new RegExp(`\\bclass\\s+${i}\\b[^{}]*\\bimplements\\b([^{}]+)`,"gis"))?.[1];if(c){let a=[{interfaceName:"Queueable",methods:["execute"]},{interfaceName:"Database.Batchable",methods:["start","execute","finish"]},{interfaceName:"Schedulable",methods:["execute"]}];for(let l of a)if(fp(c,l.interfaceName))for(let u of l.methods)up(t,u)&&s(`${i}.${u}`,"apex_async_callback",`class ${i} implements ${l.interfaceName}; ${u}(...) declaration`)}}for(let c of t.matchAll(/\btrigger\s+([A-Za-z][A-Za-z0-9_]*)\s+on\s+([A-Za-z][A-Za-z0-9_]*)\s*\(([^)]+)\)/gi))if(Ve(t,c.index??0))for(let a of c[3].split(",").map(l=>l.trim())){let l=a.match(/^(before|after)\s+(insert|update|delete|undelete)$/i);if(!l)continue;let u=`${c[2]}.${l[1].toLowerCase()}${l[2][0].toUpperCase()}${l[2].slice(1).toLowerCase()}`,f=c[0].trim();s(u,"apex_trigger_entry",f),(c[2].toLowerCase().endsWith("__e")||c[2].toLowerCase().endsWith("changeevent"))&&s(u,"apex_platform_event_subscription",f)}let r=[/\bSystem\.enqueueJob\s*\(\s*new\s+([A-Za-z][A-Za-z0-9_]*)\s*\(/gi,/\bDatabase\.executeBatch\s*\(\s*new\s+([A-Za-z][A-Za-z0-9_]*)\s*\(/gi];for(let c of r)for(let a of t.matchAll(c)){if(!Ve(t,a.index??0))continue;let l=Zn(a[1],e);l&&s(l,"apex_enqueue",a[0].trim().replace(a[1],"CLASS"))}for(let c of t.matchAll(/\bSystem\.schedule\s*\(/gi)){if(!Ve(t,c.index??0))continue;let a=(c.index??0)+c[0].length-1,l=dp(t,a);if(l===null)continue;let u=Pt(t.slice(a+1,l));if(u.length!==3)continue;let f=u[2].match(/^new\s+([A-Za-z][A-Za-z0-9_]*)\s*\(/);if(!f)continue;let m=Zn(f[1],e);m&&s(m,"apex_enqueue",`System.schedule(${u[0]}, ${u[1]}, new CLASS(`)}for(let c of t.matchAll(/\bFunctions\.Function\.get\s*\(\s*(["'])([A-Za-z][A-Za-z0-9_-]*)\1\s*\)\s*\.invoke\s*\(/gi))Ve(t,c.index??0)&&s(`SalesforceFunction:${c[2]}`,"apex_function_invocation",c[0].trim());return n}async function pp(t,e,n,s,i){let o=[],r=(a,l,u)=>{o.push({to:a,kind:l,confidence:1,sourceEvidence:u})},c=(a,l,u,f)=>{let m=l.includes(".")?l:`${a}.${l}`;Un(m)&&r(m,u,f)};switch(i.type){case"object":r(i.object,"salesforce_metadata_object","Salesforce DX CustomObject file path");break;case"field":r(`${i.object}.${i.field}`,"salesforce_metadata_field","Salesforce DX CustomField file path");break;case"recordType":r(`${i.object}.${i.recordType}`,"salesforce_record_type","Salesforce DX RecordType file path");break;case"permissionSet":for(let a of tt(t,"object"))Un(a.value)&&r(a.value,"permission_set_object",a.evidence);for(let a of tt(t,"field"))Un(a.value)&&r(a.value,"permission_set_field",a.evidence);for(let a of tt(t,"recordType"))Un(a.value)&&r(a.value,"permission_set_record_type",a.evidence);for(let a of tt(t,"apexClass")){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(a.value))continue;let l=Zn(a.value,n);l&&r(l,"permission_set_apex",a.evidence)}break;case"flow":{for(let a of t.matchAll(/<start>([\s\S]*?)<\/start>/g))if(/<recordTriggerType>[^<]+<\/recordTriggerType>/.test(a[1]))for(let l of tt(a[1],"object"))Un(l.value)&&r(l.value,"flow_trigger_object",l.evidence);for(let a of tt(t,"field"))a.value.includes(".")&&c("",a.value,"flow_field_reference",a.evidence);for(let a of t.matchAll(/<actionCalls>([\s\S]*?)<\/actionCalls>/g))if(/<actionType>apex<\/actionType>/.test(a[1]))for(let l of tt(a[1],"actionName")){let u=l.value.match(/^([A-Za-z][A-Za-z0-9_]*)\.([A-Za-z][A-Za-z0-9_]*)$/);if(!u)continue;let f=Ic(u[1],u[2],n);f&&r(f,"flow_apex_action",l.evidence)}for(let a of tt(t,"extensionName")){let l=a.value.match(/^c:([A-Za-z][A-Za-z0-9_]*)$/);if(!l)continue;let u=Xo(l[1],n);u&&r(u,"flow_screen_component",a.evidence)}break}case"workflow":r(i.object,"workflow_object","Salesforce DX workflow object file path");for(let a of tt(t,"field"))c(i.object,a.value,"workflow_field",a.evidence);break;case"approval":r(i.object,"approval_object","Salesforce DX approval-process file path");for(let a of tt(t,"field"))c(i.object,a.value,"approval_field",a.evidence);break}s.run("BEGIN TRANSACTION;");try{s.run('DELETE FROM "references" WHERE callerFile = ?',[e]),ye(s,e),s.run("DELETE FROM dependencies WHERE fromFile = ?",[e]),s.run("DELETE FROM mcp_tools WHERE filePath = ?",[e]),s.run(`INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
128
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[P.basename(e,".xml"),"salesforce-metadata",e,1,t.split(`
129
+ `).length,0,0,"Salesforce DX metadata (static declarations only; formulas and runtime targets are not resolved)."]);let a=new Set,l=s.prepare("INSERT INTO dependencies (fromFile, toFile, kind, confidence, sourceEvidence) VALUES (?, ?, ?, ?, ?)");for(let u of o){let f=`${u.to}\0${u.kind}`;a.has(f)||(a.add(f),l.run(e,u.to,u.kind,u.confidence,u.sourceEvidence))}l.finalize(),s.run("COMMIT;")}catch(a){throw s.run("ROLLBACK;"),a}}async function hp(t,e,n,s,i){let o=[{to:i.bundlePath,kind:"lwc_bundle_member"}],r=[];if(i.extension==="js"){let c=new Map;for(let l of t.matchAll(/import\s+([\s\S]*?)\s+from\s+["']([^"']+)["']/g)){let u=l[1].trim(),f=l[2],m=l.index??0;if(!Ve(t,m))continue;if(f.startsWith("c/")){let g=f.slice(2);if(/^[A-Za-z][A-Za-z0-9_]*$/.test(g)){let h=ap(e,g,n);h&&o.push({to:h,kind:"lwc_component"})}continue}let d=f.match(/^@salesforce\/apex\/([A-Za-z][A-Za-z0-9_]*)\.([A-Za-z][A-Za-z0-9_]*)$/);if(d&&!f.includes("__")){let g=Ic(d[1],d[2],n);if(g){o.push({to:g,kind:"apex_method"});let h=Ke(t,m);r.push({callee:d[2],calleeFile:g,line:h.line,column:h.column})}continue}let y=f.match(/^@salesforce\/schema\/([^/]+)$/);if(y&&cp(y[1])){o.push({to:y[1],kind:y[1].includes(".")?"salesforce_schema_field":"salesforce_schema_object"});continue}if(f.startsWith("lightning/"))for(let g of u.matchAll(/(?:\{|,)\s*([A-Za-z_$][\w$]*)/g))g[1]&&c.set(g[1],f)}let a=new Set(["getRecord","getRecordUi","getObjectInfo","getPicklistValues","getPicklistValuesByRecordType","getListUi"]);for(let l of t.matchAll(/@wire\s*\(\s*([A-Za-z_$][\w$]*)/g)){let u=l[1],f=c.get(u);f&&a.has(u)&&o.push({to:`${f}#${u}`,kind:"wire_adapter"})}}if(i.extension==="html"){let c=t.replace(/<!--[\s\S]*?-->/g,a=>a.replace(/[^\n]/g," "));for(let a of c.matchAll(/<(lightning-record-(?:form|view-form|edit-form|picker))\b/gi))o.push({to:a[1].toLowerCase(),kind:"lightning_data_service"})}s.run("BEGIN TRANSACTION;");try{s.run('DELETE FROM "references" WHERE callerFile = ?',[e]),ye(s,e),s.run("DELETE FROM dependencies WHERE fromFile = ?",[e]),s.run("DELETE FROM mcp_tools WHERE filePath = ?",[e]),i.extension==="js"&&s.run(`INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
130
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[i.componentName,"lwc-component",e,1,t.split(`
131
+ `).length,0,0,"Salesforce Lightning Web Component bundle entry point (static source relationships only)."]);let c=s.prepare(`INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column, kind)
132
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let u of r)c.run(i.componentName,e,u.callee,u.calleeFile,u.line,u.column,"apex_method");c.finalize();let a=new Set,l=s.prepare("INSERT INTO dependencies (fromFile, toFile, kind, confidence) VALUES (?, ?, ?, ?)");for(let u of o){let f=`${u.to}\0${u.kind}`;a.has(f)||(a.add(f),l.run(e,u.to,u.kind,1))}l.finalize(),s.run("COMMIT;")}catch(c){throw s.run("ROLLBACK;"),c}}function gp(t,e){let n=P.extname(e).toLowerCase();return n===".clp"||n===".ws"?!0:n===".xml"?t.includes('xmlns:cc="http://www.workday.com/')||t.includes('xmlns:wd="urn:com.workday')||t.includes("<cc:")||t.includes("<wd:")||t.includes("<integration")||t.includes("workday-out")||t.includes("workday-in"):!1}function yp(t){let e=t.toLowerCase();return e.endsWith("step")||e.endsWith("route")||e.endsWith("splitter")||e.endsWith("aggregator")||e.endsWith("send")||e.endsWith("eval")}function hc(t){let e={table:null,fields:[],parameters:[]},n=t.match(/FROM\s+([a-zA-Z0-9_]+)/i);n&&(e.table=n[1]);let s=t.match(/SELECT\s+(.+?)\s+FROM/i);if(s){let o=s[1],r="",c=0;for(let l=0;l<o.length;l++){let u=o[l];if(u==="{")c++,r+=u;else if(u==="}")c--,r+=u;else if(u===","&&c===0){let f=r.trim();f&&e.fields.push(f),r=""}else r+=u}let a=r.trim();a&&e.fields.push(a)}let i=t.matchAll(/(?:\?([0-9a-zA-Z_]+)?|:([a-zA-Z0-9_]+)|@\{([a-zA-Z0-9_]+)\})/g);for(let o of i){let r=o[1]||o[2]||o[3]||"?";e.parameters.includes(r)||e.parameters.push(r)}return e}async function bp(t,e,n,s){let o=q.readFileSync(t,"utf-8").split(`
133
+ `).filter(h=>h.trim().length>0),r=new Map,c=new Map,a=new Map,l=new Map,u=new Map,f=new Map,m=new Map,d=new Map,y=new Map;for(let h of o)try{let w=JSON.parse(h);if(w.type==="vertex"){if(w.label==="document")r.set(w.id.toString(),w.uri);else if(w.label==="range")c.set(w.id.toString(),{docId:"",line:w.start.line+1,col:w.start.character+1,endLine:w.end.line+1,endCol:w.end.character+1});else if(w.label==="hoverResult"){let k="";w.result?.contents&&(Array.isArray(w.result.contents)?k=w.result.contents.map(_=>typeof _=="object"&&_!==null&&"value"in _&&_.value||_).join(`
134
+ `):w.result.contents.value?k=w.result.contents.value:k=String(w.result.contents)),a.set(w.id.toString(),k)}}else if(w.type==="edge"){let k=w.outV.toString(),_=w.inVs?w.inVs.map(R=>String(R)):[w.inV.toString()];if(w.label==="contains")for(let R of _){let v=c.get(R);v&&(v.docId=k)}else if(w.label==="next")for(let R of _)l.set(k,R);else if(w.label==="textDocument/hover")for(let R of _)u.set(k,R);else if(w.label==="textDocument/definition")for(let R of _)d.set(k,R);else if(w.label==="textDocument/references")for(let R of _)y.set(k,R);else if(w.label==="item"){let R=w.document?w.document.toString():null;for(let v of _)if(f.has(k)||f.set(k,[]),f.get(k)?.push(v),m.has(k)||m.set(k,[]),m.get(k)?.push(v),R){let S=c.get(v);S&&(S.docId=R)}}}}catch{}let g=h=>(h.startsWith("file://")&&(h=h.substring(7)),h.startsWith(n)&&(h=h.substring(n.length+1)),h);s.run("BEGIN TRANSACTION;");try{let h=s.prepare(`
135
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
136
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
137
+ `),w=s.prepare(`
138
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column)
139
+ VALUES (?, ?, ?, NULL, ?, ?)
140
+ `),k=s.prepare(`
141
+ INSERT INTO dependencies (fromFile, toFile, kind, confidence)
142
+ VALUES (?, ?, ?, ?)
143
+ `);for(let[_,R]of l.entries()){let v=d.get(R);if(!v||!(f.get(v)||[]).includes(_))continue;let E=c.get(_);if(!E?.docId)continue;let $=r.get(E.docId);if(!$)continue;let p=g($),F=u.get(R),L=F&&a.get(F)||null,T=`symbol_${_}`,x="LSIF_Symbol";if(L){let M=L.split(`
144
+ `);if(M.length>0){let b=M[0].replace(/```\w*/,"").trim(),A=b.match(/(?:function|class|interface|const|let|var)\s+([a-zA-Z0-9_]+)/);A?T=A[1]:T=b.split(" ")[0]||T}}h.run(T,x,p,E.line,E.endLine,E.col,E.endCol,L);let I=y.get(R);if(I){let M=m.get(I)||[];for(let b of M){if(b===_)continue;let A=c.get(b);if(!A?.docId)continue;let C=r.get(A.docId);if(!C)continue;let O=g(C);w.run(null,O,T,A.line,A.col),O!==p&&k.run(O,p,"lsif_import",1)}}}h.finalize(),w.finalize(),k.finalize(),s.run("COMMIT;")}catch(h){s.run("ROLLBACK;"),console.error("Error indexing LSIF:",h)}}function wp(t,e,n){let s=[...new Set(n.symbols.map(c=>c.filePath))].sort(),i=t.prepare(`
145
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
146
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
147
+ `),o=t.prepare(`
148
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column, kind, confidence)
149
+ VALUES (?, ?, ?, ?, ?, ?, ?, 1.0)
150
+ `),r=t.prepare(`
151
+ INSERT INTO dependencies (fromFile, toFile, kind, confidence, sourceEvidence)
152
+ VALUES (?, ?, 'scip_import', 1.0, ?)
153
+ `);t.run("BEGIN TRANSACTION;");try{t.run("DELETE FROM symbols WHERE kind LIKE 'SCIP_%'"),t.run(`DELETE FROM "references" WHERE kind LIKE 'scip_%'`),t.run("DELETE FROM dependencies WHERE kind = 'scip_import'");for(let a of n.symbols)i.run(a.name,a.kind,a.filePath,a.startLine,a.endLine,a.startCol,a.endCol,JSON.stringify({provenance:"scip",symbol:a.symbol}));let c=new Set;for(let a of n.references)if(o.run(a.callerSymbol,a.callerFile,a.calleeSymbol,a.calleeFile,a.line,a.column,a.kind),a.kind==="scip_reference"&&a.callerFile!==a.calleeFile){let l=`${a.callerFile}\0${a.calleeFile}`;c.has(l)||(c.add(l),r.run(a.callerFile,a.calleeFile,JSON.stringify({provenance:"scip",input:n.inputPath})))}t.run("COMMIT;")}catch(c){throw t.run("ROLLBACK;"),c}finally{i.finalize(),o.finalize(),r.finalize()}return zt(t,e,s),s}function Sp(t){if(t.query("SELECT 1 AS present FROM symbols WHERE kind LIKE 'SCIP_%' LIMIT 1").get()){t.run("BEGIN TRANSACTION;");try{t.run("DELETE FROM symbols WHERE kind LIKE 'SCIP_%'"),t.run(`DELETE FROM "references" WHERE kind LIKE 'scip_%'`),t.run("DELETE FROM dependencies WHERE kind = 'scip_import'"),t.run("COMMIT;")}catch(n){throw t.run("ROLLBACK;"),n}}}async function Ep(t,e,n,s){let i=[],o=[],r=[],c=t.split(`
154
+ `),a=/^\s*(resource|data|module)\s+"([^"]+)"\s+"([^"]+)"\s*\{/i,l=/^\s*(resource|data|module)\s+"([^"]+)"\s*\{/i;for(let u=0;u<c.length;u++){let f=c[u],m=f.match(a);if(m){let d=m[1],y=m[2],g=m[3],h=`${y}.${g}`;i.push({name:h,kind:d==="resource"?"Resource":d==="data"?"Data":"Block",startLine:u+1,endLine:u+1,startCol:1,endCol:f.length+1,summary:`Terraform ${d} ${h}`})}else if(m=f.match(l),m){let d=m[1],y=m[2];i.push({name:y,kind:d==="module"?"Module":"Block",startLine:u+1,endLine:u+1,startCol:1,endCol:f.length+1,summary:`Terraform ${d} ${y}`})}}s.run("BEGIN TRANSACTION;");try{s.run('DELETE FROM "references" WHERE callerFile = ?',[e]),ye(s,e),s.run("DELETE FROM dependencies WHERE fromFile = ?",[e]);let u=s.prepare(`
155
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
156
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
157
+ `);for(let d of i)u.run(d.name,d.kind,e,d.startLine,d.endLine,d.startCol,d.endCol,d.summary);let f=s.prepare(`
158
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column)
159
+ VALUES (?, ?, ?, NULL, ?, ?)
160
+ `);for(let d of o)f.run(d.callerSymbol,e,d.calleeSymbol,d.line,d.column);let m=s.prepare(`
161
+ INSERT INTO dependencies (fromFile, toFile, kind, confidence)
162
+ VALUES (?, ?, ?, ?)
163
+ `);for(let d of r)m.run(e,d.toFile,d.kind,d.confidence);u.finalize(),f.finalize(),m.finalize(),s.run("COMMIT;")}catch(u){throw s.run("ROLLBACK;"),u}}async function kp(t,e,n,s){let i=[],o="main",r=t.split(`
164
+ `),c=/^FROM\s+([^\s]+)(?:\s+AS\s+([^\s]+))?/i;for(let a=0;a<r.length;a++){let l=r[a].trim(),u=l.match(c);u&&(u[2]&&(o=u[2]),i.push({name:o==="main"?"Dockerfile":o,kind:"ContainerStage",startLine:a+1,endLine:a+1,startCol:1,endCol:l.length+1,summary:`Docker image stage: ${o}`}))}i.length===0&&i.push({name:"Dockerfile",kind:"Container",startLine:1,endLine:r.length,startCol:1,endCol:1,summary:"Docker container build file"}),s.run("BEGIN TRANSACTION;");try{s.run('DELETE FROM "references" WHERE callerFile = ?',[e]),ye(s,e),s.run("DELETE FROM dependencies WHERE fromFile = ?",[e]);let a=s.prepare(`
165
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
166
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
167
+ `);for(let l of i)a.run(l.name,l.kind,e,l.startLine,l.endLine,l.startCol,l.endCol,l.summary);a.finalize(),s.run("COMMIT;")}catch(a){throw s.run("ROLLBACK;"),a}}async function vp(t,e,n,s,i){let o=[],r=[],c=[],a=(w,k,_)=>{c.some(R=>R.toFile===w&&R.kind===k)||c.push({toFile:w,kind:k,confidence:_})},l=(w,k,_,R)=>{r.some(v=>v.callerSymbol===w&&v.calleeSymbol===k&&v.line===_)||r.push({callerSymbol:w,calleeSymbol:k,line:_,column:R})};function u(w,k=null){let _=k;if(w.type==="element"){let R=w.children.find(v=>v.type==="STag"||v.type==="EmptyElemTag");if(R){let v=R.children.find(S=>S.type==="Name");if(v){let S=v.text,E={};for(let F of R.children)if(F.type==="Attribute"){let L=F.children.find(x=>x.type==="Name"),T=F.children.find(x=>x.type==="AttValue");if(L&&T){let x=L.text,I=T.text.replace(/^['"`]|['"`]$/g,"").trim();E[x]=I}}let $=S.includes("cc:")||S.includes("wd:")||S.includes("ws:"),p=["integration","component","step","route","splitter","aggregator","mediator","workday-out","workday-in","local-out","local-in","wql","mvel"].includes(S.toLowerCase());if($||p){let F=E.id||E.name,L=E.name||E.id||S;if(F){let x=yp(S)?"orchestration-step":"component",I=w.startPosition.row+1,M=w.endPosition.row+1,b=w.startPosition.column,A=w.endPosition.column;o.push({name:L,kind:x,startLine:I,endLine:M,startCol:b,endCol:A,summary:`Workday Studio ${x} (${S}) with ID/Name "${L}"`}),_=L,k&&k!==L&&l(k,L,I,b)}if(E.operation){let x=E.operation;a(x,"wws",1),_&&l(_,x,w.startPosition.row+1,w.startPosition.column)}let T=w.children.find(x=>x.type==="content");if(T)for(let x=0;x<T.childCount;x++){let I=T.child(x);if(I&&I.type==="element"){let M=I.children.find(b=>b.type==="STag"||b.type==="EmptyElemTag");if(M){let b=M.children.find(A=>A.type==="Name");if(b){let A=b.text;if(A.endsWith("operation")){let C=I.children.find(N=>N.type==="content"),O=C?C.text.trim():"";O&&(a(O,"wws",1),_&&l(_,O,I.startPosition.row+1,I.startPosition.column))}else if(A.endsWith("query")){let C=I.children.find(N=>N.type==="content"),O=C?C.text.trim():"";if(O){let N=hc(O);N.table&&(a(N.table,"wql",1),_&&l(_,N.table,I.startPosition.row+1,I.startPosition.column))}}}}}}}}}}for(let R=0;R<w.childCount;R++){let v=w.child(R);v&&(w.type==="element"&&v.type==="content"?u(v,_):u(v,k))}}u(e.rootNode);let f=/operation\s*=\s*["']([^"']+)["']/gi,m=t.matchAll(f);for(let w of m){let k=w[1].trim();a(k,"wws",1)}let d=/<(?:[a-zA-Z0-9_]+:)?operation[^>]*>([^<]+)<\/(?:[a-zA-Z0-9_]+:)?operation>/gi,y=t.matchAll(d);for(let w of y){let k=w[1].trim();a(k,"wws",1)}let g=/SELECT\s+([\s\S]+?)\s+FROM\s+([a-zA-Z0-9_]+)/gi,h=t.matchAll(g);for(let w of h){let k=w[0],_=w[2].trim(),v=hc(k).table||_;v&&a(v,"wql",.8)}i.run("BEGIN TRANSACTION;");try{i.run('DELETE FROM "references" WHERE callerFile = ?',[n]),ye(i,n),i.run("DELETE FROM dependencies WHERE fromFile = ?",[n]);let w=P.basename(n,P.extname(n));o.push({name:w,kind:"component",startLine:1,endLine:t.split(`
168
+ `).length||1,startCol:0,endCol:0,summary:`Workday Studio Orchestration File: ${w}`});let k=i.prepare(`
169
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
170
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
171
+ `);for(let S of o)k.run(S.name,S.kind,n,S.startLine,S.endLine,S.startCol,S.endCol,S.summary);k.finalize();let _=i.prepare(`
172
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column)
173
+ VALUES (?, ?, ?, ?, ?, ?)
174
+ `),R=new Set(o.map(S=>S.name));for(let S of r)_.run(S.callerSymbol,n,S.calleeSymbol,R.has(S.calleeSymbol)?n:null,S.line,S.column);_.finalize();let v=i.prepare(`
175
+ INSERT INTO dependencies (fromFile, toFile, kind, confidence)
176
+ VALUES (?, ?, ?, ?)
177
+ `);for(let S of c)v.run(n,S.toFile,S.kind,S.confidence);v.finalize(),i.run("COMMIT;")}catch(w){throw i.run("ROLLBACK;"),w}}async function xp(t,e,n,s,i){let o=[{to:i.bundlePath,kind:"aura_bundle_member",sourceEvidence:"Aura bundle file path"}];if(i.extension==="cmp"){let r=t.replace(/<!--[\s\S]*?-->/g,l=>l.replace(/[^\n]/g," ")),a=r.match(/<aura:component\b[^>]*>/i)?.[0]?.match(/\bcontroller\s*=\s*["']([A-Za-z][A-Za-z0-9_]*)["']/i)?.[1];if(a){let l=Zn(a,n);l&&o.push({to:l,kind:"aura_apex_controller",sourceEvidence:`controller="${a}"`})}for(let l of r.matchAll(/<c:([A-Za-z][A-Za-z0-9_]*)\b/g)){let u=Xo(l[1],n);u&&o.push({to:u,kind:"aura_lwc_component",sourceEvidence:l[0]})}}s.run("BEGIN TRANSACTION;");try{s.run('DELETE FROM "references" WHERE callerFile = ?',[e]),ye(s,e),s.run("DELETE FROM dependencies WHERE fromFile = ?",[e]),s.run("DELETE FROM mcp_tools WHERE filePath = ?",[e]),s.run(`INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
178
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[i.componentName,"aura-component",e,1,t.split(`
179
+ `).length,0,0,"Salesforce Aura bundle member (static containment and declared bridges only)."]);let r=new Set,c=s.prepare("INSERT INTO dependencies (fromFile, toFile, kind, confidence, sourceEvidence) VALUES (?, ?, ?, ?, ?)");for(let a of o){let l=`${a.to}\0${a.kind}`;r.has(l)||(r.add(l),c.run(e,a.to,a.kind,1,a.sourceEvidence))}c.finalize(),s.run("COMMIT;")}catch(r){throw s.run("ROLLBACK;"),r}}async function Tp(t,e,n,s,i){let o=[],r=(a,l,u)=>{a&&o.push({to:a,kind:l,sourceEvidence:u})},c={};if(i.type!=="asset")try{let a=JSON.parse(t);if(!a||typeof a!="object"||Array.isArray(a))return;c=a}catch{return}if(i.type==="lwrConfig"){let a=qo(c.site);if(a){let l=`force-app/main/default/experiences/${a}`;q.existsSync(P.join(n,l))&&r(l,"lwr_site_config",'"site" static LWR configuration')}}else if(i.type==="route")r(i.sitePath,"experience_site_route","Experience Bundle route file path"),qo(c.path)&&r(qs(i.sitePath,"views",c.view,n),"experience_route_view",'"view" static route declaration');else if(i.type==="view"){if(r(ip(c.component,n),"experience_view_component",'"component" static view declaration'),r(qs(i.sitePath,"themes",c.theme,n),"experience_view_theme",'"theme" static view declaration'),Array.isArray(c.assets))for(let a of c.assets)r(qs(i.sitePath,"assets",a,n),"experience_view_asset",'"assets" static view declaration')}else if(i.type==="theme"&&Array.isArray(c.assets))for(let a of c.assets)r(qs(i.sitePath,"assets",a,n),"experience_theme_asset",'"assets" static theme declaration');s.run("BEGIN TRANSACTION;");try{s.run('DELETE FROM "references" WHERE callerFile = ?',[e]),ye(s,e),s.run("DELETE FROM dependencies WHERE fromFile = ?",[e]),s.run("DELETE FROM mcp_tools WHERE filePath = ?",[e]),s.run(`INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
180
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[P.basename(e),"salesforce-experience",e,1,t.split(`
181
+ `).length,0,0,"Salesforce LWR/Experience Bundle topology (static declarations only)."]);let a=new Set,l=s.prepare("INSERT INTO dependencies (fromFile, toFile, kind, confidence, sourceEvidence) VALUES (?, ?, ?, ?, ?)");for(let u of o){let f=`${u.to}\0${u.kind}`;a.has(f)||(a.add(f),l.run(e,u.to,u.kind,1,u.sourceEvidence))}l.finalize(),s.run("COMMIT;")}catch(a){throw s.run("ROLLBACK;"),a}}async function Rp(t,e,n,s,i){let o=new Set,r=[],c=[];function a(d){if(d.type==="element"||d.type==="start_tag"){let y=d.childForFieldName("name")||d.children.find(g=>g.type==="tag_name");if(y&&(y.text==="apex:page"||y.text==="apex:component")){for(let g of d.children)if(g.type==="attribute"){let h=g.childForFieldName("name")||g.children.find(k=>k.type==="attribute_name"),w=g.childForFieldName("value")||g.children.find(k=>k.type==="attribute_value");if(h&&w){let k=h.text.toLowerCase(),_=w.text.replace(/^['"`]|['"`]$/g,"").trim();if(k==="controller")o.add(_);else if(k==="extensions"){let R=_.split(",").map(v=>v.trim()).filter(Boolean);for(let v of R)r.push(v)}}}}}for(let y=0;y<d.childCount;y++){let g=d.child(y);g&&a(g)}}a(e.rootNode);let l=/<apex:(page|component)[^>]*>/gi,u=t.matchAll(l);for(let d of u){let y=d[0],g=y.match(/controller\s*=\s*["']([^"']+)["']/i);g?.[1]&&o.add(g[1].trim());let h=y.match(/extensions\s*=\s*["']([^"']+)["']/i);if(h?.[1]){let w=h[1].split(",").map(k=>k.trim()).filter(Boolean);for(let k of w)r.includes(k)||r.push(k)}}let f=/\{!\s*([^}]+)\}/g,m=t.matchAll(f);for(let d of m){let g=d[1].match(/[a-zA-Z_][a-zA-Z0-9_]*/g);if(g)for(let h of g){if(["true","false","null","and","or","not","if"].includes(h.toLowerCase()))continue;let{line:w,column:k}=Ke(t,d.index??0);c.push({callerSymbol:null,calleeSymbol:h,line:w,column:k})}}i.run("BEGIN TRANSACTION;");try{i.run('DELETE FROM "references" WHERE callerFile = ?',[n]),ye(i,n),i.run("DELETE FROM dependencies WHERE fromFile = ?",[n]);let d=P.basename(n,P.extname(n));i.run(`
182
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
183
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
184
+ `,[d,"page",n,1,t.split(`
185
+ `).length,0,0,`Visualforce page associated with controllers: ${Array.from(o).join(", ")}`]);let y=i.prepare(`
186
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column)
187
+ VALUES (?, ?, ?, NULL, ?, ?)
188
+ `);for(let w of c)y.run(w.callerSymbol,n,w.calleeSymbol,w.line,w.column);y.finalize();let g=i.prepare(`
189
+ INSERT INTO dependencies (fromFile, toFile, kind, confidence, sourceEvidence)
190
+ VALUES (?, ?, ?, ?, ?)
191
+ `),h=[...Array.from(o,w=>({className:w,attribute:"controller"})),...r.map(w=>({className:w,attribute:"extensions"}))];for(let{className:w,attribute:k}of h){let R=sp(w,s)||w;g.run(n,R,"controller",1,`${k}="${w}"`)}g.finalize(),i.run("COMMIT;")}catch(d){throw i.run("ROLLBACK;"),d}}async function $p(t,e,n,s,i){let o=[],r=[],c=[];function a(d){if(d.type==="create_table"){let g=d.childForFieldName("name")||d.children.find(w=>w.type==="object_reference")||d.children.find(w=>w.type==="identifier"),h=g?g.text.replace(/["`]/g,"").trim():"";if(h){let k=function(_){if(_.type==="column_definition"){let R=_.childForFieldName("name")||_.children.find(v=>v.type==="identifier");R&&w.push(R.text.replace(/["`]/g,"").trim())}for(let R=0;R<_.childCount;R++){let v=_.child(R);v&&k(v)}};var y=k;let w=[];k(d),o.push({name:h,kind:"table",startLine:d.startPosition.row+1,endLine:d.endPosition.row+1,startCol:d.startPosition.column,endCol:d.endPosition.column,summary:`Table "${h}" with columns: ${w.join(", ")}`})}}else if(d.type==="create_view"){let g=d.childForFieldName("name")||d.children.find(w=>w.type==="object_reference")||d.children.find(w=>w.type==="identifier"),h=g?g.text.replace(/["`]/g,"").trim():"";h&&o.push({name:h,kind:"view",startLine:d.startPosition.row+1,endLine:d.endPosition.row+1,startCol:d.startPosition.column,endCol:d.endPosition.column,summary:`Database view: ${h}`})}if(d.type==="relation"||d.type==="object_reference"){let g=d.text.replace(/["`]/g,"").trim();g&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)&&r.push({callerSymbol:null,calleeSymbol:g,line:d.startPosition.row+1,column:d.startPosition.column})}for(let g=0;g<d.childCount;g++){let h=d.child(g);h&&a(h)}}a(e.rootNode);let l=/CREATE\s+(?:OR\s+REPLACE\s+)?(PROCEDURE|PROC|FUNCTION|TRIGGER)\s+([a-zA-Z0-9_]+)/gi,u=l.exec(t);for(;u!==null;){let d=u[1].toLowerCase(),y=u[2],g=d==="proc"?"procedure":d,{line:h,column:w}=Ke(t,u.index);o.push({name:y,kind:g,startLine:h,endLine:h,startCol:w,endCol:w+y.length,summary:`Database ${g}: ${y}`}),u=l.exec(t)}let f=/(?:FROM|JOIN|INTO|UPDATE)\s+([a-zA-Z0-9_]+)/gi,m=f.exec(t);for(;m!==null;){let d=m[1];["select","insert","update","delete","where","join","from","into"].includes(d.toLowerCase())||c.push({from:n,to:d,kind:"lineage"}),m=f.exec(t)}i.run("BEGIN TRANSACTION;");try{i.run('DELETE FROM "references" WHERE callerFile = ?',[n]),ye(i,n),i.run("DELETE FROM dependencies WHERE fromFile = ?",[n]);let d=i.prepare(`
192
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
193
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
194
+ `);for(let h of o)d.run(h.name,h.kind,n,h.startLine,h.endLine,h.startCol,h.endCol,h.summary);d.finalize();let y=i.prepare(`
195
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column)
196
+ VALUES (?, ?, ?, NULL, ?, ?)
197
+ `);for(let h of r)y.run(h.callerSymbol,n,h.calleeSymbol,h.line,h.column);y.finalize();let g=i.prepare(`
198
+ INSERT INTO dependencies (fromFile, toFile, kind)
199
+ VALUES (?, ?, ?)
200
+ `);for(let h of c)g.run(h.from,h.to,h.kind);g.finalize(),i.run("COMMIT;")}catch(d){throw i.run("ROLLBACK;"),d}}async function _p(t,e,n,s,i){let o=[],r=[];function c(m){if(m.type==="model_declaration"){let d=m.children.find(y=>y.type==="identifier");if(d){let y=d.text;o.push({name:y,kind:"model",startLine:m.startPosition.row+1,endLine:m.endPosition.row+1,startCol:m.startPosition.column,endCol:m.endPosition.column,summary:`Prisma ORM Model: ${y}`});let g=m.children.find(h=>h.type==="statement_block");if(g)for(let h=0;h<g.childCount;h++){let w=g.child(h);if(w&&w.type==="column_declaration"){let k=w.childForFieldName("type")||w.children.find(_=>_.type==="column_type");if(k){let _=k.text.replace(/\[\]/,"").trim();w.text.includes("@relation")&&(r.push({from:y,to:_,kind:"orm-relation"}),r.push({from:n,to:_,kind:"orm-relation"}))}}}}}for(let d=0;d<m.childCount;d++){let y=m.child(d);y&&c(y)}}c(e.rootNode);let a=/model\s+([a-zA-Z0-9_]+)\s*\{([^}]+)\}/g,l=a.exec(t);for(;l!==null;){let m=l[1],d=l[2],y=/[a-zA-Z0-9_]+\s+([a-zA-Z0-9_]+)\s+@relation/g,g=y.exec(d);for(;g!==null;){let h=g[1];r.push({from:m,to:h,kind:"orm-relation"}),r.push({from:n,to:h,kind:"orm-relation"}),g=y.exec(d)}l=a.exec(t)}let u=new Set,f=r.filter(m=>{let d=`${m.from}|${m.to}|${m.kind}`;return u.has(d)?!1:(u.add(d),!0)});i.run("BEGIN TRANSACTION;");try{ye(i,n),i.run("DELETE FROM dependencies WHERE fromFile = ?",[n]);let m=i.prepare(`
201
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
202
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
203
+ `);for(let y of o)m.run(y.name,y.kind,n,y.startLine,y.endLine,y.startCol,y.endCol,y.summary);m.finalize();let d=i.prepare(`
204
+ INSERT INTO dependencies (fromFile, toFile, kind)
205
+ VALUES (?, ?, ?)
206
+ `);for(let y of f)d.run(y.from,y.to,y.kind);d.finalize(),i.run("COMMIT;")}catch(m){throw i.run("ROLLBACK;"),m}}function Mc(t){try{if(!t.includes('"metadata"')||!t.includes('"nodes"'))return!1;let e=JSON.parse(t);return e&&typeof e=="object"&&"metadata"in e&&("nodes"in e||"sources"in e||"exposures"in e)}catch{return!1}}function Ap(t){let e=t.split(".");return e.length>=3?e[0]==="source"?`${e[e.length-2]}.${e[e.length-1]}`:e[e.length-1]:t}async function Fp(t,e,n,s,i){try{let o=JSON.parse(t),r=P.join(s,".knodin/dbt");await q.promises.mkdir(r,{recursive:!0});let c=[];if(o.nodes&&typeof o.nodes=="object")for(let[l,u]of Object.entries(o.nodes)){let f=u.resource_type,m="";if(f==="model")m="dbt-model";else if(f==="seed")m="dbt-seed";else if(f==="test")m="dbt-test";else continue;let d=u.name||"",y=u.description||"No description provided.",g=u.database||"",h=u.schema||"",w=u.config?.materialized||"",k=u.depends_on?.nodes||[],_=u.compiled_code||u.raw_code||u.compiled_sql||u.raw_sql||"",R=`dbt ${f==="model"?"Model":f==="seed"?"Seed":"Test"}: ${d}
207
+ `;g&&(R+=`Database: ${g}
208
+ `),h&&(R+=`Schema: ${h}
209
+ `),w&&(R+=`Materialization: ${w}
210
+ `),R+=`Description: ${y}
211
+ `,k.length>0&&(R+=`Depends On: ${k.join(", ")}
212
+ `),c.push({unique_id:l,name:d,kind:m,description:y,database:g,schema:h,materialization:w,depends_on_nodes:k,sqlCode:_,summary:R})}if(o.sources&&typeof o.sources=="object")for(let[l,u]of Object.entries(o.sources)){let f=u.name||"",m=u.source_name||"",d=u.description||"No description provided.",y=u.database||"",g=u.schema||"",h=m?`${m}.${f}`:f,w=`dbt Source: ${h}
213
+ `;y&&(w+=`Database: ${y}
214
+ `),g&&(w+=`Schema: ${g}
215
+ `),w+=`Description: ${d}
216
+ `,c.push({unique_id:l,name:h,kind:"dbt-source",description:d,database:y,schema:g,depends_on_nodes:[],sqlCode:"",summary:w})}if(o.exposures&&typeof o.exposures=="object")for(let[l,u]of Object.entries(o.exposures)){let f=u.name||"",m=u.description||"No description provided.",d=u.depends_on?.nodes||[],y=u.type||"",g=u.owner?.name||u.owner?.email||"",h=`dbt Exposure: ${f}
217
+ `;y&&(h+=`Type: ${y}
218
+ `),g&&(h+=`Owner: ${g}
219
+ `),h+=`Description: ${m}
220
+ `,d.length>0&&(h+=`Depends On: ${d.join(", ")}
221
+ `),c.push({unique_id:l,name:f,kind:"dbt-exposure",description:m,depends_on_nodes:d,sqlCode:"",summary:h})}if(o.metrics&&typeof o.metrics=="object")for(let[l,u]of Object.entries(o.metrics)){let f=u.name||"",m=u.description||"No description provided.",d=u.depends_on?.nodes||[],y=`dbt Metric: ${f}
222
+ `;y+=`Description: ${m}
223
+ `,d.length>0&&(y+=`Depends On: ${d.join(", ")}
224
+ `),c.push({unique_id:l,name:f,kind:"dbt-metric",description:m,depends_on_nodes:d,sqlCode:"",summary:y})}let a=new Map;for(let l of c)a.set(l.unique_id,l);i.run("BEGIN TRANSACTION;");try{ic(i,".knodin/dbt/%"),i.run(`DELETE FROM "references" WHERE callerFile LIKE '.knodin/dbt/%'`),i.run("DELETE FROM dependencies WHERE fromFile LIKE '.knodin/dbt/%'"),ye(i,n),i.run('DELETE FROM "references" WHERE callerFile = ?',[n]),i.run("DELETE FROM dependencies WHERE fromFile = ?",[n]);let l=i.prepare(`
225
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
226
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
227
+ `),u=i.prepare(`
228
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column)
229
+ VALUES (?, ?, ?, ?, ?, ?)
230
+ `),f=i.prepare(`
231
+ INSERT INTO dependencies (fromFile, toFile, kind)
232
+ VALUES (?, ?, ?)
233
+ `);for(let m of c){let y=`.knodin/dbt/${m.unique_id.replace(/[/\\]/g,"_")}.sql`,g=P.join(s,y),h=m.sqlCode;h||(h=`-- dbt Kind: ${m.kind}
234
+ -- Name: ${m.name}
235
+ -- Unique ID: ${m.unique_id}
236
+
237
+ `,h+=m.summary.split(`
238
+ `).map(k=>`-- ${k}`).join(`
239
+ `)),q.writeFileSync(g,h,"utf-8");let w=h.split(`
240
+ `).length;l.run(m.name,m.kind,y,1,w,0,0,m.summary),l.run(m.unique_id,m.kind,y,1,w,0,0,m.summary);for(let k of m.depends_on_nodes){let _=a.get(k),v=`.knodin/dbt/${k.replace(/[/\\]/g,"_")}.sql`;f.run(y,v,"dbt-lineage");let S=_?_.name:Ap(k);u.run(m.name,y,S,v,1,1),u.run(m.unique_id,y,k,v,1,1)}}l.finalize(),u.finalize(),f.finalize(),i.run("COMMIT;")}catch(l){throw i.run("ROLLBACK;"),l}}catch(o){console.error(`Error indexing dbt manifest file ${n}:`,o)}}async function Jn(t,e,n,s){try{Sp(s);let i=P.basename(t).toLowerCase();if(i==="manifest.json"){let C=q.readFileSync(t,"utf-8");if(Mc(C)){await Fp(C,t,e,n,s);return}}if(t.endsWith(".lsif")||i==="dump.lsif"){await bp(t,e,n,s);return}if(t.endsWith(".tf")||t.endsWith(".tfvars")||t.endsWith(".hcl")){let C=q.readFileSync(t,"utf-8");await Ep(C,e,n,s);return}if(t.endsWith(".dockerfile")||i==="dockerfile"){let C=q.readFileSync(t,"utf-8");await kp(C,e,n,s);return}let c=Oc(e);if(c){let C=re("read",()=>q.readFileSync(t,"utf-8"));await Tp(C,e,n,s,c);return}let a=op(e);if(a){let C=re("read",()=>q.readFileSync(t,"utf-8"));await hp(C,e,n,s,a);return}let l=rp(e);if(l){let C=re("read",()=>q.readFileSync(t,"utf-8"));await xp(C,e,n,s,l);return}let u=lp(e);if(u){let C=re("read",()=>q.readFileSync(t,"utf-8"));await pp(C,e,n,s,u);return}let f=await Ue("parser_wasm_init",()=>Kn(t));if(!f)return;let m=re("read",()=>q.readFileSync(t,"utf-8"));if(Qm(m))return;let d=t.endsWith(".sql")||t.endsWith(".pkb")||t.endsWith(".pks"),y=d?ep(m):m,g=new we;g.setLanguage(f);let h;try{h=re("parse_extract",()=>g.parse(y))}catch(C){console.warn(`knodin: skipped ${e} (parser error: ${C.message})`);return}if(!h)return;let w=/\.[cm]?[jt]sx?$/.test(t)&&/@modelcontextprotocol\/sdk/.test(m)?Rc(m,e,h.rootNode):[],k=t.endsWith(".py"),_=t.endsWith(".cls")||t.endsWith(".trigger"),R=t.endsWith(".page")||t.endsWith(".component"),v=t.endsWith(".prisma");if(t.endsWith(".clp")||t.endsWith(".ws")||t.endsWith(".xml")&&gp(m,t)){await vp(m,h,e,n,s);return}if(R){await Rp(m,h,e,n,s);return}if(d){await $p(y,h,e,n,s);return}if(v){await _p(m,h,e,n,s);return}let{definitions:E,references:$,fileDependencies:p,tableDependencies:F,ormDependencies:L,importBindings:T,apiContracts:x}=re("parse_extract",()=>Ym(h.rootNode,k,_,t)),I=_?mp(m,n):[],M=new Set(E.map(C=>C.name)),b=(C,O)=>{let N=O===null?void 0:O??T.get(C);if(N){let j=Xn(e,N,n);return j?Wo(n,j,C,0):null}return M.has(C)?e:null},A=Vt("sqlite_write");s.run("BEGIN TRANSACTION;");try{s.run('DELETE FROM "references" WHERE callerFile = ?',[e]),ye(s,e),s.run("DELETE FROM dependencies WHERE fromFile = ?",[e]),s.run("DELETE FROM mcp_tools WHERE filePath = ?",[e]),s.run("DELETE FROM api_contracts WHERE filePath = ?",[e]);let C=s.prepare(`
241
+ INSERT INTO mcp_tools(name, description, schemaSymbol, handlerSymbol, filePath, line, confidence, associationKey)
242
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
243
+ `);for(let W of w)C.run(W.name,W.description??null,W.schemaSymbol??null,W.handlerSymbol??null,e,W.line,W.confidence,W.associationKey??null);C.finalize();let O=s.prepare(`
244
+ INSERT INTO symbols (name, kind, filePath, startLine, endLine, startCol, endCol, summary)
245
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
246
+ `);for(let W of E)O.run(W.name,W.kind,e,W.startLine,W.endLine,W.startCol,W.endCol,W.summary);O.finalize();let N=s.prepare(`
247
+ INSERT INTO "references" (callerSymbol, callerFile, calleeSymbol, calleeFile, line, column, kind)
248
+ VALUES (?, ?, ?, ?, ?, ?, ?)
249
+ `);for(let W of $)N.run(W.callerSymbol,e,W.calleeSymbol,b(W.calleeSymbol,W.calleeModule),W.line,W.column,W.kind??"call");N.finalize();let j=s.prepare(`
250
+ INSERT INTO api_contracts (kind, framework, method, path, origin, handler, middleware, responseFields, responseKnown, declaredResponseFields, accessedFields, unresolved, filePath, line, confidence, evidence)
251
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
252
+ `);for(let W of x)j.run(W.kind,W.framework,W.method,W.path,W.origin,W.handler,JSON.stringify(W.middleware),JSON.stringify(W.responseFields),W.responseKnown?1:0,JSON.stringify(W.declaredResponseFields),JSON.stringify(W.accessedFields),W.unresolved?1:0,e,W.line,W.confidence,W.evidence);j.finalize();let z=s.prepare(`
253
+ INSERT INTO dependencies (fromFile, toFile, kind)
254
+ VALUES (?, ?, ?)
255
+ `);for(let W of p){let X=fi(e,W,n);X&&z.run(e,X,"import")}if(F)for(let W of F)z.run(e,W,"table");if(L)for(let W of L)z.run(e,W.to,W.kind);z.finalize();let D=s.prepare("INSERT INTO dependencies (fromFile, toFile, kind, confidence, sourceEvidence) VALUES (?, ?, ?, ?, ?)"),H=new Set;for(let W of I){let X=`${W.to}\0${W.kind}`;H.has(X)||(H.add(X),D.run(e,W.to,W.kind,1,W.sourceEvidence))}D.finalize(),s.run("COMMIT;")}catch(C){throw s.run("ROLLBACK;"),C}finally{A()}}catch(i){console.error(`Error indexing file ${e}:`,i)}}var gc=1,Lp=32,yc=64*1024*1024;function Np(){let t=process.env.KNODIN_EMBEDDING_BATCH_SIZE;if(t===void 0)return gc;let e=Number(t);return Number.isInteger(e)?Math.max(1,Math.min(Lp,e)):gc}function Cp(t){let e=new Map,n=0,s=i=>{let o=P.resolve(t,i),r=e.get(o);if(r)return e.delete(o),e.set(o,r),r.lines;let c;try{c=q.readFileSync(o,"utf-8")}catch{return null}let a={lines:c.split(`
256
+ `),bytes:Buffer.byteLength(c,"utf-8")};if(a.bytes<=yc){for(;n+a.bytes>yc&&e.size>0;){let l=e.keys().next().value;if(l===void 0)break;let u=e.get(l);e.delete(l),u&&(n-=u.bytes)}e.set(o,a),n+=a.bytes}return a.lines};return(i,o,r)=>{let c=s(i);if(!c)return"";let a=r-o+1,l=c.slice(o-1,r),u=!1;l.length>500&&(l=l.slice(0,500),u=!0);let f=l.map((m,d)=>`${o+d}: ${m}`).join(`
257
+ `);return u&&(f+=`
258
+ ... (truncated: showing lines ${o}-${o+l.length-1} of ${a} total \u2014 use \`query large_functions\` to confirm size, or read the file directly for the remainder)`),f}}var Op=5e3,Pc=50;function Dc(){return new Promise(t=>setTimeout(t,0))}function Ip(t){let e=Date.now(),n=Number.NEGATIVE_INFINITY,s,i=-1;return(o,r,c,a={})=>{if(!t)return;let l=a.phaseTotal&&a.phaseTotal>0?Math.floor(r/a.phaseTotal*100):void 0,u=l===void 0?-1:Math.floor(l/5),f=a.phaseTotal!==void 0&&r>=a.phaseTotal,m=Date.now();if(!(o===s&&u<=i&&!f&&m-n<Op)){try{t({phase:o,phaseCompleted:r,...a.phaseTotal===void 0?{}:{phaseTotal:a.phaseTotal},elapsedMs:m-e,message:c,...a.modelFile===void 0?{}:{modelFile:a.modelFile}})}catch{}o!==s?(s=o,i=u):i=Math.max(i,u),n=m}}}async function Go(t,e){try{let n=await Um(t.map(s=>s.text),!1,e);return t.map((s,i)=>({symbol:s.symbol,embedding:n[i]}))}catch(n){if(t.length===1){let r=t[0].symbol;return console.error(`Failed to generate embedding for symbol ${r.name} in ${r.filePath}:`,n),[]}let s=Math.ceil(t.length/2),i=await Go(t.slice(0,s),e),o=await Go(t.slice(s),e);return[...i,...o]}}async function fn(t,e,n){return Ue("embedding_inference_write",async()=>{try{let s=t.query(`
259
+ SELECT id, name, kind, filePath, startLine, endLine, summary
260
+ FROM symbols
261
+ WHERE id NOT IN (SELECT symbolId FROM symbol_embeddings)
262
+ `),i=s.all();if(s.finalize(),i.length===0){n?.("embedding-symbols",0,"Semantic embeddings already current",{phaseTotal:0});return}n?.("embedding-symbols",0,`Embedding ${i.length.toLocaleString()} symbols`,{phaseTotal:i.length}),n?.("embedding-model",0,"Preparing local embedding model");let o=0,r=f=>{if(o>0)return;let m=f.loaded??0,d=f.total,y=f.status==="download"?"Downloading local embedding model":f.status==="ready"?"Local embedding model ready":"Preparing local embedding model";n?.("embedding-model",m,y,{...d===void 0?{}:{phaseTotal:d},modelFile:f.file})},c=t.prepare(`
263
+ INSERT OR REPLACE INTO symbol_embeddings (symbolId, embedding)
264
+ VALUES (?, ?)
265
+ `),a=Np(),l=Cp(e),u=Date.now();for(let f=0;f<i.length;f+=a){let m=i.slice(f,f+a).map(y=>{let g=l(y.filePath,y.startLine,y.endLine);return{symbol:y,text:`Name: ${y.name}
266
+ Kind: ${y.kind}
267
+ Summary: ${y.summary||""}
268
+ Source:
269
+ ${g}`.slice(0,1e3)}}),d=await Go(m,r);t.run("BEGIN TRANSACTION;");try{for(let{symbol:y,embedding:g}of d){let h=new Uint8Array(g.buffer,g.byteOffset,g.byteLength);c.run(y.id,h)}t.run("COMMIT;")}catch(y){throw t.run("ROLLBACK;"),y}o=Math.min(f+m.length,i.length),n?.("embedding-symbols",o,`Embedding ${i.length.toLocaleString()} symbols`,{phaseTotal:i.length}),Date.now()-u>=Pc&&(await Dc(),u=Date.now())}c.finalize()}catch(s){console.error("Error during indexEmbeddings:",s)}})}function Et(t){return/\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)(tests?|__tests__)\//i.test(t)}function kt(t){let e=[],n=null;try{let s=st.execFileSync("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();s&&pn(s,t)&&(n=jc(st.execFileSync("git",["ls-files","-z","--cached","--others","--exclude-standard"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:64*1024*1024})).filter(i=>{try{return q.statSync(P.join(t,i)).isFile()}catch{return!1}}))}catch{n=null}for(let s of n??Pn(t,{accept:Ct})){if(!Ct(s))continue;let i=P.basename(s).toLowerCase();if(s.endsWith(".json")){if(Oc(s))e.push(s);else if(i==="manifest.json")try{Mc(q.readFileSync(P.join(t,s),"utf-8"))&&e.push(s)}catch{}}else e.push(s)}return e.sort()}function mn(t){try{return st.execSync("git rev-parse HEAD",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch{return null}}function Te(t,e){try{return t.query("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}catch{return null}}function Fe(t,e,n){try{t.run("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",[e,n])}catch{}}function Mp(t,e,n){if(!e||!n)return{commitRelation:"unknown",commitDistance:null};if(e===n)return{commitRelation:"equal",commitDistance:0};try{let s=st.execFileSync("git",["rev-list","--left-right","--count",`${e}...${n}`],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/).map(Number);if(s.length!==2||s.some(r=>!Number.isFinite(r)))return{commitRelation:"unknown",commitDistance:null};let[i,o]=s;return{commitRelation:i===0?"ahead":o===0?"behind":"diverged",commitDistance:i+o}}catch{return{commitRelation:"unknown",commitDistance:null}}}function Pp(t){return t===null?null:gn.createHash("sha256").update(t).digest("hex")}function Gs(t,e,n,s){let i=Jo(t),o=i&&pn(i.root,t)?i.head||null:mn(t),r=e&&Te(e,"lastIndexedHead")||null,c=Mp(t,r,o),a=e?Te(e,"lastProbeDirty"):null,l=i&&pn(i.root,t)?i.dirty.length:null,u=i!==null&&pn(i.root,t)&&a!==null&&a!==i.dirty.join(`
270
+ `),f=s??(o===null&&r===null&&a!==null?u?"stale-working-tree":"fresh":c.commitRelation==="unknown"?"unknown":c.commitRelation!=="equal"?"stale-head":u?"stale-working-tree":"fresh");return{currentHead:o,indexedHead:r,...c,workingTree:{indexedFingerprint:Pp(a),pendingPaths:l},state:f,verifiedAt:n,lastSuccessfulRefresh:e?Te(e,"lastSuccessfulReconciliation"):null}}function Yn(t,e,n){try{let s=q.statSync(P.join(e,n));t.run("INSERT INTO index_state(filePath, mtimeMs, size) VALUES (?, ?, ?) ON CONFLICT(filePath) DO UPDATE SET mtimeMs = excluded.mtimeMs, size = excluded.size",[n,s.mtimeMs,s.size])}catch{}}function mi(t,e){try{t.run("DELETE FROM index_state WHERE filePath = ?",[e])}catch{}}function jc(t){return t.split("\0").filter(e=>e.length>0)}function Dp(t){let e=t.split("\0"),n=[];for(let s=0;s<e.length;s++){let i=e[s];if(!i||i.length<3)continue;let o=i.slice(0,2),r=i.slice(3);if(r&&n.push(r),/[RC]/.test(o)){let c=e[++s];c&&n.push(c)}}return n}async function Zo(t,e,n){try{n?.("collecting-files",0,"Checking existing local graph for changes");let s=new Set,i=mn(t),o;if(i){let f=Te(e,"lastIndexedHead");try{let m=st.execFileSync("git",["status","--porcelain=v1","-z","--untracked-files=all"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});for(let d of Dp(m))s.add(d)}catch{}if(f&&f!==i)try{let m=st.execFileSync("git",["diff","--name-only","-z",f,i,"--"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});for(let d of jc(m))s.add(d)}catch{}}else{if(o=kt(t),o.length>5e4)return console.warn(`knodin: skipping freshness reconcile (${o.length} files exceeds 50k bound)`),0;let f=new Map;for(let m of e.query("SELECT filePath, mtimeMs, size FROM index_state").all())f.set(m.filePath,m);for(let m of o){let d=f.get(m);try{let y=q.statSync(P.join(t,m));(!d||Math.abs(d.mtimeMs-y.mtimeMs)>=1||d.size!==y.size)&&s.add(m)}catch{s.add(m)}}}o??=kt(t);let r=new Set(o),c=new Set;for(let f of e.query("SELECT filePath FROM index_state").all())c.add(f.filePath),r.has(f.filePath)||s.add(f.filePath);for(let f of r)c.has(f)||s.add(f);let a=[...s].filter(f=>Ct(f)||c.has(f)).sort();n?.("indexing-files",0,`Reconciling ${a.length.toLocaleString()} changed files`,{phaseTotal:a.length});let l=0,u=[];for(let[f,m]of a.entries()){let d=P.join(t,m);if(r.has(m)&&q.existsSync(d))pi(e,t,m)&&(await Jn(d,m,t,e),Yn(e,t,m),l++,u.push(m));else{e.run("BEGIN TRANSACTION;");try{ye(e,m),e.run('DELETE FROM "references" WHERE callerFile = ?',[m]),e.run("DELETE FROM dependencies WHERE fromFile = ?",[m]),e.run("DELETE FROM mcp_tools WHERE filePath = ?",[m]),mi(e,m),e.run("COMMIT;")}catch(y){e.run("ROLLBACK;"),console.error(`Error purging ineligible file from index: ${m}`,y)}l++,u.push(m)}n?.("indexing-files",f+1,`Reconciling ${a.length.toLocaleString()} changed files`,{phaseTotal:a.length})}return l>0&&(n?.("finalizing",0,"Refreshing identities and semantic embeddings"),zt(e,t,u),await fn(e,t,n),ne++),i&&Fe(e,"lastIndexedHead",i),Fe(e,"lastSuccessfulReconciliation",new Date().toISOString()),hn(t,e),l}catch(s){throw new Error("knodin: index reconciliation failed",{cause:s})}}var Vo=250,bc=6e4,jp=5e4;function zp(){let t=process.env.KNODIN_FRESHNESS_FILE_BOUND;if(t!==void 0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>=0)return e}return jp}var Dt=new Map,_o=new Map,Vs={probes:0,reconciles:0,cacheHits:0};function Bp(t){let e=P.join(t,".git");if(!q.existsSync(e))return null;try{let s=q.statSync(e).isDirectory()?e:P.resolve(t,q.readFileSync(e,"utf8").trim().replace(/^gitdir:\s*/,"")),i=q.readFileSync(P.join(s,"HEAD"),"utf8").trim();if(/^[a-f0-9]{40}$/i.test(i))return i.toLowerCase();let o="ref: ",r=i.startsWith(o)?i.slice(o.length).trim():"";if(!r)return;let c=s,a=P.join(s,"commondir");q.existsSync(a)&&(c=P.resolve(s,q.readFileSync(a,"utf8").trim()));for(let u of[s,c]){let f=P.join(u,r);if(q.existsSync(f))return q.readFileSync(f,"utf8").trim().toLowerCase()}let l=P.join(c,"packed-refs");return q.existsSync(l)?q.readFileSync(l,"utf8").split(`
271
+ `).find(u=>u.endsWith(` ${r}`))?.split(" ",1)[0]?.toLowerCase():void 0}catch{return}}function Jo(t){let e;try{e=st.execSync("git rev-parse HEAD --show-toplevel && git status --porcelain",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).split(`
272
+ `)}catch{return null}let n=e[0]?.trim(),s=e[1]?.trim();if(!n||!s)return null;let i=[];for(let o of e.slice(2))if(o.trim())for(let r of o.slice(3).split(" -> ")){let c=r.trim().replace(/^"|"$/g,"");c&&i.push(c)}return{head:n,root:s,dirty:i.sort()}}function pn(t,e){try{return q.realpathSync(t)===q.realpathSync(e)}catch{return P.resolve(t)===P.resolve(e)}}function pi(t,e,n){let s=t.query("SELECT filePath, mtimeMs, size FROM index_state WHERE filePath = ?").get(n),i=null;try{i=q.statSync(P.join(e,n))}catch{i=null}return s?i?Math.abs(s.mtimeMs-i.mtimeMs)>=1||s.size!==i.size:!0:i!==null}function hn(t,e){let n=Jo(t),s=n&&pn(n.root,t)?n.dirty:null;Fe(e,"lastProbeDirty",s===null?"":s.join(`
273
+ `))}function zc(t,e){let n=Jo(t);if(n&&pn(n.root,t)){if((Te(e,"lastIndexedHead")??"")!==n.head)return{drifted:!0,verifiable:!0};if(Te(e,"lastProbeDirty")!==n.dirty.join(`
274
+ `))return{drifted:!0,verifiable:!0};for(let i of n.dirty)if(Lt(i)&&pi(e,t,i))return{drifted:!0,verifiable:!0};return{drifted:!1,verifiable:!0}}let s=e.query("SELECT filePath, mtimeMs, size FROM index_state").all();if(s.length>zp())return{drifted:!1,verifiable:!1};for(let i of s)try{let o=q.statSync(P.join(t,i.filePath));if(i.mtimeMs!==o.mtimeMs||i.size!==o.size)return{drifted:!0,verifiable:!0}}catch{return{drifted:!0,verifiable:!0}}return{drifted:!1,verifiable:!0}}function jt(t,e){Dt.set(P.resolve(t),{at:Date.now(),staleness:e})}async function Hp(t,e){let n=P.resolve(t),s=Dt.get(n),o=q.existsSync(P.join(n,".git"))?0:ui.get(n)?.ready?bc:Vo,r=o===bc?Bp(n):null,c=r===null||r!==void 0&&r===Te(e,"lastIndexedHead");if(s&&Date.now()-s.at<o&&c)return Vs.cacheHits++,s.staleness;let a=_o.get(n);if(a)return Vs.cacheHits++,a;let l=(async()=>{Vs.probes++;let u;try{let{drifted:f,verifiable:m}=re("freshness_probe",()=>zc(t,e));m?f?(Vs.reconciles++,await Zo(t,e),u="reconciled"):u="fresh":u="unknown"}catch(f){console.error("Error during freshness probe:",f),u="unknown"}return jt(n,u),u})().finally(()=>{_o.delete(n)});return _o.set(n,l),l}function Ot(t){return Dt.get(P.resolve(t))?.staleness??"unknown"}async function Bc(t,e,n){n?.("collecting-files",0,"Discovering indexable files");let s=re("file_collection",()=>kt(t));n?.("indexing-files",0,`Indexing ${s.length.toLocaleString()} files`,{phaseTotal:s.length}),oc(e),e.run('DELETE FROM "references";'),e.run("DELETE FROM dependencies;"),e.run("DELETE FROM mcp_tools;"),e.run("DELETE FROM index_state;");let i=Date.now();for(let o=0;o<s.length;o++){let r=s[o];await Jn(P.join(t,r),r,t,e),Yn(e,t,r),n?.("indexing-files",o+1,`Indexing ${s.length.toLocaleString()} files`,{phaseTotal:s.length}),Date.now()-i>=Pc&&(await Dc(),i=Date.now())}n?.("finalizing",0,"Persisting symbol identities and semantic index"),zt(e,t),await fn(e,t,n),Fe(e,"lastIndexedHead",mn(t)??""),Fe(e,"lastSuccessfulReconciliation",new Date().toISOString()),Fe(e,"mcpBackfillVersion","17"),hn(t,e),ne++}function Up(t,e){let n=P.resolve(t);if(li.has(n))return;let s={pending:new Set,timer:null,flushPromise:null,closed:!1,flushes:0,errors:0,drain:async()=>{},failNextFlush:!1,nextFlushGateForTests:null,ready:!1,embeddingReconciliations:0,generationAdvances:0};ui.set(n,s);let i=a=>{e.run("BEGIN TRANSACTION;");try{ye(e,a),e.run('DELETE FROM "references" WHERE callerFile = ?',[a]),e.run("DELETE FROM dependencies WHERE fromFile = ?",[a]),e.run("COMMIT;"),mi(e,a)}catch(l){throw e.run("ROLLBACK;"),l}},o=async()=>(s.flushPromise||(s.flushPromise=(async()=>{do{let a=[...s.pending].sort();if(s.pending.clear(),a.length===0)break;try{let l=s.nextFlushGateForTests;if(s.nextFlushGateForTests=null,l&&await l,s.failNextFlush)throw s.failNextFlush=!1,new Error("injected watcher flush failure");for(let u of a){let f=P.join(n,u);q.existsSync(f)?(await Jn(f,u,n,e),Yn(e,n,u)):i(u)}zt(e,n,a),await fn(e,n),s.embeddingReconciliations++,ne++,s.generationAdvances++,hn(n,e),jt(n,"fresh"),s.flushes++}catch(l){s.errors++,console.error(`Error flushing watcher updates for ${n}:`,l);for(let u of a)s.pending.add(u);s.closed||(s.timer=setTimeout(()=>{s.timer=null,o()},rc));break}}while(s.pending.size>0)})().finally(()=>{s.flushPromise=null})),s.flushPromise),r=a=>{if(s.closed)return;let l=P.relative(n,a);Ct(l)&&(Dt.delete(n),s.pending.add(l),s.timer&&clearTimeout(s.timer),s.timer=setTimeout(()=>{s.timer=null,o()},rc))};s.drain=o;let c=bm.watch(t,{ignored:Va(t),persistent:!0,ignoreInitial:!0});c.on("add",r),c.on("change",r),c.on("unlink",r),c.on("ready",()=>{s.ready=!0}),c.on("error",a=>console.error(`File watcher error for ${n}:`,a)),li.set(n,c)}async function Ge(t,e={}){let n=P.resolve(t),s=No.get(n);s||(s=(async()=>{let o=process.env.VITEST||process.env.NODE_ENV==="test",r;if(o)r=":memory:";else{let h=P.join(n,".knodin");await q.promises.mkdir(h,{recursive:!0});try{let w=P.join(n,".gitignore"),k="";q.existsSync(w)&&(k=await q.promises.readFile(w,"utf-8"));let _=k.split(`
275
+ `).map(R=>R.trim());if(!_.includes(".knodin")&&!_.includes(".knodin/")&&!_.includes("/.knodin")){let R=k.length>0&&!k.endsWith(`
276
+ `)?`
277
+ `:"";await q.promises.appendFile(w,`${R}
278
+ # knodin
279
+ .knodin
280
+ `)}}catch(w){console.error("Failed to update .gitignore",w)}r=P.join(h,"db.sqlite")}let c=Vt("db_open_migration"),a=new an(r);a.run("PRAGMA busy_timeout = 30000;"),a.run("PRAGMA journal_mode = WAL;"),a.run("PRAGMA foreign_keys = ON;");let l=21,u=21,m=a.query("PRAGMA user_version").get()?.user_version??0,d=m<17,y=m<l;m<u&&(a.run("DROP TRIGGER IF EXISTS after_symbol_insert;"),a.run("DROP TRIGGER IF EXISTS after_symbol_delete;"),a.run("DROP TRIGGER IF EXISTS after_symbol_update;"),a.run("DROP TABLE IF EXISTS symbols_fts;"),a.run("DROP TABLE IF EXISTS symbol_embeddings;"),a.run('DROP TABLE IF EXISTS "references";'),a.run("DROP TABLE IF EXISTS dependencies;"),a.run("DROP TABLE IF EXISTS symbols;"),a.run("DROP TABLE IF EXISTS index_state;"),a.run("DROP TABLE IF EXISTS meta;"),a.run("DROP TABLE IF EXISTS mcp_tools;"),a.run("DROP TABLE IF EXISTS api_contracts;")),m<l&&a.run(`PRAGMA user_version = ${l};`),a.run(`
281
+ CREATE TABLE IF NOT EXISTS symbols (
282
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
283
+ identity TEXT,
284
+ name TEXT NOT NULL,
285
+ kind TEXT NOT NULL,
286
+ filePath TEXT NOT NULL,
287
+ startLine INTEGER NOT NULL,
288
+ endLine INTEGER NOT NULL,
289
+ startCol INTEGER NOT NULL,
290
+ endCol INTEGER NOT NULL,
291
+ summary TEXT
292
+ )
293
+ `);try{a.run("ALTER TABLE symbols ADD COLUMN identity TEXT;")}catch{}a.run("CREATE INDEX IF NOT EXISTS idx_symbols_identity ON symbols(identity);"),a.run(`
294
+ CREATE TABLE IF NOT EXISTS "references" (
295
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
296
+ callerSymbol TEXT,
297
+ callerFile TEXT NOT NULL,
298
+ calleeSymbol TEXT NOT NULL,
299
+ calleeFile TEXT,
300
+ callerIdentity TEXT,
301
+ calleeIdentity TEXT,
302
+ line INTEGER NOT NULL,
303
+ column INTEGER NOT NULL,
304
+ kind TEXT NOT NULL DEFAULT 'call',
305
+ confidence REAL NOT NULL DEFAULT 1.0
306
+ )
307
+ `),a.run(`
308
+ CREATE TABLE IF NOT EXISTS api_contracts (
309
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
310
+ kind TEXT NOT NULL,
311
+ framework TEXT NOT NULL,
312
+ method TEXT NOT NULL,
313
+ path TEXT NOT NULL,
314
+ origin TEXT,
315
+ handler TEXT,
316
+ middleware TEXT NOT NULL,
317
+ responseFields TEXT NOT NULL,
318
+ responseKnown INTEGER NOT NULL DEFAULT 0,
319
+ declaredResponseFields TEXT NOT NULL,
320
+ accessedFields TEXT NOT NULL,
321
+ unresolved INTEGER NOT NULL DEFAULT 0,
322
+ filePath TEXT NOT NULL,
323
+ line INTEGER NOT NULL,
324
+ confidence REAL NOT NULL,
325
+ evidence TEXT NOT NULL
326
+ )
327
+ `),a.run("CREATE INDEX IF NOT EXISTS idx_api_contracts_lookup ON api_contracts(kind, method, path);");try{a.run('ALTER TABLE "references" ADD COLUMN confidence REAL NOT NULL DEFAULT 1.0;')}catch{}try{a.run('ALTER TABLE "references" ADD COLUMN callerIdentity TEXT;')}catch{}try{a.run('ALTER TABLE "references" ADD COLUMN calleeIdentity TEXT;')}catch{}a.run(`
328
+ CREATE TABLE IF NOT EXISTS dependencies (
329
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
330
+ fromFile TEXT NOT NULL,
331
+ toFile TEXT NOT NULL,
332
+ kind TEXT NOT NULL,
333
+ confidence REAL DEFAULT 1.0,
334
+ sourceEvidence TEXT
335
+ )
336
+ `),a.run(`
337
+ CREATE TABLE IF NOT EXISTS symbol_embeddings (
338
+ symbolId INTEGER PRIMARY KEY,
339
+ embedding BLOB NOT NULL,
340
+ FOREIGN KEY(symbolId) REFERENCES symbols(id) ON DELETE CASCADE
341
+ )
342
+ `),a.run(`
343
+ CREATE TABLE IF NOT EXISTS index_state (
344
+ filePath TEXT PRIMARY KEY,
345
+ mtimeMs REAL,
346
+ size INTEGER
347
+ )
348
+ `),a.run(`
349
+ CREATE TABLE IF NOT EXISTS meta (
350
+ key TEXT PRIMARY KEY,
351
+ value TEXT
352
+ )
353
+ `),a.run(`
354
+ CREATE TABLE IF NOT EXISTS mcp_tools (
355
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
356
+ name TEXT NOT NULL,
357
+ description TEXT,
358
+ schemaSymbol TEXT,
359
+ handlerSymbol TEXT,
360
+ filePath TEXT NOT NULL,
361
+ line INTEGER NOT NULL,
362
+ confidence TEXT NOT NULL CHECK(confidence IN ('exact', 'heuristic'))
363
+ , associationKey TEXT
364
+ )
365
+ `);try{a.run("ALTER TABLE mcp_tools ADD COLUMN associationKey TEXT;")}catch{}a.run(`
366
+ CREATE VIRTUAL TABLE IF NOT EXISTS symbols_fts USING fts5(
367
+ symbolId UNINDEXED,
368
+ name,
369
+ kind,
370
+ summary
371
+ )
372
+ `),a.run(`
373
+ CREATE TRIGGER IF NOT EXISTS after_symbol_insert
374
+ AFTER INSERT ON symbols
375
+ BEGIN
376
+ INSERT INTO symbols_fts(symbolId, name, kind, summary)
377
+ VALUES (new.id, new.name, new.kind, COALESCE(new.summary, ''));
378
+ END;
379
+ `),a.run(`
380
+ CREATE TRIGGER IF NOT EXISTS after_symbol_delete
381
+ AFTER DELETE ON symbols
382
+ BEGIN
383
+ DELETE FROM symbols_fts WHERE symbolId = old.id;
384
+ END;
385
+ `),a.run(`
386
+ CREATE TRIGGER IF NOT EXISTS after_symbol_update
387
+ AFTER UPDATE ON symbols
388
+ BEGIN
389
+ UPDATE symbols_fts
390
+ SET name = new.name,
391
+ kind = new.kind,
392
+ summary = COALESCE(new.summary, '')
393
+ WHERE symbolId = old.id;
394
+ END;
395
+ `);try{a.run("ALTER TABLE dependencies ADD COLUMN confidence REAL DEFAULT 1.0;")}catch{}try{a.run("ALTER TABLE dependencies ADD COLUMN sourceEvidence TEXT;")}catch{}a.run("CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);"),a.run("CREATE INDEX IF NOT EXISTS idx_symbols_file ON symbols(filePath);"),a.run('CREATE INDEX IF NOT EXISTS idx_references_callee ON "references"(calleeSymbol);'),a.run('CREATE INDEX IF NOT EXISTS idx_references_callee_file ON "references"(calleeSymbol, calleeFile);'),a.run('CREATE INDEX IF NOT EXISTS idx_references_callee_file_only ON "references"(calleeFile);'),a.run('CREATE INDEX IF NOT EXISTS idx_references_caller_file ON "references"(callerFile);'),a.run("CREATE INDEX IF NOT EXISTS idx_dependencies_from ON dependencies(fromFile);"),a.run("CREATE INDEX IF NOT EXISTS idx_dependencies_to ON dependencies(toFile);"),a.run("CREATE INDEX IF NOT EXISTS idx_mcp_tools_name ON mcp_tools(name);"),a.run("CREATE INDEX IF NOT EXISTS idx_mcp_tools_file ON mcp_tools(filePath);"),y&&sc(a),c();let g=!0;try{let h=a.query("SELECT COUNT(*) as count FROM symbols").all();h&&h.length>0&&h[0].count>0&&(g=!1)}catch{g=!0}if(g&&!e.skipContentReconciliation)await Bc(n,a,e.onProgress),jt(n,"fresh");else if(!g&&!e.skipContentReconciliation){let h=await Zo(n,a,e.onProgress),w=a.query("SELECT COUNT(*) count FROM symbols WHERE identity IS NULL OR identity = ''").get()?.count??0;if(w>0&&(e.onProgress?.("finalizing",0,`Persisting stable identities for ${w.toLocaleString()} missing symbols`),zt(a,n)),d||Te(a,"mcpBackfillVersion")!=="17"){let k=!0,_=a.query("SELECT filePath FROM index_state").all();for(let{filePath:R}of _)try{if(!/\.[cm]?[jt]sx?$/.test(R))continue;let v=P.join(n,R);if(!q.existsSync(v))continue;let S=q.readFileSync(v,"utf8");if(!/@modelcontextprotocol\/sdk/.test(S))continue;let E=await Kn(v);if(!E)continue;let $=new we;$.setLanguage(E);let p;try{p=$.parse(S)}catch{k=!1;continue}if(!p)continue;a.run("DELETE FROM mcp_tools WHERE filePath = ?",[R]);for(let F of Rc(S,R,p.rootNode))a.run("INSERT INTO mcp_tools(name, description, schemaSymbol, handlerSymbol, filePath, line, confidence, associationKey) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[F.name,F.description??null,F.schemaSymbol??null,F.handlerSymbol??null,R,F.line,F.confidence,F.associationKey??null])}catch{k=!1}k&&Fe(a,"mcpBackfillVersion","17")}jt(n,h>0?"reconciled":"fresh")}return o||Up(n,a),Mt.set(n,a),a})(),No.set(n,s));let i=await s;return e.skipFreshnessGuard||await Hp(n,i),i}async function It(t){let e=P.resolve(t),n=[e],s=process.env.KNODIN_AUTO_FEDERATE==="1"||process.env.KNODIN_AUTO_FEDERATE==="true",i=P.join(e,".knodin/federation.json");if(q.existsSync(i))try{let r=JSON.parse(q.readFileSync(i,"utf-8"));if(r&&Array.isArray(r.repos))for(let c of r.repos){let a=P.resolve(e,c);q.existsSync(a)&&!n.includes(a)&&n.push(a)}r?.autoDiscover===!0&&(s=!0)}catch(r){console.error(`Error parsing federation config at ${i}:`,r)}if(!s)return n;let o=process.env.VITEST||process.env.NODE_ENV==="test";try{let r=P.dirname(e),c=await q.promises.readdir(r,{withFileTypes:!0});for(let a of c)if(a.isDirectory()&&!a.name.startsWith(".")&&a.name!=="node_modules"){let l=P.join(r,a.name);if(l===e)continue;(Mt.has(P.resolve(l))||!o&&q.existsSync(P.join(l,".knodin","db.sqlite")))&&n.push(l)}}catch(r){console.error("Error during auto-discovery of sibling repos:",r)}return n}function hi(t,e){if(t===e)return!0;let n=t.split("/"),s=e.split("/");return n.length!==s.length?!1:s.every((i,o)=>/^:\w+$/.test(i)||/^\{\w+\}$/.test(i)?n[o].length>0:n[o].toLocaleLowerCase("en-US")===i.toLocaleLowerCase("en-US"))}function Gn(t,e,n,s,i){let o=P.resolve(t,e);if(!q.existsSync(o))return"";let c=q.readFileSync(o,"utf-8").split(`
396
+ `),a=s-n+1,l=c.slice(n-1,s),u=!1;i!==void 0&&l.length>i&&(l=l.slice(0,i),u=!0);let f=l.map((m,d)=>`${n+d}: ${m}`).join(`
397
+ `);return u&&(f+=`
398
+ ... (truncated: showing lines ${n}-${n+l.length-1} of ${a} total \u2014 use \`query large_functions\` to confirm size, or read the file directly for the remainder)`),f}function ai(t,e,n){let s=t.query("SELECT id, identity, name, kind, filePath, startLine, endLine, startCol, endCol, summary FROM symbols WHERE filePath = ? ORDER BY startLine, endLine DESC"),i=s.all(e);return s.finalize(),i.map(o=>{let r=n?Gn(n,e,o.startLine,Math.min(o.endLine,o.startLine+8)).split(/\r?\n/).map(u=>u.trim().replace(/^\d+:\s*/,"")).join(" ").replace(/\s+/g," ").split(/\s*(?:\{|=>)\s*/,1)[0].slice(0,500):"",c=r.match(/\b(public|private|protected|internal)\b/)?.[1]??(o.filePath.endsWith(".py")&&o.name.startsWith("_")?"private":"default"),a=i.filter(u=>u.id!==o.id&&u.startLine<=o.startLine&&u.endLine>=o.endLine).sort((u,f)=>u.endLine-u.startLine-(f.endLine-f.startLine))[0],l=new Set([".ts",".mts",".cts",".tsx",".js",".jsx",".mjs",".cjs",".py",".cls",".trigger",".java",".cs",".go",".rs",".xml",".sql",".prisma"]).has(P.extname(e).toLowerCase());return{identity:o.identity??void 0,symbol:o.name,kind:o.kind,file:e,line:o.startLine,endLine:o.endLine,signature:r,visibility:c,exported:/\bexport\b/.test(r)||c==="public",parent:a?{identity:a.identity??null,symbol:a.name,kind:a.kind}:null,evidenceQuality:n&&l?"parser-grounded":"source-derived"}})}function Wp(t,e){let n=e.query("SELECT filePath FROM index_state ORDER BY filePath").all(),s=[];for(let{filePath:i}of n){let o=P.resolve(t,i);try{let r=q.readFileSync(o),c=q.statSync(o);s.push({path:i,sizeBytes:r.byteLength,mtimeMs:c.mtimeMs,contentFingerprint:Tr(r),symbols:ai(e,i,t).map(a=>({identity:a.identity??null,symbol:a.symbol??"",kind:a.kind??"unknown",line:a.line??1,endLine:a.endLine??a.line??1,...a.signature?{signature:a.signature}:{},...a.visibility?{visibility:a.visibility}:{},...a.exported!==void 0?{exported:a.exported}:{},...a.parent?{parent:a.parent}:{},evidenceQuality:a.evidenceQuality??"parser-grounded"}))})}catch{}}Rr(t,s)}function qp(t,e=!1){let n=t.query('SELECT DISTINCT callerSymbol, calleeSymbol FROM "references" WHERE callerSymbol IS NOT NULL').all(),s=new Map,i=(o,r)=>{let c=s.get(o);c||(c=[],s.set(o,c)),c.push(r)};for(let o of n)i(o.callerSymbol,o.calleeSymbol),e&&i(o.calleeSymbol,o.callerSymbol);return s}var yn=new Set(["Math","JSON","Object","Array","String","Number","Boolean","Symbol","BigInt","Promise","Set","Map","WeakMap","WeakSet","Date","RegExp","Error","Proxy","Reflect","console","globalThis","process","parseInt","parseFloat","isNaN","isFinite","encodeURIComponent","decodeURIComponent","structuredClone","require","fetch","setTimeout","setInterval","clearTimeout","clearInterval","min","max","abs","floor","ceil","round","trunc","sqrt","pow","random","sign","hypot","map","filter","reduce","forEach","find","findIndex","some","every","push","pop","shift","unshift","slice","splice","concat","join","reverse","sort","flat","flatMap","includes","indexOf","lastIndexOf","fill","keys","values","entries","from","of","isArray","split","trim","trimStart","trimEnd","replace","replaceAll","toLowerCase","toUpperCase","substring","substr","startsWith","endsWith","padStart","padEnd","charAt","charCodeAt","codePointAt","repeat","match","matchAll","normalize","assign","freeze","create","defineProperty","getOwnPropertyNames","fromEntries","hasOwnProperty","has","get","set","add","delete","clear","resolve","reject","all","allSettled","race","then","catch","finally","stringify","parse","now","toString","valueOf","toFixed","toJSON","log","error","warn","info","debug","trace","describe","it","test","expect","suite","bench","beforeAll","afterAll","beforeEach","afterEach","vi","jest","fn","spyOn","mock","mocked","mockResolvedValue","mockRejectedValue","mockReturnValue","mockImplementation","toBe","toEqual","toStrictEqual","toContain","toContainEqual","toMatch","toMatchObject","toMatchSnapshot","toThrow","toThrowError","toHaveLength","toHaveProperty","toHaveBeenCalled","toHaveBeenCalledWith","toHaveBeenCalledTimes","toBeDefined","toBeUndefined","toBeNull","toBeTruthy","toBeFalsy","toBeNaN","toBeGreaterThan","toBeGreaterThanOrEqual","toBeLessThan","toBeLessThanOrEqual","toBeCloseTo","toBeInstanceOf","resolves","rejects"]);function Vn(t,e,n,s,i=new Set,o=null,r=null){if(s<=0)return[];let c=`${e}:${n}:${o??""}`;if(i.has(c))return[];i.add(c);let a=[],l=t.find(d=>d.path===e);if(!l)return[];let u=l.db,f;if(o){let d=u.query(`
399
+ SELECT *
400
+ FROM "references"
401
+ WHERE calleeSymbol = ? AND calleeFile = ?
402
+ AND (? IS NULL OR calleeIdentity = ?) AND kind = 'call'
403
+ `);f=d.all(n,o,r,r),d.finalize()}else{let d=u.query(`
404
+ SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, line, column, kind
405
+ FROM "references"
406
+ WHERE calleeSymbol = ? AND kind = 'call'
407
+ `);f=d.all(n),d.finalize()}for(let d of f){if(!d.callerSymbol)continue;a.push({symbol:d.callerSymbol,filePath:d.callerFile,lineNumber:d.line,repoPath:e,kind:d.kind});let y=Vn(t,e,d.callerSymbol,s-1,i,d.callerFile,d.callerIdentity??null);a.push(...y)}if(n.startsWith("/"))for(let d of t){if(d.path===e)continue;let y=d.db.query(`
408
+ SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, line, column
409
+ FROM "references"
410
+ `).all();for(let g of y)if(hi(g.calleeSymbol,n)){if(!g.callerSymbol)continue;a.push({symbol:g.callerSymbol,filePath:g.callerFile,lineNumber:g.line,repoPath:d.path});let h=Vn(t,d.path,g.callerSymbol,s-1,i,g.callerFile);a.push(...h)}}let m=new Set;return a.filter(d=>{let y=`${d.symbol}:${d.filePath}:${d.lineNumber}:${d.repoPath}`;return m.has(y)?!1:(m.add(y),!0)})}function gi(t,e,n,s,i=new Set,o=null,r=null){if(s<=0)return[];let c=`${e}:${n}:${o??""}`;if(i.has(c))return[];i.add(c);let a=[],l=t.find(d=>d.path===e);if(!l)return[];let u=l.db,f;if(o){let y=(u.query("SELECT COUNT(*) AS count FROM symbols WHERE name = ? AND filePath = ?").get(n,o)?.count??0)>1?r:null,g=u.query(`
411
+ SELECT *
412
+ FROM "references"
413
+ WHERE callerSymbol = ? AND callerFile = ?
414
+ AND (? IS NULL OR callerIdentity = ?) AND kind = 'call'
415
+ `);f=g.all(n,o,y,y),g.finalize()}else{let d=u.query(`
416
+ SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, line, column, kind
417
+ FROM "references"
418
+ WHERE callerSymbol = ? AND kind = 'call'
419
+ `);f=d.all(n),d.finalize()}for(let d of f){if(!d.calleeFile&&yn.has(d.calleeSymbol))continue;let y=null;if(d.calleeFile){let g=u.query("SELECT * FROM symbols WHERE name = ? AND filePath = ? AND (? IS NULL OR identity = ?)");y=g.get(d.calleeSymbol,d.calleeFile,d.calleeIdentity??null,d.calleeIdentity??null),g.finalize()}if(y){a.push({symbol:d.calleeSymbol,filePath:y.filePath,lineNumber:y.startLine,repoPath:e,kind:d.kind});let g=gi(t,e,d.calleeSymbol,s-1,i,y.filePath,y.identity??null);a.push(...g)}else if(d.calleeSymbol.startsWith("/")){if(yn.has(d.calleeSymbol))continue;let g=!1;for(let h of t){if(h.path===e)continue;let w=h.db.query(`
420
+ SELECT filePath, startLine, name FROM symbols
421
+ WHERE kind = 'endpoint'
422
+ `),k=w.all();w.finalize();for(let _ of k)if(hi(d.calleeSymbol,_.name)){g=!0,a.push({symbol:_.name,filePath:_.filePath,lineNumber:_.startLine,repoPath:h.path});let R=gi(t,h.path,_.name,s-1,i);a.push(...R)}}}}let m=new Set;return a.filter(d=>{let y=`${d.symbol}:${d.filePath}:${d.lineNumber}:${d.repoPath}`;return m.has(y)?!1:(m.add(y),!0)})}function Gp(t){let e=new Map;{let n=t.split(`
423
+ `),s=null;for(let i of n)if(i.startsWith("+++ b/"))s=i.slice(6).trim(),s.startsWith('"')&&s.endsWith('"')&&(s=s.slice(1,-1));else if(i.startsWith("+++ ")&&i.endsWith("/dev/null"))s=null;else if(i.startsWith("@@")&&s){let o=i.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);if(o){let r=parseInt(o[1],10),c=o[2]!==void 0?parseInt(o[2],10):1;if(c>0){let a=e.get(s);a||(a=new Set,e.set(s,a));for(let l=0;l<c;l++)a.add(r+l)}}}}return e}function Ko(t,e){return st.execFileSync("git",e,{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","ignore"]})}function Vp(t){let e=t.replaceAll("\\","/").replace(/^\.\//,"");if(!e||P.isAbsolute(e)||e===".."||e.startsWith("../"))throw new Error(`review file must be repo-relative: ${t}`);return e}function Tt(t){if(!t||t.startsWith("-"))throw new Error(`invalid review revision: ${t}`);return t}function Kp(t,e,n={}){if(n.scope&&!["unstaged","staged","all","compare"].includes(n.scope))throw new Error(`invalid review scope: ${String(n.scope)}`);if(n.files?.length)return new Map(n.files.map(o=>[Vp(o),new Set([Number.MAX_SAFE_INTEGER])]));if(n.from===void 0!=(n.to===void 0))throw new Error("review revisions require both `from` and `to`");let s=n.scope??"all",i=["diff","--unified=0"];n.from&&n.to?i.push(Tt(n.from),Tt(n.to)):s==="staged"?i.push("--cached"):s==="unstaged"||(s==="compare"?i.push(Tt(t||"HEAD~1"),"HEAD"):i.push(Tt(t||"HEAD"))),i.push("--");try{return Gp(Ko(e,i))}catch(o){return console.error("Error executing or parsing git diff:",o),new Map}}function Xp(t,e,n,s){let i=new Set(s.keys());if(n.files?.length)return[...i].sort();let o=n.scope??"all";try{let r=["diff","--name-only","-z"];n.from&&n.to?r.push(Tt(n.from),Tt(n.to)):o==="staged"?r.push("--cached"):o==="compare"?r.push(Tt(t||"HEAD~1"),"HEAD"):o==="all"&&r.push(Tt(t||"HEAD")),r.push("--");for(let c of Ko(e,r).split("\0"))c&&i.add(c)}catch{}if(!n.from&&(o==="unstaged"||o==="all"))try{for(let r of Ko(e,["ls-files","--others","--exclude-standard","-z"]).split("\0"))r&&i.add(r)}catch{}return[...i].sort()}function Hc(t){let e=P.dirname(t),n=P.extname(t),s=P.basename(t,n),i=[".ts",".tsx",".js",".jsx",".py",".cls"],o=[(c,a)=>`${c}.test${a}`,(c,a)=>`${c}.spec${a}`,(c,a)=>`${c}Test${a}`,(c,a)=>`${c}_Test${a}`,(c,a)=>`__tests__/${c}.test${a}`,(c,a)=>`__tests__/${c}.spec${a}`],r=[];for(let c of o)for(let a of i)r.push(P.join(e,c(s,a)));return[...new Set(r)]}function Zp(t,e,n,s=!1){let i=null;function o(r){if(i)return;let c=!1;if(n){if(r.type==="function_definition"||r.type==="class_definition"){let a=r.childForFieldName("name");a&&a.text===e&&(c=!0)}}else if(s){if(r.type==="class_declaration"||r.type==="method_declaration"||r.type==="trigger_declaration"){let a=r.childForFieldName("name")||r.children.find(l=>l.type==="identifier");a&&a.text===e&&(c=!0)}}else if(r.type==="function_declaration"||r.type==="generator_function_declaration"||r.type==="class_declaration"||r.type==="method_definition"||r.type==="interface_declaration"||r.type==="type_alias_declaration"){let a=r.childForFieldName("name");a&&a.text===e&&(c=!0)}else if(r.type==="variable_declarator"){let a=r.childForFieldName("name");a&&a.type==="identifier"&&a.text===e&&(c=!0)}if(c){i=r;return}for(let a=0;a<r.childCount;a++){let l=r.child(a);l&&o(l)}}return o(t),i}function Jp(t){let e=1;function n(s){let i=s.type,o=s.text;(i==="if_statement"||i==="if_clause"||i==="elif_clause"||i==="switch_statement"||i==="switch_case"||i==="case_clause"||i==="ternary_expression"||i==="conditional_expression"||i==="for_statement"||i==="while_statement"||i==="do_statement"||i==="for_in_statement"||i==="for_of_statement"||i==="with_statement"||i==="try_statement"||i==="catch_clause")&&(e+=1),(o==="&&"||o==="||"||o==="and"||o==="or"||i==="&&"||i==="||")&&(e+=.5);for(let r=0;r<s.childCount;r++){let c=s.child(r);c&&n(c)}}return n(t),e}function Ao(t){let e=new Map,n=new Map;for(let c of t){let l=P.dirname(c).split(/[\\/]/).filter(d=>d&&d!=="."&&d!=="src"&&d!=="app"&&d!=="lib"&&d!=="__tests__"&&d!=="unit");for(let d of l)e.set(d,(e.get(d)||0)+1);let u=P.extname(c),m=P.basename(c,u).replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(d=>d.length>2&&d!=="test"&&d!=="spec"&&d!=="index"&&d!=="module"&&d!=="helper"&&d!=="helpers");for(let d of m)n.set(d,(n.get(d)||0)+1)}let s="",i=0;for(let[c,a]of e.entries())a>i&&(i=a,s=c);let o="",r=0;for(let[c,a]of n.entries())a>r&&(r=a,o=c);return i>=t.length*.3&&s?s:o||s||null}function Yp(t,e){if(t.length===0)return"empty-community";let n=t.filter(r=>r.includes("test")||r.includes("spec")||r.includes("__tests__")).length,s="";if(n/t.length>.5){let r=t.filter(c=>!c.includes("test")&&!c.includes("spec")&&!c.includes("__tests__"));if(r.length>0){let c=Ao(r);s=c?`${c}-tests`:"test-suite"}else{let c=Ao(t);s=c?`${c}-tests`:"test-suite"}}else s=Ao(t)||"core";!s.endsWith("-tests")&&!s.endsWith("-suite")&&!s.endsWith("-module")&&!s.endsWith("-helpers")&&!s.endsWith("-subsystem")&&(s=`${s}-module`);let i=s,o=1;for(;e.has(i);)i=`${s}-${o}`,o++;return e.add(i),i}function Uc(t,e,n){let s=new Map,i=(r,c,a)=>{if(yn.has(r))return;let l=`${c}::${r}`,u=s.get(l);u?(u.degree+=a,u.inDegree+=a):s.set(l,{name:r,file:c,degree:a,inDegree:a,outDegree:0})},o=(r,c,a)=>{if(yn.has(r))return;let l=`${c}::${r}`,u=s.get(l);u?(u.degree+=a,u.outDegree+=a):s.set(l,{name:r,file:c,degree:a,inDegree:0,outDegree:a})};for(let r of t){if(n?.length){let l=r.db.query('SELECT callerSymbol, callerFile, calleeSymbol, calleeFile, kind FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all().filter(u=>n.includes(u.kind));for(let u of l)i(u.calleeSymbol,e(r.path,u.calleeFile),1),o(u.callerSymbol,e(r.path,u.callerFile),1);continue}let c=r.db.query('SELECT calleeSymbol AS name, calleeFile AS file, COUNT(*) AS c FROM "references" WHERE calleeFile IS NOT NULL GROUP BY calleeSymbol, calleeFile').all();for(let l of c)i(l.name,e(r.path,l.file),l.c);let a=r.db.query('SELECT callerSymbol AS name, callerFile AS file, COUNT(*) AS c FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL GROUP BY callerSymbol, callerFile').all();for(let l of a)o(l.name,e(r.path,l.file),l.c)}return s}function Wc(t,e,n=15,s){let i=Uc(t,e,s);return Array.from(i.values()).sort((o,r)=>r.degree-o.degree).slice(0,n).map(o=>({symbol:o.name,filePath:o.file,degree:o.degree,inDegree:o.inDegree,outDegree:o.outDegree}))}function Qp(t,e){let n=new Int32Array(t);for(let l=0;l<t;l++)n[l]=l;let s=new Float64Array(t),i=0;for(let l=0;l<t;l++){let u=0,f=e.get(l);if(f)for(let m of f.values())u+=m;s[l]=u,i+=u}let o=i/2;if(o<=0)return n;let r=new Float64Array(t);for(let l=0;l<t;l++)r[l]=s[l];let c=!0,a=0;for(;c&&a<100;){c=!1,a++;for(let l=0;l<t;l++){let u=s[l];if(u===0)continue;let f=e.get(l);if(!f)continue;let m=new Map;for(let[k,_]of f){let R=n[k];m.set(R,(m.get(R)??0)+_)}let d=n[l],y=m.get(d)??0;r[d]-=u;let g=r[d]+u,h=d,w=0;for(let[k,_]of m){let R=r[k],v=(_-y)/o+(g-R-u)*u/(2*o*o);v>w+1e-7&&(w=v,h=k)}h===d?r[d]+=u:(r[h]+=u,n[l]=h,c=!0)}}return n}function qc(t,e,n,s){let o=new Map,r=[],c=(v,S)=>`${v} ${S}`,a=(v,S)=>{let E=c(v,S),$=o.get(E);return $===void 0&&($=r.length,o.set(E,$),r.push({name:S,file:v})),$},l=[],u=v=>{for(;l.length<=v;)l.push([])};for(let v of t){let S=v.db.query('SELECT callerSymbol, callerFile, calleeSymbol, calleeFile, kind FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all().filter(E=>!s?.length||s.includes(E.kind));for(let E of S){let $=a(e(v.path,E.callerFile),E.callerSymbol),p=a(e(v.path,E.calleeFile),E.calleeSymbol);$!==p&&(u($),u(p),l[$].push(p))}}let f=r.length;if(f===0)return[];for(;l.length<f;)l.push([]);let m=2e3,d=[];if(f<=m)for(let v=0;v<f;v++)d.push(v);else{let v=Math.max(1,Math.floor(f/1e3));for(let S=0;S<f;S+=v)d.push(S)}let y=new Float64Array(f),g=new Int32Array(f).fill(-1),h=new Float64Array(f),w=new Float64Array(f),k=Array.from({length:f},()=>[]);for(let v of d){let S=[],E=[v],$=0;for(g[v]=0,h[v]=1;$<E.length;){let p=E[$++];S.push(p);for(let F of l[p])g[F]<0&&(g[F]=g[p]+1,E.push(F)),g[F]===g[p]+1&&(h[F]+=h[p],k[F].push(p))}for(let p=S.length-1;p>=0;p--){let F=S[p];for(let L of k[F])w[L]+=h[L]/h[F]*(1+w[F]);F!==v&&(y[F]+=w[F])}for(let p of S)g[p]=-1,h[p]=0,w[p]=0,k[p].length=0}let _=f<=m?1:f/d.length,R=f>2?1/((f-1)*(f-2)):1;return r.map((v,S)=>({symbol:v.name,filePath:v.file,betweenness:y[S]*_*R})).filter(v=>v.betweenness>0).sort((v,S)=>S.betweenness-v.betweenness).slice(0,n)}function Yo(t,e,n){let i=new Map,o=[],r=new Map,c=(g,h)=>`${g}\0${h}`;for(let g of t){let h=g.db.query("SELECT name, filePath FROM symbols").all();for(let w of h){let k=e(g.path,w.filePath),_=c(k,w.name);if(i.has(_))continue;let R=o.length;i.set(_,R),o.push({name:w.name,file:k});let v=r.get(k);v||(v=[],r.set(k,v)),v.push(R)}}let a=o.length;if(a===0)return[];let l=new Map,u=(g,h,w)=>{if(g===h)return;let k=l.get(g);k||(k=new Map,l.set(g,k)),k.set(h,(k.get(h)??0)+w);let _=l.get(h);_||(_=new Map,l.set(h,_)),_.set(g,(_.get(g)??0)+w)};for(let g of t){let h=g.db.query('SELECT callerSymbol, callerFile, calleeSymbol, calleeFile, kind FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all().filter(w=>!n?.length||n.includes(w.kind));for(let w of h){let k=i.get(c(e(g.path,w.callerFile),w.callerSymbol)),_=i.get(c(e(g.path,w.calleeFile),w.calleeSymbol));k!==void 0&&_!==void 0&&u(k,_,1)}}for(let g of r.values())for(let h=1;h<g.length;h++)u(g[0],g[h],.5);let f=Qp(a,l),m=new Map;for(let g=0;g<a;g++){let h=f[g],w=m.get(h);w||(w=[],m.set(h,w)),w.push(g)}let d=[],y=new Set;for(let g of m.values()){let h=new Set(g),w=g.map(E=>o[E].name).sort(),k=Array.from(new Set(g.map(E=>o[E].file))).sort(),_=0,R=0;for(let E of g){let $=l.get(E);if($)for(let[p,F]of $)R+=F,h.has(p)&&(_+=F)}let v=R>0?_/R:1,S=Math.round(Math.max(.1,Math.min(1,v))*100)/100;d.push({name:Yp(k,y),size:w.length,cohesion:S,files:k,symbols:w})}return d.sort((g,h)=>h.size-g.size),d}async function wc(t,e,n,s){let i=Xe(n),o=e.communities.filter(g=>g.size<3).map(g=>({name:g.name,size:g.size,files:g.files??[]})),r=dn(),c=async g=>{let h=new Set;for(let w of g)h.add(await r(w));return[...h].sort()},a=[];for(let g of e.communities){let h=g.files??[];h.length===1&&a.push({name:g.name,size:g.size,file:h[0],languages:await c(h)})}let l=[];if(!s?.skipIsolatedNodes){let g=new Set(Uc(t,i).keys());for(let h of t){let w=h.db.query(`SELECT DISTINCT callerSymbol AS name, callerFile AS file FROM "references" WHERE callerSymbol IS NOT NULL AND kind IN ('schedules', 'listens', 'publishes', 'consumes')`).all();for(let k of w)yn.has(k.name)||g.add(`${i(h.path,k.file)}::${k.name}`)}for(let h of t){let w=h.db.query("SELECT DISTINCT name, filePath FROM symbols").all();for(let k of w){if(yn.has(k.name))continue;let _=i(h.path,k.filePath);g.has(`${_}::${k.name}`)||l.push({symbol:k.name,file:_})}}l.sort((h,w)=>h.file.localeCompare(w.file)||h.symbol.localeCompare(w.symbol))}let u=g=>{for(let w of t){if(w.path===n)continue;let k=`${P.basename(w.path)}/`;if(g.startsWith(k))return{repo:w,rel:g.slice(k.length)}}return{repo:t.find(w=>w.path===n)??t[0],rel:g}},f=(g,h,w,k)=>{for(let R of Hc(w))if(q.existsSync(P.resolve(g,R)))return!0;return h.query('SELECT callerFile FROM "references" WHERE calleeSymbol = ? AND (calleeFile = ? OR calleeFile IS NULL)').all(k,w).some(R=>Et(R.callerFile))},m=[],d=new Set,y=(g,h,w,k)=>{let _=`${h}::${g}`;if(d.has(_))return;let{repo:R,rel:v}=u(h);f(R.path,R.db,v,g)||(d.add(_),m.push({symbol:g,file:h,kind:w,...k}))};for(let g of e.hubs)y(g.symbol,g.filePath,"hub",{degree:g.degree});for(let g of e.bridges)y(g.symbol,g.filePath,"bridge",{betweenness:g.betweenness});return{thinCommunities:o,singleFileCommunities:a,isolatedNodes:l,untestedHotspots:m}}function Gc(t,e,n){let s=new Map,i=[],o=new Set;for(let l of t){let u=l.db.query('SELECT DISTINCT callerSymbol, calleeSymbol, kind FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all();for(let f of u){let m=e.get(f.callerSymbol),d=e.get(f.calleeSymbol);if(!m||!d||m===d)continue;let y=`${f.callerSymbol}\0${f.calleeSymbol}\0${f.kind}`;if(o.has(y))continue;o.add(y);let[g,h]=m<d?[m,d]:[d,m],w=`${g}\0${h}`,k=s.get(w);k||(k={communities:[g,h],count:0,kinds:new Map},s.set(w,k)),k.count++,k.kinds.set(f.kind,(k.kinds.get(f.kind)??0)+1),n||i.push({from:f.callerSymbol,fromCommunity:m,to:f.calleeSymbol,toCommunity:d,kind:f.kind})}}let r=Array.from(s.values()),c=r.length>0?r.reduce((l,u)=>l+u.count,0)/r.length:0;return{couplingPairs:r.map(l=>{let u="",f=-1;for(let[d,y]of Array.from(l.kinds).sort((g,h)=>g[0]<h[0]?-1:1))y>f&&(f=y,u=d);let m=l.count>2*c;return{communities:l.communities,count:l.count,dominantKind:u,...m?{highCoupling:!0}:{}}}).sort((l,u)=>u.count-l.count),edgeList:i}}function Qo(t){let e=new Map;for(let n of t)for(let s of n.symbols??[])e.has(s)||e.set(s,n.name);return e}async function Sc(t,e,n){let s=Xe(n),i=Qo(e.communities),o=new Set(e.hubs.map(l=>`${l.filePath}::${l.symbol}`)),r=dn(),c=new Set,a=[];for(let l of t){let u=l.db.query('SELECT DISTINCT callerSymbol, callerFile, calleeSymbol, calleeFile, kind FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all();for(let f of u){let m=s(l.path,f.callerFile),d=s(l.path,f.calleeFile),y=`${m}::${f.callerSymbol}|${d}::${f.calleeSymbol}|${f.kind}`;if(c.has(y))continue;c.add(y);let g=0,h=[],w=i.get(f.callerSymbol),k=i.get(f.calleeSymbol);w&&k&&w!==k&&(g+=.3,h.push("cross-community")),await r(m)!==await r(d)&&(g+=.2,h.push("cross-language"));let _=o.has(`${m}::${f.callerSymbol}`),R=o.has(`${d}::${f.calleeSymbol}`);_!==R&&(g+=.2,h.push("peripheral-to-hub")),Et(m)!==Et(d)&&(g+=.15,h.push("cross-test-boundary")),f.kind!=="call"&&(g+=.15,h.push("unusual-edge-kind")),g>0&&a.push({from:f.callerSymbol,fromFile:m,to:f.calleeSymbol,toFile:d,kind:f.kind,score:Math.round(g*100)/100,reasons:h})}}return a.sort((l,u)=>u.score-l.score||l.from.localeCompare(u.from)||l.to.localeCompare(u.to)||l.fromFile.localeCompare(u.fromFile)),a}function Ec(t,e){let n=t.length,s=Array.from(e.values()),i=new Set;for(let o of s)i.add(`${o.from}|${o.to}`),i.add(`${o.to}|${o.from}`);for(let o=0;o<n;o++){let r=t[o];for(let c=o+1;c<n;c++){let a=t[c];if(i.has(`${r}|${a}`))continue;let l=P.dirname(r),u=P.dirname(a),f=0;if(l===u)f=.8;else{let k=P.dirname(l),_=P.dirname(u);k===_&&k!=="."&&k!==""&&(f=.4)}let m=k=>P.basename(k,P.extname(k)).replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(R=>R.length>=2&&R!=="test"&&R!=="spec"&&R!=="index"),d=m(r),y=m(a),g=0;if(d.length>0&&y.length>0){let k=new Set(d),_=0;for(let R of y)k.has(R)&&_++;g=_/Math.max(d.length,y.length)}let h=g*.6+f*.4,w=Math.round(h*100)/100;w>=.3&&s.push({from:r,to:a,kind:"inferred",provenance:"INFERRED",confidence:w})}}return s}function eh(t){return new Float32Array(t.buffer,t.byteOffset,t.byteLength/4)}function Xe(t){return(e,n)=>e===t?n:`${P.basename(e)}/${n}`}function th(t){return t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"community"}function kc(t){return gn.createHash("sha256").update(t).digest("hex")}var Fo=50,nh=20;function sh(t,e){let n=t.files??[],s=t.symbols??[],i=new Set(n),o=[];if(o.push(`# ${t.name}`,""),o.push("## Overview",""),o.push(`- Size: ${t.size} symbol(s)`),o.push(`- Cohesion: ${t.cohesion}`,""),o.push("## Files",""),n.length>0)for(let l of n)o.push(`- ${l}`);else o.push("_No files recorded for this community._");if(o.push(""),o.push("## Symbols",""),s.length>0){let l=s.slice(0,Fo);for(let u of l)o.push(`- ${u}`);s.length>Fo&&o.push("",`_(truncated: showing ${Fo} of ${s.length} symbols)_`)}else o.push("_No symbols recorded for this community._");o.push(""),o.push("## Hubs & bridges in this community","");let r=e.hubs.filter(l=>i.has(l.filePath)),c=e.bridges.filter(l=>i.has(l.filePath));if(o.push("### Hubs"),r.length>0)for(let l of r)o.push(`- ${l.symbol} (${l.filePath}) \u2014 degree ${l.degree}`);else o.push("_No hub nodes in this community._");if(o.push("","### Bridges"),c.length>0)for(let l of c)o.push(`- ${l.symbol} (${l.filePath}) \u2014 betweenness ${l.betweenness}`);else o.push("_No bridge nodes in this community._");o.push(""),o.push("## Edges","");let a=e.edges.filter(l=>i.has(l.from)||i.has(l.to)).sort((l,u)=>l.provenance!==u.provenance?l.provenance==="EXTRACTED"?-1:1:(u.confidence??1)-(l.confidence??1)).slice(0,nh);if(a.length>0)for(let l of a)o.push(`- ${l.from} \u2192 ${l.to} (${l.kind}, ${l.provenance})`);else o.push("_No edges touch this community._");return o.push(""),o.join(`
424
+ `)}function ih(t,e,n){let s=[];s.push("# knodin Wiki",""),s.push(`Repo: ${t}`,""),s.push("## Communities",""),s.push("| Name | Size | Cohesion | Top files |","|---|---|---|---|");for(let i of e.communities){let o=(i.files??[]).slice(0,3).join(", ");s.push(`| ${i.name} | ${i.size} | ${i.cohesion} | ${o} |`)}s.push(""),s.push("## Pages","");for(let i of e.communities){let o=n.get(i.name);s.push(`- [${i.name}](${o}.md)`)}return s.push(""),s.join(`
425
+ `)}function vc(t,e,n,s,i,o){let r=P.join(t,e);if(!s&&q.existsSync(r)){let c=q.readFileSync(r,"utf-8");if(kc(c)===kc(n)){o.push(e);return}}q.writeFileSync(r,n,"utf-8"),i.push(e)}async function oh(t,e,n){let s=P.resolve(e),i=await t.map(e,"standard"),o=P.join(s,".knodin","wiki");q.mkdirSync(o,{recursive:!0});let r=new Map,c=new Set;for(let f of i.communities){let m=th(f.name),d=m,y=1;for(;c.has(d);)d=`${m}-${y}`,y++;c.add(d),r.set(f.name,d)}let a=[],l=[];for(let f of i.communities){let m=r.get(f.name),d=sh(f,i);vc(o,`${m}.md`,d,n,a,l)}let u=ih(s,i,r);return vc(o,"index.md",u,n,a,l),{wikiDir:P.relative(s,o)||".",written:a,skipped:l}}function rh(t){if(!q.existsSync(P.join(t,"tsconfig.json")))return null;let e=P.join(t,"node_modules",".bin","tsc");return q.existsSync(e)?`"${e}" --noEmit`:"npx --no-install tsc --noEmit"}function ah(t){return t.split(`
426
+ `).map(e=>e.trim()).filter(e=>/error TS\d+/.test(e))}function xc(t,e){let n;try{n=st.execSync(t,{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(s){let i=s;if(n=`${i.stdout?.toString()??""}${i.stderr?.toString()??""}`,!/error TS\d+/.test(n))return{available:!1,diagnostics:[]}}return{available:!0,diagnostics:ah(n)}}function ch(t,e){let n=new Map;for(let i of t)n.set(i,(n.get(i)??0)+1);let s=[];for(let i of e){let o=n.get(i)??0;o>0?n.set(i,o-1):s.push(i)}return s}function Vc(t){let e=t.split(""),n=null;for(let s=0;s<t.length;s++){let i=t[s];if(n){i===n&&t[s-1]!=="\\"?n=null:e[s]=" ";continue}if(i==='"'||i==="'"||i==="`"){n=i;continue}if(i==="/"&&t[s+1]==="/"){for(let o=s;o<t.length;o++)e[o]=" ";break}}return e.join("")}function lh(t,e,n){let s=Vc(t),i=new RegExp(e.source,"g"),o="",r=0;for(let c=i.exec(s);c;c=i.exec(s))o+=t.slice(r,c.index)+n,r=c.index+c[0].length;return o+t.slice(r)}function uh(t,e){let n;try{n=q.readFileSync(t,"utf-8")}catch{return[]}let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${s}\\b`),o=/^\s*import\b|^\s*export\s*[{*]|\brequire\s*\(/,r=[],c=n.split(`
427
+ `),a=0;for(let l=0;l<c.length;l++){let u=Vc(c[l]);if(a===0&&!o.test(u))continue;i.test(u)&&r.push(l+1);let f=(u.match(/{/g)??[]).length,m=(u.match(/}/g)??[]).length;a=Math.max(0,a+f-m)}return r}function dh(t){return{async explain(e,n,s,i){let o=await t.explain(e,n,s,i);return o.staleness=Ot(n),o},async review(e,n,s,i){let o=await t.review(e,n,s,i);return o.staleness=Ot(n),o},async map(e,n="minimal",s){let i=await t.map(e,n,s),o=s?{...i,communities:[...i.communities],edges:[...i.edges],hubs:[...i.hubs],bridges:[...i.bridges]}:i;if(s&&n==="standard"){let r=s.topN??15;if(s.relationKinds?.length){let a=await It(e),l=await Promise.all(a.map(async f=>({path:f,db:await Ge(f)}))),u=await Oo(l,P.resolve(e),r,s.relationKinds);o.communities=u.communities,o.hubs=u.hubs,o.bridges=u.bridges}let c=(a,l)=>(a.symbol??a.name??"").localeCompare(l.symbol??l.name??"");o.communities=[...o.communities].sort(s.sort==="name"?c:(a,l)=>l.size-a.size||c(a,l)).slice(0,r),o.hubs=[...o.hubs].sort(s.sort==="name"?c:(a,l)=>l.degree-a.degree||c(a,l)).slice(0,r),o.bridges=[...o.bridges].sort(s.sort==="name"?c:(a,l)=>l.betweenness-a.betweenness||c(a,l)).slice(0,r),o.edges=o.edges.filter(a=>!s.relationKinds?.length||s.relationKinds.includes(a.kind)).slice(0,r)}return o.staleness=Ot(e),o},async wiki(e,n){let s=await t.wiki(e,n);return s.staleness=Ot(e),s},status(e,n){return t.status(e,n)},repair(e,n){return t.repair(e,n)},index(e,n,s,i){return t.index(e,n,s,i)},async search(e,n,s,i){let o=await t.search(e,n,s,i),r=Ot(n);for(let c of o.results)c.staleness=r;return o},async query(e,n,s,i,o,r,c,a,l,u){let f=await t.query(e,n,s,i,o,r,c,a,l,u);return f.staleness=Ot(s),f},async rename(e,n,s,i,o,r){let c=await t.rename(e,n,s,i,o,r);return c.staleness=Ot(s),c},close(){return t.close()}}}function XS(){let t={async explain(e,n,s="standard",i={}){let o=await It(n),r=await Promise.all(o.map(async E=>({path:E,db:await Ge(E)}))),c=n,a=null,l=[];for(let E of r){let $=E.db.query("SELECT * FROM symbols WHERE name = ?").all(e);i.file&&($=$.filter(p=>p.filePath===i.file)),i.kind&&($=$.filter(p=>p.kind===i.kind)),i.identity&&($=$.filter(p=>Lo(be(E.path,p),i.identity??"")));for(let p of $)l.push({repo:E.path,row:p})}if(l.sort((E,$)=>E.repo.localeCompare($.repo)||E.row.filePath.localeCompare($.row.filePath)||E.row.startLine-$.row.startLine),l.length>1){let E={kind:"ambiguous_symbol",message:`Ambiguous symbol "${e}" matches ${l.length} definitions; select one by identity, file, or kind.`,candidates:l.map(($,p)=>({identity:be($.repo,$.row),symbol:e,file:Xe(P.resolve(n))($.repo,$.row.filePath),kind:$.row.kind,line:$.row.startLine,rank:p+1}))};return{symbol:e,summary:E.message,source:"",callers:[],callerCount:0,callees:[],calleeCount:0,blastRadius:[],blastRadiusCount:0,ambiguity:E}}if(l[0]&&(a=l[0].row,c=l[0].repo),!a)return{symbol:e,summary:`Symbol "${e}" not found in codebase.`,source:"",callers:[],callerCount:0,callees:[],calleeCount:0,blastRadius:[],blastRadiusCount:0};let u=a.summary||`Symbol "${e}" is a ${a.kind} defined in ${a.filePath}.`,f=Gn(c,a.filePath,a.startLine,a.endLine,500),m=Vn(r,c,e,1,new Set,a.filePath,a.identity??null),d=gi(r,c,e,1,new Set,a.filePath,a.identity??null),y=Xe(P.resolve(n)),g=E=>{let $=new Set,p=[];for(let F of E){let L=y(F.repoPath||c,F.filePath),T=`${F.symbol}|${L}`;if($.has(T))continue;$.add(T);let x=r.find(M=>M.path===(F.repoPath||c)),I=x?.db.query("SELECT * FROM symbols WHERE name = ? AND filePath = ? LIMIT 1").get(F.symbol,F.filePath);p.push({symbol:F.symbol,filePath:L,lineNumber:F.lineNumber,...I?{identity:be(x?.path||c,I)}:{}})}return p},h=g(m),w=g(d),k=Array.from(new Set(h.map(E=>E.filePath))),_=!h.some(E=>Et(E.filePath)),v=s==="minimal"?25:200,S=h.length>v||w.length>v||k.length>v;return{identity:be(c,a),symbol:e,summary:u,source:f,callers:h.slice(0,v),callerCount:h.length,callees:w.slice(0,v),calleeCount:w.length,blastRadius:k.slice(0,v),blastRadiusCount:k.length,untested:_,...S?{truncated:!0}:{}}},async review(e,n,s="standard",i={}){let o=await Ge(n),{modifiedFiles:r,changedFiles:c}=re("review_diff_discovery",()=>{let M=Kp(e,n,i);return{modifiedFiles:M,changedFiles:Xp(e,n,i,M)}}),a=re("review_churn",()=>Ya(n,c,i.historyLimits)),l=new Map(a.churn.map(M=>[M.file,M.commitCount])),u=new Set,f=new Set,m=[],d=new Map,y=Vt("review_parsing");try{for(let M of c){let b=r.get(M)??new Set([Number.MAX_SAFE_INTEGER]),A=M.endsWith(".py"),C=M.endsWith(".cls")||M.endsWith(".trigger"),O=o.query("SELECT * FROM symbols WHERE filePath = ?").all(M);if(O.length===0)continue;let N=!1,j=Hc(M);for(let H of j)if(q.existsSync(P.resolve(n,H))){N=!0;break}let z=l.get(M)??0,D=null;try{let H=P.resolve(n,M);if(q.existsSync(H)){let W=q.readFileSync(H,"utf-8"),X=await Kn(H);if(X){let J=new we;J.setLanguage(X),D=J.parse(W)}}}catch(H){console.error(`Error parsing file ${M} for AST review:`,H)}for(let H of O)if(b.has(Number.MAX_SAFE_INTEGER)||Array.from(b).some(X=>X>=H.startLine&&X<=H.endLine)){u.add(H.name);let X=o.query('SELECT COUNT(*) AS count FROM "references" WHERE calleeSymbol = ? AND (calleeFile = ? OR calleeFile IS NULL)').get(H.name,M)?.count??0,J=o.query('SELECT COUNT(*) AS count FROM "references" WHERE callerSymbol = ? AND callerFile = ?').get(H.name,M)?.count??0;d.set(`${M}\0${H.name}`,{symbol:H.name,file:M,inboundReferences:X,outboundReferences:J,totalReferences:X+J});let Z=1;if(D)try{let ue=Zp(D.rootNode,H.name,A,C);ue&&(Z=Jp(ue))}catch(ue){console.error(`Error calculating complexity for symbol ${H.name}:`,ue)}let Y=!1;N&&(Y=o.query('SELECT callerFile FROM "references" WHERE calleeSymbol = ? AND (calleeFile = ? OR calleeFile IS NULL)').all(H.name,M).some(Ni=>{let En=Ni.callerFile.toLowerCase();return En.includes("test")||En.includes("spec")||En.includes("__tests__")}));let U=!N||!Y;U&&(N?f.add(`${M}::${H.name}`):f.add(M));let B=Math.min(50,Z*2),V=Math.min(50,z*1),te=U?1.5:1,le=Math.min(100,Math.max(0,(B+V)*te));m.push(le)}}}finally{y()}let g=0;m.length>0&&(g=Math.round(m.reduce((M,b)=>M+b,0)/m.length));let h=re("review_flow_lookup",()=>{let M=Bm(o,P.resolve(n)),b=new Set;for(let A of c)for(let C of M.get(A)??[])b.add(C);return b}),w=Array.from(u),k=c.filter(M=>o.query("SELECT 1 AS present FROM symbols WHERE filePath = ? LIMIT 1").get(M)),_=new Set(k),R=c.filter(M=>!_.has(M)),v=Array.from(h),S=Array.from(f),E=[...d.values()].sort((M,b)=>b.totalReferences-M.totalReferences||M.file.localeCompare(b.file)||M.symbol.localeCompare(b.symbol)),$=25,p=s==="minimal",F=p?c.slice(0,$):c,L=p?v.slice(0,$):v,T=p?S.slice(0,$):S,x=p?E.slice(0,$):E,I=p&&(c.length>$||k.length>$||R.length>$||w.length>$||v.length>$||S.length>$);return{base:e,scope:i.scope??"all",changedFiles:p?c.slice(0,$):c,changedFileCount:c.length,mappedChangedFiles:p?k.slice(0,$):k,mappedChangedFileCount:k.length,unmappedChangedFiles:p?R.slice(0,$):R,unmappedChangedFileCount:R.length,riskScore:g,signals:{graphImpact:{affectedFlows:L,changedFiles:F,confidence:"exact-indexed-relationships"},testGaps:{facts:T,confidence:"indexed-references-and-test-paths"},structuralCentrality:{facts:x,confidence:"exact-indexed-references"},history:a},changedSymbols:p?w.slice(0,$):w,changedSymbolCount:w.length,affectedFlows:p?v.slice(0,$):v,affectedFlowCount:v.length,testGaps:p?S.slice(0,$):S,testGapCount:S.length,...I?{truncated:!0}:{}}},async map(e,n="minimal",s={}){let i=s.topN??15;if(!Number.isInteger(i)||i<1||i>1e3)throw new Error("knodin map: topN must be an integer from 1 to 1000");if(s.sort&&!["relevance","name","size","degree","complexity"].includes(s.sort))throw new Error("knodin map: invalid sort");if(s.sort==="complexity")throw new Error("knodin map: sort=complexity is unsupported; use name, size, or degree");let o=P.resolve(e);if(n==="minimal"){let k=await It(e),_=await Promise.all(k.map(async E=>({path:E,db:await Ge(E)}))),R=JSON.stringify([o,i,s.sort??"relevance",[...s.relationKinds??[]].sort()]),v=Bn.get(R);if(v&&v.generation===ne)return v.result;let S=(async()=>{let E=await Oo(_,o,i,s.relationKinds),{communities:$,symbolCommunity:p,aggregate:F}=E,L=dn(),T=[...$].sort(s.sort==="name"?(b,A)=>b.name.localeCompare(A.name):(b,A)=>A.size-b.size||b.name.localeCompare(A.name)),x=await Promise.all(T.slice(0,i).map(async b=>{let A=new Map;for(let O of b.files??[]){let N=await L(O);A.set(N,(A.get(N)??0)+1)}let C=[...A].sort((O,N)=>N[1]-O[1])[0]?.[0];return{name:b.name,size:b.size,cohesion:b.cohesion,dominantLanguage:C}})),I=[...E.hubs].sort(s.sort==="name"?(b,A)=>b.symbol.localeCompare(A.symbol):(b,A)=>A.degree-b.degree||b.symbol.localeCompare(A.symbol)),M=[...E.bridges].sort(s.sort==="name"?(b,A)=>b.symbol.localeCompare(A.symbol):(b,A)=>A.betweenness-b.betweenness||b.symbol.localeCompare(A.symbol));return{repoPath:o,communities:x,edges:F.couplingPairs.filter(b=>!s.relationKinds?.length||s.relationKinds.includes(b.dominantKind)).slice(0,i).map(b=>({from:b.communities[0],to:b.communities[1],kind:b.dominantKind,provenance:"AGGREGATED",count:b.count,highCoupling:b.highCoupling})),hubs:I.slice(0,i).map(b=>({...b,communityId:p.get(b.symbol)})),bridges:M.slice(0,i).map(b=>({...b,communityId:p.get(b.symbol)})),communityCount:$.length,edgeCount:F.couplingPairs.length,hubCount:I.length,bridgeCount:M.length}})();return S.catch(()=>{Bn.get(R)?.result===S&&Bn.delete(R)}),ft(Bn,R,{generation:ne,result:S},Tm),S}let r=zn.get(o);if(r&&r.generation===ne)return r.result;let c=(async()=>{let k=await It(e),_=await Promise.all(k.map(async b=>({path:b,db:await Ge(b)}))),R=Xe(o),v=await Oo(_,o),{communities:S,symbolCommunity:E}=v,$=v.hubs.map(b=>({...b,communityId:E.get(b.symbol)})),p=v.bridges.map(b=>({...b,communityId:E.get(b.symbol)}));if(k.length<=1){let X=function(Y,U,B,V=1,te){if(Y===U)return;let le=`${Y}|${U}|${B}`;W.has(le)||W.set(le,{from:Y,to:U,kind:B,provenance:"EXTRACTED",confidence:V,confidenceLabel:V>=1?"exact":"heuristic",...te?{sourceEvidence:te}:{}})},b=_[0].db,A=new Set,C=b.query("SELECT DISTINCT filePath FROM symbols").all();for(let Y of C)A.add(Y.filePath);let O=b.query("SELECT fromFile, toFile, kind, COALESCE(confidence, 1.0) AS confidence, sourceEvidence FROM dependencies").all();for(let Y of O)A.add(Y.fromFile),A.add(Y.toFile);let N=b.query('SELECT DISTINCT callerFile FROM "references"').all();for(let Y of N)A.add(Y.callerFile);let j=Array.from(A).sort();if(j.length===0)return{repoPath:o,communities:S,edges:[],hubs:$,bridges:p};let D=b.query("SELECT name, filePath FROM symbols").all(),H=new Map;for(let Y of D){let U=H.get(Y.name);U||(U=[],H.set(Y.name,U)),U.push(Y.filePath)}let W=new Map;for(let Y of O)X(Y.fromFile,Y.toFile,Y.kind,Y.confidence,Y.sourceEvidence);let J=b.query('SELECT callerFile, calleeSymbol, calleeFile FROM "references"').all();for(let Y of J){let U=Y.calleeFile;if(!U){let B=H.get(Y.calleeSymbol);B&&B.length===1&&(U=B[0])}!U||U===Y.callerFile||X(Y.callerFile,U,"calls")}return{repoPath:o,communities:S,edges:Ec(j,W),hubs:$,bridges:p}}let F=new Set;for(let b of _){let A=b.db.query("SELECT DISTINCT filePath FROM symbols").all();for(let N of A)F.add(R(b.path,N.filePath));let C=b.db.query("SELECT fromFile, toFile FROM dependencies").all();for(let N of C)F.add(R(b.path,N.fromFile)),F.add(R(b.path,N.toFile));let O=b.db.query('SELECT DISTINCT callerFile FROM "references"').all();for(let N of O)F.add(R(b.path,N.callerFile))}let L=Array.from(F).sort();if(L.length===0)return{repoPath:o,communities:S,edges:[],hubs:$,bridges:p};let x=new Map;for(let b of _){let A=b.db.query("SELECT name, filePath FROM symbols").all();for(let C of A){let O=x.get(C.name);O||(O=[],x.set(C.name,O)),O.push({repoPath:b.path,file:R(b.path,C.filePath)})}}let I=new Map,M=(b,A,C,O=1,N)=>{if(b===A)return;let j=`${b}|${A}|${C}`;I.has(j)||I.set(j,{from:b,to:A,kind:C,provenance:"EXTRACTED",confidence:O,confidenceLabel:O>=1?"exact":"heuristic",...N?{sourceEvidence:N}:{}})};for(let b of _){let A=b.db.query("SELECT fromFile, toFile, kind, COALESCE(confidence, 1.0) AS confidence, sourceEvidence FROM dependencies").all();for(let C of A){let O=R(b.path,C.fromFile),N=R(b.path,C.toFile);M(O,N,C.kind,C.confidence,C.sourceEvidence)}}for(let b of _){let A=b.db.query('SELECT callerFile, calleeSymbol, calleeFile FROM "references"').all();for(let C of A){let O=R(b.path,C.callerFile),N=x.get(C.calleeSymbol),j=null;if(C.calleeFile)j=R(b.path,C.calleeFile);else{let D=N?.filter(H=>H.repoPath===b.path)??[];D.length===1&&(j=D[0].file)}if(j&&j!==O&&M(O,j,"calls"),!N?.some(D=>D.repoPath===b.path))for(let D of _){if(D.path===b.path)continue;let H=D.db.query(`
428
+ SELECT filePath, name FROM symbols
429
+ WHERE kind = 'endpoint'
430
+ `),W=H.all();H.finalize();for(let X of W)if(hi(C.calleeSymbol,X.name)){let J=R(D.path,X.filePath);M(O,J,"calls")}}}}return{repoPath:o,communities:S,edges:Ec(L,I),hubs:$,bridges:p}})();c.catch(()=>{zn.get(o)?.result===c&&zn.delete(o)}),zn.set(o,{generation:ne,result:c});let a=await c;if(n==="standard")return a;let l=dn(),u=await It(e),f=await Promise.all(u.map(async k=>({path:k,db:await Ge(k)}))),m=await Promise.all(a.communities.map(async k=>{let _=k.files??[],R=new Map;for(let E of _){let $=await l(E);R.set($,(R.get($)??0)+1)}let v,S=-1;for(let[E,$]of R.entries())$>S&&(S=$,v=E);return{name:k.name,size:k.size,cohesion:k.cohesion,dominantLanguage:v}})),d=Qo(a.communities),g=Gc(f,d,!0).couplingPairs.map(k=>({from:k.communities[0],to:k.communities[1],kind:k.dominantKind,provenance:"AGGREGATED",count:k.count,highCoupling:k.highCoupling})),h=a.hubs.slice(0,15),w=a.bridges.slice(0,15);return{repoPath:a.repoPath,communities:m,edges:g,hubs:h,bridges:w,staleness:a.staleness}},async wiki(e,n=!1){return oh(t,e,n)},async status(e,n={}){let s=P.resolve(e),i=Mt.get(s),o=P.join(s,".knodin","db.sqlite"),r=i??(q.existsSync(o)?new an(o,{readonly:!0}):null),c=new Date().toISOString(),a=n.ignoreActiveOperation?null:Ia(s);if(a){let b=re("status_audit",()=>kt(s)),A=0,C=0,O=0,N=null;if(r){try{A=r.query("PRAGMA user_version").get()?.user_version??0,C=r.query("SELECT COUNT(*) count FROM index_state").get()?.count??0,O=r.query("SELECT COUNT(DISTINCT filePath) count FROM symbols").get()?.count??0,N=Te(r,"lastSuccessfulReconciliation")??null}catch{}i||r.close()}return{status:"indexing",repo:s,version:Mn,schemaVersion:A,model:{id:"Xenova/all-MiniLM-L6-v2",dimensions:384,locality:"local"},coverage:{sourceFiles:b.length,indexedFiles:C,filesWithSymbols:O,percent:b.length?Math.round(Math.min(C,b.length)/b.length*1e4)/100:100},orphaned:{embeddings:0,references:0,dependencies:0},missing:{files:[],records:[]},lastSuccessfulReconciliation:N,lastIndexedHead:r?Te(r,"lastIndexedHead")??"":"",freshness:Gs(s,r,c,"indexing"),verification:{mode:"live-operation",verifiedAt:c},repairSteps:[],activity:a}}if(!r){let b=re("status_audit",()=>kt(s));return{status:"repair-needed",repo:s,version:Mn,schemaVersion:0,model:{id:"Xenova/all-MiniLM-L6-v2",dimensions:384,locality:"local"},coverage:{sourceFiles:b.length,indexedFiles:0,filesWithSymbols:0,percent:b.length?0:100},orphaned:{embeddings:0,references:0,dependencies:0},missing:{files:b,records:["local index database is missing"]},lastSuccessfulReconciliation:null,lastIndexedHead:"",freshness:Gs(s,null,c,"repair-needed"),verification:{mode:"deep-audit",verifiedAt:c},repairSteps:["Run `knodin repair` to create the local index.","Run `knodin status` again to verify health."]}}let l=Fm(o),u=cn.get(s);if(n.audit!=="deep"&&u?.generation===ne&&u.databaseFingerprint===l){let b=Date.parse(u.result.verification.verifiedAt);if(u.result.status==="repair-needed"&&Number.isFinite(b)&&Date.now()-b<Vo)return i||r.close(),structuredClone(u.result);try{let A=Dt.get(s);if(A&&A.staleness!=="unknown"&&Date.now()-A.at<Vo)return i||r.close(),{...structuredClone(u.result),verification:{mode:"cached-after-freshness-probe",verifiedAt:new Date(A.at).toISOString()}};let C=re("freshness_probe",()=>zc(s,r));if(C.verifiable&&!C.drifted)return jt(s,"fresh"),i||r.close(),{...structuredClone(u.result),verification:{mode:"cached-after-freshness-probe",verifiedAt:c}}}catch{}}let f=re("status_audit",()=>kt(s)),m=r.query("PRAGMA user_version").get()?.user_version??0,d=["symbols","references","dependencies","symbol_embeddings","index_state","meta"],y=new Set(r.query("SELECT name FROM sqlite_master WHERE type='table'").all().map(b=>b.name)),g=y.has("index_state")?new Set(r.query("PRAGMA table_info(index_state)").all().map(b=>b.name)):new Set,h=d.filter(b=>!y.has(b)).map(b=>`required table is missing: ${b}`);for(let b of["filePath","mtimeMs","size"])g.has(b)||h.push(`required index_state column is missing: ${b}`);if(m<18&&h.push(`schema ${m} is older than required schema 18`),h.length)return i||r.close(),{status:"repair-needed",repo:s,version:Mn,schemaVersion:m,model:{id:"Xenova/all-MiniLM-L6-v2",dimensions:384,locality:"local"},coverage:{sourceFiles:f.length,indexedFiles:0,filesWithSymbols:0,percent:f.length?0:100},orphaned:{embeddings:0,references:0,dependencies:0},missing:{files:f,records:h},lastSuccessfulReconciliation:null,lastIndexedHead:"",freshness:Gs(s,r,c,"repair-needed"),verification:{mode:"deep-audit",verifiedAt:c},repairSteps:["Run `knodin repair` to migrate/rebuild damaged local schema.","Run `knodin status` again to verify health."]};let w=r.query("SELECT filePath, mtimeMs, size FROM index_state").all(),k=new Set(w.map(b=>b.filePath)),_=new Set(f),R=new Set(r.query("SELECT DISTINCT filePath FROM symbols").all().map(b=>b.filePath)),v=f.filter(b=>!k.has(b)),S=w.map(b=>b.filePath).filter(b=>!_.has(b)&&!q.existsSync(P.join(s,b))),E=w.map(b=>b.filePath).filter(b=>!_.has(b)&&q.existsSync(P.join(s,b))),$=w.filter(b=>{if(!_.has(b.filePath))return!1;try{let A=q.statSync(P.join(s,b.filePath));return A.size!==b.size||Math.abs(A.mtimeMs-b.mtimeMs)>=1}catch{return!1}}).map(b=>b.filePath),p=b=>r.query(b).get()?.count??0,F={embeddings:p(`SELECT COUNT(*) count FROM symbol_embeddings WHERE ${Dn}`),references:p('SELECT COUNT(*) count FROM "references" r WHERE NOT EXISTS (SELECT 1 FROM index_state i WHERE i.filePath=r.callerFile)'),dependencies:p("SELECT COUNT(*) count FROM dependencies d WHERE NOT EXISTS (SELECT 1 FROM index_state i WHERE i.filePath=d.fromFile)")},L=S.map(b=>`indexed file no longer exists: ${b}`);for(let b of E)L.push(`indexed file is no longer eligible: ${b}`);for(let b of $)L.push(`indexed snapshot differs from disk: ${b}`);F.embeddings&&L.push(`${F.embeddings} embedding row(s) lack a symbol`),F.references&&L.push(`${F.references} reference row(s) lack an indexed caller file`),F.dependencies&&L.push(`${F.dependencies} dependency row(s) lack an indexed source file`),Te(r,"repairPostprocessingPending")==="1"&&L.push("repair post-processing is incomplete");let T=v.length>0||L.length>0,x=Gs(s,r,c,T?"repair-needed":void 0),I=!T&&x.state!=="fresh",M={status:T?"repair-needed":I?"stale":"healthy",repo:s,version:Mn,schemaVersion:m,model:{id:"Xenova/all-MiniLM-L6-v2",dimensions:384,locality:"local"},coverage:{sourceFiles:f.length,indexedFiles:k.size,filesWithSymbols:R.size,percent:f.length?Math.round((f.length-v.length)/f.length*1e4)/100:100},orphaned:F,missing:{files:v,records:L},lastSuccessfulReconciliation:Te(r,"lastSuccessfulReconciliation")??null,lastIndexedHead:Te(r,"lastIndexedHead")??"",freshness:x,indexGeneration:ne,verification:{mode:"deep-audit",verifiedAt:c},repairSteps:T?["Run `knodin repair` to rebuild only missing or damaged local state.","Run `knodin status` again to verify health."]:[]};return i||r.close(),!T&&!I&&jt(s,"fresh"),ft(cn,s,{generation:ne,databaseFingerprint:l,result:structuredClone(M)},Am),M},async repair(e,n){let s=P.resolve(e),i=Ws.get(s);if(i){n?.onProgress&&i.subscribers.add(n.onProgress);let v=()=>i.controller.abort();n?.signal?.aborted?v():n?.signal?.addEventListener("abort",v,{once:!0});try{return await i.promise}finally{n?.onProgress&&i.subscribers.delete(n.onProgress),n?.signal?.removeEventListener("abort",v)}}let o=gn.randomUUID(),r=Date.now(),c=0,a=0,l,u={indexed:0,rebuilt:0,removed:0,skipped:0,failed:0},f,m=[],d=[],y=0,g=!1,h=ne,w={promise:void 0,subscribers:new Set(n?.onProgress?[n.onProgress]:[]),controller:new AbortController},k=()=>w.controller.abort();n?.signal?.aborted?k():n?.signal?.addEventListener("abort",k,{once:!0});let _=(v,S,E,$={})=>{let p={operationId:o,sequence:++c,timestamp:new Date().toISOString(),phase:v,phaseCompleted:S,overallCompleted:a,...u,elapsedMs:Date.now()-r,message:E,...$};l!==void 0&&(p.overallTotal=l);for(let F of[...w.subscribers])try{F(p)}catch{}},R=Promise.resolve().then(async()=>{let v=()=>{if(w.controller.signal.aborted)throw w.controller.signal},S=()=>{g&&ne===h&&ne++};_("audit",0,"Auditing repository health"),f=await t.status(s),_("audit",1,"Repository health audit completed",{phaseTotal:1}),v(),_("planning",0,"Building the repair plan");let E=new Map;for(let b of f.missing.files)E.set(b,"indexed");for(let b of f.missing.records){let A="indexed snapshot differs from disk: ",C="indexed file no longer exists: ",O="indexed file is no longer eligible: ";b.startsWith(A)?E.set(b.slice(A.length),"damaged"):b.startsWith(C)?E.set(b.slice(C.length),"stale"):b.startsWith(O)&&E.set(b.slice(O.length),"stale")}let $=P.join(s,".knodin","db.sqlite");if(q.existsSync($)){let b=Mt.get(s),A=b??new an($);if(A.query("SELECT COUNT(*) count FROM sqlite_master WHERE type='table' AND name='index_state'").get()?.count===1){let O=new Set(A.query("PRAGMA table_info(index_state)").all().map(N=>N.name));O.has("mtimeMs")||(A.run("ALTER TABLE index_state ADD COLUMN mtimeMs REAL"),g=!0),O.has("size")||(A.run("ALTER TABLE index_state ADD COLUMN size INTEGER"),g=!0)}b||A.close()}let p=Mt.get(s)??await Ge(s,{skipContentReconciliation:!0,skipFreshnessGuard:!0}),F=Te(p,"repairPostprocessingPending")==="1",L=new Set(kt(s));d=[...E.keys()].filter(b=>E.get(b)==="stale"||pi(p,s,b)).sort(),u.skipped=Math.max(0,E.size-d.length),l=d.length+4,_("planning",d.length,"Repair plan completed",{phaseTotal:d.length}),v(),_("repair-files",0,"Reconciling files",{phaseTotal:d.length});for(let[b,A]of d.entries()){let C=P.join(s,A),O=!L.has(A)||!q.existsSync(C);if(!O)await Jn(C,A,s,p),Yn(p,s,A),E.get(A)==="damaged"?u.rebuilt++:u.indexed++;else{p.run("BEGIN TRANSACTION;");try{ye(p,A),p.run('DELETE FROM "references" WHERE callerFile = ?',[A]),p.run("DELETE FROM dependencies WHERE fromFile = ?",[A]),p.run("DELETE FROM mcp_tools WHERE filePath = ?",[A]),mi(p,A),p.run("COMMIT;")}catch(j){throw p.run("ROLLBACK;"),j}u.removed++}g=!0,Fe(p,"repairPostprocessingPending","1"),y=b+1;let N=E.get(A);O||N==="stale"?m.push(`removed stale records for ${A}`):N==="indexed"?m.push(`indexed ${A}`):m.push(`rebuilt damaged state for ${A}`),a++,_("repair-files",b+1,`Reconciled ${A}`,{phaseTotal:d.length,currentFamily:Em(A),currentPath:A.replaceAll("\\","/")}),v()}let T=d.length>0||Te(p,"repairPostprocessingPending")==="1";if(T){_("symbol-identities",0,"Persisting stable symbol identities",{phaseTotal:1}),v(),zt(p,s,F?void 0:d),g=!0,a++,_("symbol-identities",1,"Stable symbol identities persisted",{phaseTotal:1}),v();let b=0;_("embeddings",0,"Refreshing embeddings"),v(),await fn(p,s,(A,C,O,N={})=>{if(A==="embedding-symbols")b=N.phaseTotal??b,_("embeddings",C,O,{...N.phaseTotal===void 0?{}:{phaseTotal:N.phaseTotal}});else if(A==="embedding-model"){let j=N.modelFile?` (${N.modelFile})`:"";_("embeddings",0,`${O}${j}`)}}),g=!0,Fe(p,"repairPostprocessingPending","0"),a++,_("embeddings",b,"Embeddings refreshed",{phaseTotal:b}),v()}else a+=2,_("symbol-identities",0,"No symbol identities required repair",{phaseTotal:0}),_("embeddings",0,"No embeddings required repair",{phaseTotal:0}),v();let x=f.orphaned.embeddings>0||f.orphaned.references>0||f.orphaned.dependencies>0;if(_("orphan-cleanup",0,"Cleaning orphaned graph records",{phaseTotal:3}),v(),x){p.run("BEGIN TRANSACTION;");try{p.run(`DELETE FROM symbol_embeddings WHERE ${Dn}`),p.run('DELETE FROM "references" WHERE NOT EXISTS (SELECT 1 FROM index_state i WHERE i.filePath="references".callerFile)'),p.run("DELETE FROM dependencies WHERE NOT EXISTS (SELECT 1 FROM index_state i WHERE i.filePath=dependencies.fromFile)"),p.run("COMMIT;")}catch(b){throw p.run("ROLLBACK;"),b}g=!0}a++,_("orphan-cleanup",3,"Orphan cleanup completed",{phaseTotal:3}),f.orphaned.embeddings&&m.push("removed orphaned embeddings"),f.orphaned.references&&m.push("removed orphaned references"),f.orphaned.dependencies&&m.push("removed orphaned dependencies"),v(),S(),_("verification",0,"Verifying repaired index",{phaseTotal:1}),v();let I=await t.status(s,{audit:"deep"});if(v(),a++,_("verification",1,"Repair verification completed",{phaseTotal:1}),v(),E.size>0||x||T){let b=new Date().toISOString();I.coverage.sourceFiles===I.coverage.indexedFiles&&I.missing.files.length===0&&I.missing.records.length===0&&Object.values(I.orphaned).every(C=>C===0)&&(I.freshness.state==="stale-head"||I.freshness.state==="unknown")&&Fe(p,"lastIndexedHead",mn(s)??""),Fe(p,"lastSuccessfulReconciliation",b),hn(s,p),cn.delete(s),I=await t.status(s,{audit:"deep"})}let M={repaired:m,before:f,after:I,verified:I.status==="healthy",cancelled:!1,remaining:0};return _("completed",a,M.verified?"Repair completed and verified":"Repair completed with remaining issues",{phaseTotal:l}),M}).catch(async v=>{if(v===w.controller.signal){g&&ne===h&&ne++;let S=await t.status(s,{audit:"deep"}),E=Math.max(0,d.length-y);return _("cancelled",y,`Repair cancelled with ${E} file(s) remaining`,{phaseTotal:d.length}),{repaired:m,before:f,after:S,verified:!1,cancelled:!0,remaining:E}}throw u.failed++,_("failed",a,"Repair failed",{phaseTotal:l}),v});w.promise=R,Ws.set(s,w);try{return await R}finally{n?.signal?.removeEventListener("abort",k),n?.onProgress&&w.subscribers.delete(n.onProgress),Ws.get(s)===w&&Ws.delete(s)}},async index(e,n,s=!1,i){let o=[],r=[],c,a=Ip(i?.onProgress);a("starting",0,"Opening local graph database");let l=await Ge(e,{onProgress:a,skipContentReconciliation:!0,skipFreshnessGuard:!0}),u="Local graph is current";if(n&&n.length>0){a("indexing-files",0,`Checking ${n.length.toLocaleString()} requested files`,{phaseTotal:n.length});for(let[h,w]of n.entries()){let k=P.isAbsolute(w)?P.relative(e,w):w,_=P.resolve(e,k),R=s||pi(l,e,k);if(!R)r.push(k);else if(q.existsSync(_))await Jn(_,k,e,l),Yn(l,e,k);else{l.run("BEGIN TRANSACTION;");try{ye(l,k),l.run('DELETE FROM "references" WHERE callerFile = ?',[k]),l.run("DELETE FROM dependencies WHERE fromFile = ?",[k]),l.run("DELETE FROM mcp_tools WHERE filePath = ?",[k]),l.run("COMMIT;")}catch(v){l.run("ROLLBACK;"),console.error(`Error deleting file from index: ${k}`,v)}mi(l,k)}R&&o.push(k),a("indexing-files",h+1,`Checking ${n.length.toLocaleString()} requested files`,{phaseTotal:n.length})}o.length>0&&(a("finalizing",0,"Refreshing identities and semantic embeddings"),zt(l,e,o),await fn(l,e,a),ne++);let g=r.length===1?"1 requested file already current":`${r.length.toLocaleString()} requested files already current`;u=o.length===0?g:`Indexed ${o.length.toLocaleString()} requested file(s); ${g}`}else{let g=!1;try{let h=l.query("SELECT COUNT(*) as count FROM symbols").all();h&&h.length>0&&h[0].count>0&&(g=!0)}catch{}!s&&g?(a("collecting-files",0,"Checking existing local graph for changes"),await Zo(e,l,a)):await Bc(e,l,a),o.push(...kt(e)),u=`${o.length.toLocaleString()} repository file(s) are current`}if(i?.scip){let g=tc(e,i.scip),h=wp(l,e,g);a("finalizing",0,"Refreshing SCIP identities and semantic embeddings"),await fn(l,e,a),ne++;let w={...vo,...i.scip};c={provenance:"scip",inputPath:g.inputPath,bytes:g.bytes,files:g.files,facts:g.facts,languages:g.languages,indexers:g.indexers,elapsedMs:g.elapsedMs,bounds:{maxBytes:w.maxBytes,maxFiles:w.maxFiles,maxFacts:w.maxFacts,timeoutMs:w.timeoutMs}};for(let k of h)o.includes(k)||o.push(k)}a("verifying",0,"Verifying local graph health",{phaseTotal:1});let f=await t.status(e,{audit:"deep",ignoreActiveOperation:!0});f.coverage.sourceFiles===f.coverage.indexedFiles&&f.missing.files.length===0&&f.missing.records.length===0&&Object.values(f.orphaned).every(g=>g===0)&&(f.freshness.state==="stale-head"||f.freshness.state==="unknown")&&(Fe(l,"lastIndexedHead",mn(e)??""),Fe(l,"lastSuccessfulReconciliation",new Date().toISOString()),hn(e,l),cn.delete(P.resolve(e)),f=await t.status(e,{audit:"deep",ignoreActiveOperation:!0})),cn.delete(P.resolve(e));let d=f.missing.files.length+f.missing.records.length;f.status==="healthy"?(n&&n.length>0&&(Fe(l,"lastIndexedHead",mn(e)??""),Fe(l,"lastSuccessfulReconciliation",new Date().toISOString()),hn(e,l)),jt(e,"fresh"),!process.env.VITEST&&process.env.NODE_ENV!=="test"&&Wp(e,l)):Dt.delete(P.resolve(e)),a("verifying",1,f.status==="healthy"?"Local graph health verified":`Local graph still has ${d.toLocaleString()} issue(s)`,{phaseTotal:1});let y=n?.length??o.length;return a("completed",y,f.status==="healthy"?u:`${u}; verification found ${d.toLocaleString()} issue(s)`,{phaseTotal:y}),{indexed:o,unchanged:r,scip:c,verification:{status:f.status,issueCount:d,missing:f.missing,verifiedAt:f.verification.verifiedAt}}},async search(e,n,s,i={}){let o=P.resolve(n),r=i.offset??0;if(!Number.isInteger(r)||r<0)throw new Error("knodin search: offset must be a non-negative integer");if(i.testScope&&!["all","test","production"].includes(i.testScope))throw new Error("knodin search: invalid testScope");let c=i.federate===!1?[o]:await It(n),a=await Promise.all(c.map(async b=>({path:b,db:await Ge(b)}))),l=new Map(a.map(b=>[b.path,jm(b.path,b.db)])),u=typeof s=="number"&&Number.isFinite(s)?Math.min(Math.max(Math.trunc(s),1),100):5,f=r+u,m=new Set((i.extensions??[]).map(b=>b.toLowerCase().replace(/^\./,""))),d=new Set((i.languages??[]).map(b=>b.toLowerCase())),y=new Set((i.kinds??[]).map(b=>b.toLowerCase())),g=m.size>0||d.size>0||y.size>0||!!i.path||i.testScope!==void 0&&i.testScope!=="all",h={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",rb:"ruby",cs:"csharp"},w=b=>{let A=P.extname(b.filePath).slice(1).toLowerCase();return!(m.size&&!m.has(A)||d.size&&!d.has(h[A]??A)||y.size&&!y.has(b.kind.toLowerCase())||i.path&&!b.filePath.toLowerCase().includes(i.path.toLowerCase())||i.testScope==="test"&&!Et(b.filePath)||i.testScope==="production"&&Et(b.filePath))},k=Xe(o),_=i.retrievalMode??"complete",R=b=>b.toLocaleLowerCase().replace(/[^a-z0-9]/g,""),v=b=>{let A=b.length>0?cc(a,o):new Map;return b.map(({repo:C,row:O})=>{let N="";i.includeSource!==!1&&(N=Gn(C.path,O.filePath,O.startLine,O.endLine,500));let j=C.db.query(`
431
+ SELECT DISTINCT callerSymbol FROM "references"
432
+ WHERE calleeSymbol = ? AND callerSymbol IS NOT NULL AND callerSymbol != ?
433
+ AND (calleeFile = ? OR calleeFile IS NULL)
434
+ `),z=j.all(O.name,O.name,O.filePath).map(H=>H.callerSymbol).sort((H,W)=>H.localeCompare(W));j.finalize();let D=k(C.path,O.filePath);return{identity:be(C.path,O),symbol:O.name,kind:O.kind,filePath:D,similarity:1,rrfScore:1,source:N,belongsToCommunity:A.get(D)||"core-module",directCallers:z}})},S=b=>{let A=Math.min(200,Math.max(f*4,20)),C=b.slice(0,A),O=new Set(C.map(({repo:j,row:z})=>`${j.path}:${z.id}`)),N=[...b];for(let j=0;j<2&&N.length>0&&C.length<A;j++){let z=[];for(let D of N){let H=D.repo.db.query(`SELECT callerSymbol, callerFile, calleeSymbol, calleeFile FROM "references"
435
+ WHERE (callerSymbol = ? AND callerFile = ?)
436
+ OR (calleeSymbol = ? AND calleeFile = ?)
437
+ ORDER BY callerFile, callerSymbol, calleeFile, calleeSymbol
438
+ LIMIT 200`).all(D.row.name,D.row.filePath,D.row.name,D.row.filePath),W=l.get(D.repo.path);for(let X of H){let J=X.callerSymbol===D.row.name&&X.callerFile===D.row.filePath,Z=J?X.calleeSymbol:X.callerSymbol,Y=J?X.calleeFile:X.callerFile;if(!(!Z||!Y))for(let U of W.rows){if(U.name!==Z||!w(U)||Y&&U.filePath!==Y)continue;let B=`${D.repo.path}:${U.id}`;if(!O.has(B)){if(O.size>=A)break;O.add(B),z.push({repo:D.repo,row:U})}}}}z.sort((D,H)=>D.repo.path.localeCompare(H.repo.path)||D.row.filePath.localeCompare(H.row.filePath)||D.row.startLine-H.row.startLine),C.push(...z.slice(0,A-C.length)),N=z}return C};if(i.structural){let b=R(e),A=a.flatMap(O=>l.get(O.path).rows.filter(N=>w(N)&&R(N.name).includes(b)).map(N=>({repo:O,row:N}))).sort((O,N)=>O.row.name.localeCompare(N.row.name)||O.row.filePath.localeCompare(N.row.filePath)||O.row.startLine-N.row.startLine);return{results:A.slice(r,r+u).map(({repo:O,row:N})=>({identity:be(O.path,N),symbol:N.name,kind:N.kind,filePath:k(O.path,N.filePath),similarity:1,rrfScore:1,source:"",belongsToCommunity:"",directCallers:[]})),total:A.length,offset:r,limit:u,hasMore:r+u<A.length,retrieval:{route:["exact-name"],embeddingsUsed:!1}}}if(_!=="vector-only"){let b=e.trim().replaceAll("\\","/"),A=R(b),C=b.startsWith("sym_")?b:void 0,O=b.includes("/")||/\.[A-Za-z0-9]+$/.test(b),N=a.flatMap(j=>l.get(j.path).rows.filter(z=>{if(!w(z))return!1;if(C)return Lo(be(j.path,z),C);if(O){let D=z.filePath.replaceAll("\\","/");return D===b||D.endsWith(`/${b}`)}return A.length>0&&R(z.name)===A}).map(z=>({repo:j,row:z}))).sort((j,z)=>j.repo.path.localeCompare(z.repo.path)||j.row.filePath.localeCompare(z.row.filePath)||j.row.startLine-z.row.startLine);if(N.length>0){let j=_==="complete"||_==="bounded-graph"?S(N):N,z=j.slice(r,r+u);return{results:v(z),total:j.length,offset:r,limit:u,hasMore:r+u<j.length,retrieval:{route:_==="complete"||_==="bounded-graph"?[C?"stable-identity":O?"exact-path":"exact-name","bounded-graph"]:[C?"stable-identity":O?"exact-path":"exact-name"],embeddingsUsed:!1}}}}let E=new Map;if(_!=="vector-only"){for(let A of a){let C=l.get(A.path),O=new Set(C.rows.filter(w).map(Z=>Z.id)),N=e.replace(/[^\w\s]/g," ").trim().split(/\s+/).filter(Z=>Z.length>=4).map(Z=>`"${Z}"`),j=Z=>{if(N.length===0)return[];try{let Y=A.db.query(`
439
+ SELECT symbolId FROM symbols_fts
440
+ WHERE symbols_fts MATCH ?
441
+ ORDER BY bm25(symbols_fts), symbolId
442
+ LIMIT 100
443
+ `),U=Y.all(N.join(Z)).map(({symbolId:B})=>B).filter(B=>O.has(B));return Y.finalize(),U}catch(Y){return console.error(`FTS query failed for "${e}":`,Y),[]}},z=re("fts",()=>j(" ")),D=N.length>1?re("fts",()=>j(" OR ")):z,H=D.map(Z=>C.rowById.get(Z)).filter(Z=>Z!==void 0).map(Z=>({repo:A,row:Z})),W=S(H).filter(({repo:Z})=>Z.path===A.path).map(({row:Z})=>Z.id),X=z.map(Z=>C.rowById.get(Z)).filter(Z=>Z!==void 0).map(Z=>({repo:A,row:Z})),J=S(X).filter(({repo:Z})=>Z.path===A.path).map(({row:Z})=>Z.id);E.set(A.path,{and:z,or:D,structural:W,sufficient:J})}let b=_==="complete"&&!wo()&&[...E.values()].some(A=>A.and.length>0);if(_==="lexical-only"||_==="bounded-graph"||b){let A=a.flatMap(O=>{let N=l.get(O.path),j=E.get(O.path);return((b?j?.sufficient:_==="bounded-graph"?j?.structural:j?.or)??[]).map(D=>N.rowById.get(D)).filter(D=>D!==void 0).map(D=>({repo:O,row:D}))}),C=A.slice(r,r+u);return{results:v(C),total:A.length,offset:r,limit:u,hasMore:r+u<A.length,retrieval:{route:_==="bounded-graph"||b?["lexical","bounded-graph"]:["lexical"],embeddingsUsed:!1}}}}let $=await Hm(e,!0),p=[],F=0;for(let b of a){let A=b.db,C=l.get(b.path),O=C.rows.filter(w),N=new Set(O.map(B=>B.id));F+=N.size;let j=[];if(wo()&&!g){let B=zm(b.path,C.rows),V=Wa(),{results:te}=B.search($,V,Math.max(f,V));for(let le of te){let ue=C.rowById.get(le.id);ue&&N.has(ue.id)&&j.push({id:le.id,score:le.score,row:ue})}}else re("similarity",()=>{for(let B of O)if(B.vector)try{xt.vectorScores++;let V=Cs($,B.vector);j.push({id:B.id,score:V,row:B})}catch(V){console.error(`Skipping corrupt embedding for symbol ${B.id}:`,V)}});let z=j.sort((B,V)=>V.score-B.score),D=z.length>1&&z.every(B=>B.score===z[0]?.score),H=E.get(b.path),W=D?H?.or:H?.and,X=[...new Set(W??[])].filter(B=>N.has(B)),J=new Map,Z=new Map;z.forEach((B,V)=>{J.set(B.id,V+1),Z.set(B.id,B)});let Y=new Map;X.forEach((B,V)=>{Y.set(B,V+1)});let U=re("fusion",()=>{let B=new Set([...J.keys(),...Y.keys()]);return Array.from(B).map(te=>{let le=J.get(te),ue=Y.get(te),Ni=le!==void 0?1/(60+le):0,En=ue!==void 0?1/(60+ue):0;return{id:te,rrfScore:Ni+En}}).sort((te,le)=>le.rrfScore-te.rrfScore).slice(0,f)});for(let B of U){let V=Z.get(B.id),te=V?.row??C.rowById.get(B.id);te&&p.push({repoPath:b.path,db:A,row:te,similarity:V?.score??.5,rrfScore:B.rrfScore})}}let T=p.sort((b,A)=>A.rrfScore-b.rrfScore||A.similarity-b.similarity).slice(r,r+u),x=T.length>0?re("map_community",()=>cc(a,o)):new Map,I=[];for(let b of T){let{db:A,repoPath:C,row:O}=b;xt.hydratedRows++;let N="";i.includeSource!==!1&&(xt.sourceReads++,N=Gn(C,O.filePath,O.startLine,O.endLine,500));let j=k(C,O.filePath),z=A.query(`
444
+ SELECT DISTINCT callerSymbol FROM "references"
445
+ WHERE calleeSymbol = ? AND callerSymbol IS NOT NULL AND callerSymbol != ?
446
+ AND (calleeFile = ? OR calleeFile IS NULL)
447
+ `);xt.callerQueries++;let D=z.all(O.name,O.name,O.filePath).map(H=>H.callerSymbol);z.finalize(),I.push({identity:be(C,O),symbol:O.name,kind:O.kind,filePath:j,similarity:Math.round(b.similarity*1e3)/1e3,rrfScore:b.rrfScore,source:N,belongsToCommunity:x.get(j)||"core-module",directCallers:D})}let M=F;return{results:I,total:M,offset:r,limit:u,hasMore:r+u<M,retrieval:{route:_==="vector-only"?["embeddings"]:["lexical","bounded-graph","embeddings"],embeddingsUsed:!0}}},async query(e,n,s,i,o,r,c,a={},l={},u={}){if(e==="lsp_diagnostics"||e==="lsp_definitions"||e==="lsp_declarations"||e==="lsp_implementations")return await Da(e,n,P.resolve(s));let f=await It(s),m=await Promise.all(f.map(async S=>({path:S,db:await Ge(S)}))),d=P.resolve(s),y=Xe(d),g=m.find(S=>S.path===s||S.path===d)??m[0],h=g.db;if(o!==void 0&&(!Number.isFinite(o)||!Number.isInteger(o)||o<1))throw new Error("knodin query: limit must be a positive integer");for(let[S,E]of[["minLines",u.minLines],["minComplexity",u.minComplexity]])if(E!==void 0&&(!Number.isFinite(E)||!Number.isInteger(E)||E<0))throw new Error(`knodin query: ${S} must be a non-negative integer`);if(u.topN!==void 0&&(!Number.isInteger(u.topN)||u.topN<1))throw new Error("knodin query: topN must be a positive integer");if(u.sort&&!["relevance","name","size","degree","complexity"].includes(u.sort))throw new Error("knodin query: invalid sort");let w={large_functions:["relevance","name","size","complexity"],large_files:["relevance","name","size"],flows:["relevance","name","size"],flow_of:["relevance","name"],traverse:["relevance","name"],feature_path:["relevance","name"],community:["relevance","name","size"]};if(u.sort&&!w[e]?.includes(u.sort))throw new Error(`knodin query ${e}: sort=${u.sort} is unsupported`);if(u.minComplexity!==void 0&&e!=="large_functions")throw new Error(`knodin query ${e}: minComplexity is unsupported`);if((u.minLines!==void 0||u.kinds?.length||u.path)&&!["large_functions","large_files","architecture_overview"].includes(e))throw new Error(`knodin query ${e}: large-code filters are unsupported`);if(u.direction&&e!=="traverse")throw new Error(`knodin query ${e}: direction is unsupported`);if(u.direction&&!["upstream","downstream","both"].includes(u.direction))throw new Error("knodin query traverse: invalid direction");if(u.includeDataFlow!==void 0&&e!=="traverse")throw new Error(`knodin query ${e}: includeDataFlow is unsupported`);if(u.flowVariable!==void 0&&e!=="flow_analysis")throw new Error(`knodin query ${e}: flowVariable is unsupported`);if(u.architectureFacets?.length&&e!=="architecture_overview")throw new Error(`knodin query ${e}: architectureFacets is unsupported`);if(u.architectureFacets?.some(S=>!["packages","layers","boundaries","hotspots","entryPoints","languages"].includes(S)))throw new Error("knodin query architecture_overview: invalid architectureFacets");if(u.relationKinds?.length&&!["flows","flow_of","traverse","feature_path","community"].includes(e))throw new Error(`knodin query ${e}: relationKinds is unsupported`);if(u.detailLevel&&!["community","flow_of","traverse","feature_path","architecture_overview"].includes(e))throw new Error(`knodin query ${e}: detailLevel is unsupported`);let k=Math.min(u.topN??o??100,1e3),_=new Set(["callers_of","callees_of","structural_implementations_of","tests_for","shortest_path","rename_preview","traverse","feature_path","flow_analysis",...l.mode!=="file"?["impact"]:[]]),R;if(n&&_.has(e)){let S=To(h,g.path,n,a);if(S.ambiguity)return{pattern:e,target:n,...i?{to:i}:{},count:0,results:[],...e==="shortest_path"?{path:[]}:{},ambiguity:S.ambiguity};R=S.selected}let v=(S,E={})=>{for(let $ of S){if($.identity||!$.symbol||!$.file)continue;let p=h.query("SELECT * FROM symbols WHERE name = ? AND filePath = ? LIMIT 1").get($.symbol,$.file);p&&($.identity=be(g.path,p))}return{pattern:e,target:n,...i?{to:i}:{},count:S.length,results:S.slice(0,k),...S.length>k?{hasMore:!0}:{},...E}};switch(e){case"api_contract_mismatches":{let S=T=>{try{let x=JSON.parse(T);return Array.isArray(x)&&x.every(I=>typeof I=="string")?x:[]}catch{return[]}},E=m.flatMap(T=>T.db.query("SELECT * FROM api_contracts ORDER BY filePath, line").all().map(x=>({...x,repoPath:T.path,filePath:y(T.path,x.filePath),middleware:S(x.middleware),responseFields:S(x.responseFields),declaredResponseFields:S(x.declaredResponseFields),accessedFields:S(x.accessedFields)}))),$=E.filter(T=>T.kind==="endpoint"),p=E.filter(T=>T.kind==="client"),F=[];for(let T of $){if(T.unresolved||!T.handler||!T.responseKnown)continue;let x=new Set(T.responseFields);for(let I of T.declaredResponseFields)x.has(I)||F.push({apiContractMismatch:{kind:"declared_response_field_missing",method:T.method,path:T.path,field:I,endpoint:T.handler,endpointEvidence:{file:T.filePath,line:T.line,source:T.evidence},confidence:T.confidence}})}for(let T of p)if(!(T.unresolved||!T.handler||T.accessedFields.length===0))for(let x of $){if(x.unresolved||!x.handler||!x.responseKnown||x.method!==T.method||!hi(T.path,x.path)||T.origin===null&&T.repoPath!==x.repoPath||T.origin!==null&&T.origin!==x.origin)continue;let I=new Set(x.responseFields);for(let M of T.accessedFields)I.has(M)||F.push({apiContractMismatch:{kind:"client_response_field_missing",method:T.method,path:T.path,field:M,client:T.handler,endpoint:x.handler,clientEvidence:{file:T.filePath,line:T.line,source:T.evidence},endpointEvidence:{file:x.filePath,line:x.line,source:x.evidence},confidence:Math.min(T.confidence,x.confidence)}})}let L=$.map(T=>({method:T.method,path:T.path,...T.handler?{handler:T.handler}:{},middleware:T.middleware,responseFields:T.responseFields,unresolved:T.unresolved===1,file:T.filePath,line:T.line}));return F.unshift({apiContractSummary:{routes:L,clients:p.length,unresolved:E.filter(T=>T.unresolved===1).length}}),v(F)}case"mcp_tools":{let S=[];for(let E of m){let $=S.length,p=n?E.db.query("SELECT * FROM mcp_tools WHERE name = ? ORDER BY filePath, line").all(n):E.db.query("SELECT * FROM mcp_tools ORDER BY name, filePath, line").all();for(let F of p){let L={name:F.name,description:F.description??void 0,schemaSymbol:F.schemaSymbol??void 0,handlerSymbol:F.handlerSymbol??void 0,file:y(E.path,F.filePath),line:F.line,confidence:F.confidence,associationKey:F.associationKey??void 0},T=F.name==="<dynamic>"?void 0:S.slice($).find(x=>x.name===F.name&&x.associationKey&&x.associationKey===L.associationKey&&(!x.handlerSymbol||!x.schemaSymbol));T&&(!L.handlerSymbol||!L.schemaSymbol)?(T.description??=L.description,T.schemaSymbol??=L.schemaSymbol,L.handlerSymbol&&(T.handlerSymbol=L.handlerSymbol,T.file=L.file,T.line=L.line),T.confidence=T.handlerSymbol&&T.schemaSymbol?"exact":"heuristic"):S.push(L)}}return v(S.sort((E,$)=>E.name.localeCompare($.name)).map(E=>({mcpTool:E})))}case"callers_of":case"callees_of":{let S=R?.name??n,E=g.path,$=R?.filePath??null;for(let T of R?[]:m){let x=T.db.query("SELECT filePath FROM symbols WHERE name = ? LIMIT 1"),I=x.get(n);if(x.finalize(),I&&(E=T.path,$=I.filePath,T.path===g.path))break}let p=e==="callers_of"?Vn(m,E,S,1,new Set,$,R?.identity??null):gi(m,E,S,1,new Set,$,R?.identity??null),F=new Set,L=[];for(let T of p){let x=y(T.repoPath||E,T.filePath),I=`${T.symbol}|${x}`;if(F.has(I))continue;F.add(I);let M=(T.repoPath?m.find(b=>b.path===T.repoPath):g)?.db.query("SELECT * FROM symbols WHERE name = ? AND filePath = ? LIMIT 1").get(T.symbol,T.filePath);L.push({symbol:T.symbol,file:x,line:T.lineNumber,kind:T.kind??"call",...M?{identity:be(T.repoPath||E,M)}:{}})}return v(L)}case"imports_of":{let S=h.query("SELECT DISTINCT toFile, kind FROM dependencies WHERE fromFile = ?"),E=S.all(n).map($=>({file:$.toFile,kind:$.kind}));return S.finalize(),v(E)}case"importers_of":{let S=h.query("SELECT DISTINCT fromFile, kind FROM dependencies WHERE toFile = ?"),E=S.all(n).map($=>({file:$.fromFile,kind:$.kind}));return S.finalize(),v(E)}case"import_cycles":{let S=h.query("SELECT DISTINCT fromFile, toFile FROM dependencies WHERE kind IN ('import', 'lsif_import') ORDER BY fromFile, toFile").all(),E=new Map,$=new Set;for(let b of S){$.add(b.fromFile),$.add(b.toFile);let A=E.get(b.fromFile)??[];A.push(b.toFile),E.set(b.fromFile,A)}for(let b of E.values())b.sort();let p=[],F=k+1,L=Math.min(Math.max(k*1e3,1e4),1e6),T=0,x=!1;for(let b of[...$].sort()){if(p.length>=F||x)break;let A=[b],C=new Set(A),O=[{node:b,nextIndex:0}];for(;O.length&&p.length<F&&!x;){let N=O[O.length-1],j=E.get(N.node)??[];if(N.nextIndex>=j.length){O.pop();let D=A.pop();D!==b&&C.delete(D??"");continue}let z=j[N.nextIndex++];if(T++,T>L){x=!0;break}if(z===b){p.push([...A,b]);continue}z<b||C.has(z)||(C.add(z),A.push(z),O.push({node:z,nextIndex:0}))}}let I=p.length>k||x,M=p.slice(0,k).map(b=>({file:b[0],kind:"import_cycle",cycle:b}));return v(M,{...I?{truncated:!0}:{},importCyclePolicy:{typeOnlyImports:"included"}})}case"inheritors_of":{let S=h.query(`SELECT DISTINCT callerSymbol, callerFile, kind, line FROM "references" WHERE calleeSymbol = ? AND kind IN ('extends', 'implements') AND callerSymbol IS NOT NULL`),E=S.all(R?.name??n).map($=>({symbol:$.callerSymbol,file:$.callerFile,kind:$.kind,line:$.line}));return S.finalize(),v(E)}case"structural_implementations_of":{let S=h.query(`SELECT DISTINCT callerSymbol, callerFile, kind, line FROM "references" WHERE calleeSymbol = ? AND calleeFile = ? AND kind = 'structural_implements' AND callerSymbol IS NOT NULL`),E=S.all(R?.name??n,R?.filePath??"").map($=>({symbol:$.callerSymbol,file:$.callerFile,kind:$.kind,line:$.line}));return S.finalize(),v(E)}case"tests_for":{let S=g.path,E=R?.filePath??null;for(let L of R?[]:m){let T=L.db.query("SELECT filePath FROM symbols WHERE name = ? LIMIT 1"),x=T.get(n);if(T.finalize(),x&&(S=L.path,E=x.filePath,L.path===g.path))break}let $=Vn(m,S,n,1,new Set,E,R?.identity??null),p=new Set,F=[];for(let L of $){let T=y(L.repoPath||S,L.filePath);if(!Et(T))continue;let x=`${L.symbol}|${T}`;p.has(x)||(p.add(x),F.push({symbol:L.symbol,file:T,line:L.lineNumber}))}return v(F)}case"rename_preview":{let S=n,E=[],$=h.query("SELECT * FROM symbols WHERE name = ?"),p=R?[R]:$.all(S);$.finalize();for(let x of p)E.push({identity:be(g.path,x),symbol:S,file:x.filePath,line:x.startLine,kind:"definition"});let F=new Set(p.map(x=>x.filePath)),L=F.size===1?[...F][0]:null,T;if(L){let x=h.query('SELECT callerFile, line FROM "references" WHERE calleeSymbol = ? AND calleeFile = ? AND (? IS NULL OR calleeIdentity = ?)');T=x.all(S,L,R?.identity??null,R?.identity??null),x.finalize()}else{let x=h.query('SELECT callerFile, line FROM "references" WHERE calleeSymbol = ?');T=x.all(S),x.finalize()}for(let x of T)E.push({symbol:S,file:x.callerFile,line:x.line,kind:"reference"});if(L){let x=h.query("SELECT DISTINCT fromFile FROM dependencies WHERE toFile = ?"),I=x.all(L).map(A=>A.fromFile);x.finalize();let M=new Set(E.map(A=>`${A.file}|${A.line}`)),b=new Set([...I,...E.map(A=>A.file)]);for(let A of b)if(A)for(let C of uh(P.resolve(s,A),S)){let O=`${A}|${C}`;M.has(O)||(M.add(O),E.push({symbol:S,file:A,line:C,kind:"import"}))}}return v(E)}case"impact":{let S=l.mode??"symbol",E=l.direction??"both",$=Math.min(Math.max(r??3,1),6),p=l.includeTests??!0,F=new Set(l.relationKinds??[]),L=Math.min(Math.max(l.minConfidence??0,0),1),T=j=>/(^|\/)(test|tests|__tests__)(\/|$)|\.(test|spec)\.[^.]+$/i.test(j),x=(j,z,D)=>(p||!T(D))&&(F.size===0||F.has(j))&&z>=L,I=j=>Math.round((j.confidence??1)*(j.calleeFile===j.callerFile?.9:1)*100)/100,M=(j,z,D)=>{if(l.includeDataFlow)try{let H=q.readFileSync(P.join(d,j),"utf8").split(`
448
+ `)[z-1];if(!H)return;let W=D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),X=H.match(new RegExp(`\\b${W}\\s*\\(([^)]*)\\)`));return X?{kind:"call-arguments",arguments:X[1].split(",").map(J=>J.trim()).filter(Boolean),evidence:H.trim().slice(0,240),grounding:"source-line",heuristic:!0}:void 0}catch{return}},b=async(j,z)=>{let D=new Set(j.map(Z=>`${Z.symbol??""}|${Z.file??""}`));R&&D.add(`${R.name}|${R.filePath}`);let H=qn(h,d).filter(Z=>Z.steps.some(Y=>D.has(`${Y.symbol}|${Y.file}`))).map(Z=>Z.entrySymbol),W=await this.map(s,"standard"),X=new Set(j.map(Z=>Z.file??""));if(R&&X.add(R.filePath),S==="file")for(let Z of n.split(",").map(Y=>Y.trim()))X.add(Z);let J=W.communities.filter(Z=>Z.files?.some(Y=>X.has(Y))).map(Z=>Z.name);return v(j,{impact:{mode:S,direction:z,maxDepth:$,heuristic:!0,summary:`${j.length} heuristic ${z} ${S}-level result${j.length===1?"":"s"} within ${$} hop${$===1?"":"s"}`,affectedFlows:[...new Set(H)],affectedCommunities:[...new Set(J)]}})};if(S==="file"){let j=n.split(",").map(X=>X.trim()).filter(Boolean),z=[];for(let X of j){let J=h.query("SELECT name FROM symbols WHERE filePath = ?");for(let Z of J.all(X))z.push({name:Z.name,file:X});J.finalize()}let D=new Set,H=[],W=h.query('SELECT DISTINCT callerSymbol, callerFile, line, kind, confidence FROM "references" WHERE calleeSymbol = ? AND calleeFile = ? AND callerSymbol IS NOT NULL');for(let X of z)for(let J of W.all(X.name,X.file)){if(j.includes(J.callerFile))continue;let Z=`${J.callerSymbol}|${J.callerFile}`;D.has(Z)||(D.add(Z),x(J.kind,J.confidence,J.callerFile)&&H.push({symbol:J.callerSymbol,file:J.callerFile,line:J.line,depth:1,impactEdge:{from:J.callerSymbol,fromFile:J.callerFile,to:X.name,toFile:X.file,kind:J.kind,confidence:J.confidence,line:J.line}}))}return W.finalize(),b(H,"upstream")}if(!R)return b([],E);let A=[{name:R.name,file:R.filePath,depth:0}],C=new Set,O=new Set([`${R.name}|${R.filePath}`]),N=[];for(;A.length>0;){let j=A.shift();if(!j)break;if(j.depth>=$)continue;let z=[];if(j.traversal==="upstream"||!j.traversal&&E!=="downstream"){let D=h.query('SELECT * FROM "references" WHERE calleeSymbol = ? AND calleeFile = ?').all(j.name,j.file);z.push(...D.map(H=>({...H,traversal:"upstream"})))}if(j.traversal==="downstream"||!j.traversal&&E!=="upstream"){let D=h.query('SELECT * FROM "references" WHERE callerSymbol = ? AND callerFile = ?').all(j.name,j.file);z.push(...D.map(H=>({...H,traversal:"downstream"})))}for(let D of z){let H=D.traversal==="upstream"?{name:D.callerSymbol??"",file:D.callerFile}:{name:D.calleeSymbol,file:D.calleeFile??""},W=I(D);if(!H.name||!H.file||!x(D.kind,W,H.file))continue;let X=`${H.name}|${H.file}`,J=`${D.traversal}|${X}`;if(C.has(J))continue;C.add(J);let Z=j.depth+1;if(A.push({...H,depth:Z,traversal:D.traversal}),O.has(X))continue;O.add(X);let Y=M(D.callerFile,D.line,D.calleeSymbol);N.push({symbol:H.name,file:H.file,depth:Z,line:D.line,kind:D.kind,impactEdge:{from:D.callerSymbol??D.callerFile,fromFile:D.callerFile,to:D.calleeSymbol,toFile:D.calleeFile??j.file,kind:D.kind,confidence:W,line:D.line,...Y?{dataFlow:Y}:{}}})}}return b(N,E)}case"file_summary":return $o(`${g.path}\0${e}\0${n}\0${k}`,()=>v(ai(h,n,g.path)));case"batch_outline":return $o(`${g.path}\0${e}\0${n}\0${k}`,()=>{let S=h.query("SELECT DISTINCT filePath FROM symbols ORDER BY filePath").all().map(({filePath:$})=>$).filter($=>!n||$.includes(n)),E=[];for(let $ of S){for(let p of ai(h,$,g.path)){if(E.length>=k)break;E.push(p)}if(E.length>=k)break}return v(E,{hasMore:S.length>0&&E.length>=k?!0:void 0})});case"project_overview":return $o(`${g.path}\0${e}\0${n}\0${k}`,()=>{let S=h.query("SELECT filePath FROM index_state ORDER BY filePath").all().map(({filePath:$})=>$).filter($=>!n||$.includes(n)),E=new Map;for(let $ of S){let p=$.includes("/")?$.split("/",1)[0]:".",F=E.get(p)??{fileCount:0,sizeBytes:0};F.fileCount+=1;try{F.sizeBytes+=q.statSync(P.join(g.path,$)).size}catch{}E.set(p,F)}return v([...E].sort(([$],[p])=>$.localeCompare(p)).slice(0,k).map(([$,p])=>({symbol:$,file:$,kind:"directory",...p})),{hasMore:E.size>k?!0:void 0})});case"large_functions":{let S=u.minLines??50,E=h.query("SELECT name, kind, filePath, startLine, (endLine - startLine + 1) AS lines FROM symbols WHERE kind IN ('function', 'class', 'method') AND (endLine - startLine + 1) >= ? ORDER BY lines DESC"),$=E.all(S);E.finalize();let p=u.path??n;p&&($=$.filter(L=>L.filePath.includes(p))),u.kinds?.length&&($=$.filter(L=>u.kinds?.includes(L.kind)));let F=$.map(L=>{let x=1+(Gn(g.path,L.filePath,L.startLine,L.startLine+L.lines-1).match(/\b(?:if|for|while|case|catch)\b|&&|\|\||\?/g)??[]).length;return{symbol:L.name,kind:L.kind,file:L.filePath,line:L.startLine,lines:L.lines,complexity:x}}).filter(L=>L.complexity>=(u.minComplexity??0));return u.sort==="name"?F.sort((L,T)=>L.symbol.localeCompare(T.symbol)):u.sort==="complexity"?F.sort((L,T)=>T.complexity-L.complexity||L.symbol.localeCompare(T.symbol)):F.sort((L,T)=>T.lines-L.lines||L.symbol.localeCompare(T.symbol)),v(F)}case"large_files":{let S=u.minLines??200,E=h.query("SELECT filePath, MAX(endLine) AS lines FROM symbols GROUP BY filePath HAVING lines >= ? ORDER BY lines DESC"),$=E.all(S);E.finalize();let p=u.path??n;return p&&($=$.filter(F=>F.filePath.includes(p))),u.kinds?.length&&!u.kinds.includes("file")&&($=[]),u.sort==="name"&&$.sort((F,L)=>F.filePath.localeCompare(L.filePath)),v($.map(F=>({symbol:F.filePath,kind:"file",file:F.filePath,line:1,lines:F.lines})))}case"dead_code":{let S=new Set(h.query('SELECT DISTINCT calleeSymbol FROM "references"').all().map(b=>b.calleeSymbol)),E=new Set(["main","default","handler","setup","run","constructor","render","toString"]),$=/^__.+__$/,p=new Map;for(let b of h.query("SELECT DISTINCT fromFile, toFile FROM dependencies").all()){let A=p.get(b.toFile)??[];A.push(b.fromFile),p.set(b.toFile,A)}let F=new Map,L=b=>{if(F.has(b))return F.get(b)??null;let A=null;try{A=q.readFileSync(P.join(s,b),"utf-8")}catch{}return F.set(b,A),A},T=(b,A)=>{let C=L(b);if(!C)return!1;let O=A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\bexport\\s+(?:default\\s+)?(?:function|class|const|let|var|type|interface|enum)\\s+${O}\\b`).test(C)||new RegExp(`\\bexport\\s*\\{[^}]*\\b${O}\\b[^}]*\\}`).test(C)},x=(b,A,C)=>{let O=L(b);if(!O)return!0;let N=!1;for(let j of O.matchAll(/(?:import|export)\s+(?:type\s+)?([\s\S]*?)\s+from\s+["']([^"']+)["']/g)){if(Xn(b,j[2],s)!==A)continue;N=!0;let z=j[1].trim();if(z.includes("*"))return!0;let D=z.match(/\{([^}]*)\}/)?.[1];if(!D)return!0;for(let H of D.split(","))if(H.trim().split(/\s+as\s+/)[0]?.trim()===C)return!0}return!N},I=h.query("SELECT name, kind, filePath, startLine FROM symbols WHERE kind IN ('function', 'class', 'method')"),M=I.all();return I.finalize(),M=M.filter(b=>{if(b.kind==="variable"||b.name.length<=3||E.has(b.name)||$.test(b.name)||S.has(b.name)||Et(b.filePath))return!1;if(T(b.filePath,b.name)){let A=p.get(b.filePath)??[];if(!A.length||A.some(C=>x(C,b.filePath,b.name)))return!1}return!0}),n&&(M=M.filter(b=>b.filePath.includes(n))),v(M.map(b=>({symbol:b.name,kind:b.kind,file:b.filePath,line:b.startLine,heuristic:!0,sourceEvidence:"No statically resolved references; runtime dispatch, reflection, aliases, and indirect exports remain unresolved.",drillDown:{operation:"query",pattern:"callers_of",symbol:b.name,file:b.filePath,limit:25}})))}case"shortest_path":{if(!i)return v([],{path:[]});let S={identity:a.toIdentity,file:a.toFile,kind:a.toKind},E=To(h,g.path,i,S);if(E.ambiguity)return v([],{path:[],ambiguity:E.ambiguity});if(R&&E.selected){let x=h.query(`SELECT callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL AND kind = 'call'`).all(),I=(z,D,H)=>`${z}\0${D}\0${H??""}`,M=I(R.name,R.filePath,R.identity),b=I(E.selected.name,E.selected.filePath,E.selected.identity),A=new Map;for(let z of x){let D=I(z.callerSymbol,z.callerFile,z.callerIdentity),H=A.get(D)??[];H.push(I(z.calleeSymbol,z.calleeFile,z.calleeIdentity)),A.set(D,H)}let C=new Map([[M,null]]),O=[M];for(;O.length&&!C.has(b);){let z=O.shift();for(let D of A.get(z)??[])C.has(D)||(C.set(D,z),O.push(D))}if(!C.has(b))return v([],{path:[],pathDetails:[]});let N=[];for(let z=b;z;z=C.get(z)??null)N.unshift(z);let j=N.map(z=>{let[D,H,W]=z.split("\0"),X=h.query("SELECT * FROM symbols WHERE name = ? AND filePath = ? AND identity = ?").get(D,H,W);return{symbol:D,file:H,...X?{identity:be(g.path,X),kind:X.kind,line:X.startLine}:{}}});return v([],{path:j.map(z=>z.symbol),pathDetails:j})}let $=qp(h),p=new Map([[n,null]]),F=[n],L=n===i;for(;F.length>0&&!L;){let x=F.shift();for(let I of $.get(x)??[])if(!p.has(I)){if(p.set(I,x),I===i){L=!0;break}F.push(I)}}if(!p.has(i))return v([],{path:[]});let T=[];for(let x=i;x!==null;x=p.get(x)??null)T.unshift(x);return v(T.map(x=>({symbol:x})),{path:T})}case"flows":{if(u.relationKinds?.length&&!u.relationKinds.includes("call"))return v([]);let E=qn(h,d).slice().sort(($,p)=>p.criticality-$.criticality||p.nodeCount-$.nodeCount||$.entrySymbol.localeCompare(p.entrySymbol)).map($=>({symbol:$.entrySymbol,file:$.entryFile,kind:"flow",lines:$.nodeCount,depth:$.depth,criticality:$.criticality}));return u.sort==="name"?E.sort(($,p)=>($.symbol??"").localeCompare(p.symbol??"")):u.sort==="size"&&E.sort(($,p)=>(p.lines??0)-($.lines??0)),v(E)}case"flow_of":{if(u.relationKinds?.length&&!u.relationKinds.includes("call"))return v([]);let E=qn(h,d).find(p=>p.entrySymbol===n);if(!E)return v([]);let $=E.steps.map(p=>({symbol:p.symbol,...u.detailLevel==="minimal"?{}:{file:p.file,line:p.line},depth:p.depth}));return u.sort==="name"&&$.sort((p,F)=>(p.symbol??"").localeCompare(F.symbol??"")),v($)}case"stats":{let S=await t.map(s,"standard"),E={repos:0,symbols:0,references:0,dependencies:0,embeddings:0,files:0,orphanedEmbeddings:0,flows:0,communities:S.communities.length,hubs:S.hubs.length,bridges:S.bridges.length},$=[];for(let p of m){let F=p.db,L=H=>F.query(H).get()?.count??0,T=L("SELECT COUNT(*) AS count FROM symbols"),x=L('SELECT COUNT(*) AS count FROM "references"'),I=L("SELECT COUNT(*) AS count FROM dependencies"),M=L("SELECT COUNT(*) AS count FROM symbol_embeddings"),b=L("SELECT COUNT(*) AS count FROM index_state"),A=L(`SELECT COUNT(*) AS count FROM symbol_embeddings WHERE ${Dn}`),C=F.query("PRAGMA user_version").get()?.user_version??0,O=Te(F,"lastIndexedHead")??"",N={};for(let H of F.query("SELECT kind, COUNT(*) AS count FROM symbols GROUP BY kind").all())N[H.kind]=H.count;let j={},z=dn();for(let H of F.query("SELECT filePath, COUNT(*) AS count FROM symbols GROUP BY filePath").all()){let W=await z(H.filePath);j[W]=(j[W]??0)+H.count}let D=qn(F,p.path).length;$.push({stats:{repo:p.path,symbols:T,references:x,dependencies:I,embeddings:M,files:b,orphanedEmbeddings:A,flows:D,schemaVersion:C,head:O,byKind:N,byLanguage:j}}),E.repos+=1,E.symbols+=T,E.references+=x,E.dependencies+=I,E.embeddings+=M,E.files+=b,E.orphanedEmbeddings+=A,E.flows+=D}return v($,{totals:E})}case"traverse":{let S=Math.min(Math.max(r??3,1),6);if(R){let E=u.direction??"both",$=Nm(d,h),p=vt(R.name,R.filePath),F=new Map([[p,0]]),L=[],T=[p],x=!1;for(let A=1;A<=S&&T.length&&!x;A++){let C=[];for(let O of T)for(let N of $.adjacency.get(O)??[]){let j=N>0?"downstream":"upstream";if(E==="upstream"&&j!=="upstream"||E==="downstream"&&j!=="downstream")continue;let z=$.edges[Math.abs(N)-1];if(u.relationKinds?.length&&!u.relationKinds.includes(z.kind))continue;let D={node:j==="downstream"?vt(z.calleeSymbol,z.calleeFile):vt(z.callerSymbol,z.callerFile),ref:z,direction:j};if(!F.has(D.node)){if(F.size>=k){x=!0;break}F.set(D.node,A),L.push({from:O,to:D.node,hop:D}),C.push(D.node)}}T=C}let I=A=>{let[C,O]=A.split("\0");return{name:C,file:O}},M=[...F].map(([A,C])=>{let{name:O,file:N}=I(A),j=$.definitions.get(A);return{symbol:O,...u.detailLevel==="minimal"?{}:{file:N},depth:C,...j?{identity:be(g.path,j),kind:j.kind,line:j.startLine}:{}}});u.sort==="name"&&M.sort((A,C)=>A.symbol.localeCompare(C.symbol));let b=async A=>{if(!(!u.includeDataFlow||A.kind!=="call"))try{let C=P.join(d,A.callerFile),O=q.readFileSync(C,"utf8"),N=await Kn(C);if(!N)return;let j=new we;j.setLanguage(N);let z=j.parse(O),D,H=X=>{if(!(D||X.startPosition.row+1>A.line||X.endPosition.row+1<A.line)){if(X.type==="call_expression"||X.type==="call"){let J=X.childForFieldName("function"),Z=J?.childForFieldName("property")?.text??J?.text;if(Z===A.calleeSymbol||Z?.endsWith(`.${A.calleeSymbol}`)){D=X;return}}for(let J of X.namedChildren)H(J)}};H(z.rootNode);let W=D?.childForFieldName("arguments");return!D||!W?void 0:{kind:"call-arguments",arguments:W.namedChildren.map(X=>X.text),evidence:D.text.slice(0,240),grounding:"tree-sitter",heuristic:!0}}catch{return}};return v(M,{edges:await Promise.all(L.map(async A=>{let C=await b(A.hop.ref);return{from:I(A.from).name,to:I(A.to).name,fromFile:I(A.from).file,toFile:I(A.to).file,kind:A.hop.ref.kind,direction:A.hop.direction,provenance:A.hop.ref.confidence===null||A.hop.ref.confidence>=1?"EXTRACTED":"INFERRED",confidence:A.hop.ref.confidence??1,line:A.hop.ref.line,...C?{dataFlow:C}:{}}})),...x?{truncated:!0}:{}})}return v([],{edges:[]})}case"feature_path":{let S=Math.min(Math.max(r??3,1),6),$={strategy:"dfs",maxDepth:S,maxNodes:k,cycleGuarded:!0,limitations:["Source-graph walk only; it is not a runtime execution trace.","Dynamic dispatch, reflection, and unresolved references are omitted.","Cycles are guarded by resolved symbol identity and are not repeated."]};if(!R)return v([],{edges:[],featurePath:$});let p=h.query('SELECT callerSymbol, callerFile, calleeSymbol, calleeFile, kind, line, confidence FROM "references" WHERE callerSymbol IS NOT NULL AND calleeFile IS NOT NULL').all().filter(O=>!u.relationKinds?.length||u.relationKinds.includes(O.kind)),F=(O,N)=>`${O}\0${N}`,L=O=>{let[N,j]=O.split("\0");return{name:N,file:j}},T=new Map;for(let O of p){let N=F(O.callerSymbol,O.callerFile);T.set(N,[...T.get(N)??[],O])}for(let O of T.values())O.sort((N,j)=>N.line-j.line||N.calleeSymbol.localeCompare(j.calleeSymbol)||N.calleeFile.localeCompare(j.calleeFile)||N.kind.localeCompare(j.kind));let x=F(R.name,R.filePath),I=new Map([[x,0]]),M=[],b=!1,A=(O,N)=>{if(!b){if(N>=S){(T.get(O)??[]).some(j=>!I.has(F(j.calleeSymbol,j.calleeFile)))&&(b=!0);return}for(let j of T.get(O)??[]){let z=F(j.calleeSymbol,j.calleeFile);if(!I.has(z)){if(I.size>=k){b=!0;return}if(I.set(z,N+1),M.push({from:O,to:z,ref:j}),A(z,N+1),b)return}}}};A(x,0);let C=[...I].map(([O,N])=>{let{name:j,file:z}=L(O),D=h.query("SELECT * FROM symbols WHERE name = ? AND filePath = ? LIMIT 1").get(j,z);return{symbol:j,...u.detailLevel==="minimal"?{}:{file:z},depth:N,...D?{identity:be(g.path,D),kind:D.kind,line:D.startLine}:{}}});return u.sort==="name"&&(C=C.sort((O,N)=>O.symbol.localeCompare(N.symbol))),v(C,{edges:M.map(O=>({from:L(O.from).name,to:L(O.to).name,fromFile:L(O.from).file,toFile:L(O.to).file,kind:O.ref.kind,direction:"downstream",provenance:O.ref.confidence===null||O.ref.confidence>=1?"EXTRACTED":"INFERRED",confidence:O.ref.confidence??1,line:O.ref.line})),featurePath:$,...b?{truncated:!0}:{}})}case"flow_analysis":{if(!R)return v([]);let S=P.extname(R.filePath).toLowerCase(),E=[".ts",".tsx"].includes(S)?"typescript":[".js",".jsx",".mjs",".cjs"].includes(S)?"javascript":void 0;if(!E)return v([]);let F=q.readFileSync(P.join(d,R.filePath),"utf8").split(/\r?\n/).slice(R.startLine-1,R.endLine),L=[],T=u.flowVariable,x=new Set,I=(A,C,O,N)=>{T&&C!==T||L.length>=k||L.push({symbol:R.name,file:R.filePath,flowAnalysis:{kind:A,variable:C,line:R.startLine+O,source:N.trim().slice(0,240),grounding:"source",heuristic:!0}})},M=F[0]??"",b=M.match(/\(([^)]*)\)/)?.[1]??"";for(let A of b.split(",")){let C=A.trim().match(/^([A-Za-z_$][\w$]*)/)?.[1];C&&(x.add(C),I("definition",C,0,M))}for(let[A,C]of F.entries()){let O=C.trim();if(!O||O.startsWith("//"))continue;let N=O.match(/^(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/);N&&(x.add(N[1]),I("definition",N[1],A,C));let j=/^(?:if|while|for|switch)\s*\((.*)\)/.exec(O)?.[1],z=new Set;for(let D of O.matchAll(/\b([A-Za-z_$][\w$]*)\b/g))z.add(D[1]);for(let D of z)x.has(D)&&(["const","let","var","return","if","while","for","switch","true","false","null","undefined"].includes(D)||N?.[1]===D&&!O.slice((N.index??0)+N[0].length).match(new RegExp(`\\b${D}\\b`))||(j?.match(new RegExp(`\\b${D}\\b`))?I("control",D,A,C):(!N||N[1]!==D)&&I("use",D,A,C)))}return v(L,{flowAnalysis:{mode:"on-demand-source",language:E,symbol:R.name,...T?{variable:T}:{},limitations:["No persisted PDG or cross-function propagation.","Source-text facts are heuristic; aliases, destructuring, closures, dynamic properties, and runtime control flow are unresolved."]},...L.length>=k?{truncated:!0}:{}})}case"knowledge_gaps":{let S=Math.min(Math.max(o??15,1),1e3),E=await t.map(s,"standard"),$=await wc(m,E,d),p={};$.thinCommunities.length>S&&(p.thinCommunities=!0),$.singleFileCommunities.length>S&&(p.singleFileCommunities=!0),$.isolatedNodes.length>S&&(p.isolatedNodes=!0),$.untestedHotspots.length>S&&(p.untestedHotspots=!0);let F={thinCommunities:$.thinCommunities.slice(0,S),singleFileCommunities:$.singleFileCommunities.slice(0,S),isolatedNodes:$.isolatedNodes.slice(0,S),untestedHotspots:$.untestedHotspots.slice(0,S),...Object.keys(p).length?{truncated:p}:{}};return v([{knowledgeGaps:F}])}case"surprising_connections":{let S=await t.map(s,"standard"),E=await Sc(m,S,d),$=o!=null?k:15,p=E.map(F=>({symbol:F.from,file:F.fromFile,kind:F.kind,surprise:F}));return v(p.slice(0,$),{count:E.length})}case"suggested_questions":{let S=await t.map(s,"standard"),E=await wc(m,S,d,{skipIsolatedNodes:!0}),$=await Sc(m,S,d),p=[];for(let x of E.untestedHotspots){let I=x.kind==="hub"?`a hub with ${x.degree??0} reference${x.degree===1?"":"s"}`:"a bridge on many call paths";p.push({symbol:x.symbol,file:x.file,question:`${x.symbol} is ${I} and has no test coverage \u2014 worth a test before the next change touches it?`})}let F={"cross-community":"a community boundary","cross-language":"a language boundary","peripheral-to-hub":"from the periphery into a hub","cross-test-boundary":"the test boundary","unusual-edge-kind":"an unusual edge kind"};for(let x of $){let I=x.reasons.map(M=>F[M]??M).join(" and ")||"a boundary";p.push({symbol:x.from,file:x.fromFile,question:`${x.from} \u2192 ${x.to} crosses ${I} \u2014 is this coupling intentional?`})}let L=new Set;for(let x of E.thinCommunities){L.add(x.name);let I=x.files[0]??x.name;p.push({file:x.files[0],question:`${x.name} (${I}) has only ${x.size} member${x.size===1?"":"s"} \u2014 is it mis-clustered, or genuinely this small?`})}for(let x of E.singleFileCommunities)L.has(x.name)||(L.add(x.name),p.push({file:x.file,question:`${x.name} lives entirely in ${x.file} (${x.size} symbol${x.size===1?"":"s"}) \u2014 should it be split, or is single-file right here?`}));let T=o!=null?k:10;return v(p.slice(0,T),{count:p.length})}case"community":{let S=await t.map(s,"standard",{relationKinds:u.relationKinds}),E=S.communities.find(F=>F.name.toLowerCase()===n.toLowerCase()),$=[];E?$=[E]:n?$=S.communities.filter(F=>F.name.toLowerCase().includes(n.toLowerCase())):$=S.communities,u.sort==="name"?$.sort((F,L)=>F.name.localeCompare(L.name)):$.sort((F,L)=>L.size-F.size||F.name.localeCompare(L.name));let p=$.map(F=>({community:u.detailLevel==="minimal"?{name:F.name,size:F.size,cohesion:F.cohesion}:F}));return v(p)}case"federated_repos":{let S=f.map(E=>({symbol:E,kind:"repo"}));return v(S)}case"architecture_overview":{let S=Vt("architecture_facets"),E=c!=="standard",$=u.path?.replace(/^\.\//,"").replace(/\/$/,""),p=["packages","layers","boundaries","hotspots","entryPoints","languages"],F=u.architectureFacets?.length?u.architectureFacets:p,L=JSON.stringify([d,f,E?"minimal":"standard",$??"",k,F]),T=Ro.get(L);if(T&&T.generation===ne)return S(),v([{architectureOverview:structuredClone(T.result)}]);let x=$m(m,d),I=U=>!$||U===$||U.startsWith(`${$}/`),M=x.symbols.filter(U=>I(U.filePath)),b=x.references.filter(U=>I(U.callerFile)&&I(U.calleeFile??"")),A=(U,B)=>x.communityBySymbolFile.get(vt(U,B)),C=new Map;for(let U of M){let B=A(U.name,U.filePath);if(!B)continue;let V=C.get(B);V?V.push(U):C.set(B,[U])}let O=new Map;for(let U of b){let B=A(U.callerSymbol??U.callerFile,U.callerFile),V=A(U.calleeSymbol,U.calleeFile??"");B&&B===V&&O.set(B,(O.get(B)??0)+1)}let N=x.communities.filter(U=>(U.files??[]).some(I)).map(U=>{let B=(U.files??[]).filter(I),V=C.get(U.name)??[],te=O.get(U.name)??0;return{name:U.name,size:V.length,cohesion:V.length>1?te/(V.length*(V.length-1)):0,files:B}}),j=new Set(N.map(U=>U.name)),z=[],D=new Map,H=E?void 0:Vt("architecture_edge_materialization");for(let U of b){let B=A(U.callerSymbol??U.callerFile,U.callerFile),V=A(U.calleeSymbol,U.calleeFile??"");if(!B||!V||B===V||!j.has(B)||!j.has(V))continue;E||z.push({from:U.callerSymbol??U.callerFile,fromCommunity:B,to:U.calleeSymbol,toCommunity:V,kind:U.kind});let te=B<V?[B,V]:[V,B],le=te.join("\0"),ue=D.get(le)??{communities:te,kinds:new Map,count:0};ue.count+=1,ue.kinds.set(U.kind,(ue.kinds.get(U.kind)??0)+1),D.set(le,ue)}H?.();let W=[...D.values()].reduce((U,B)=>U+B.count,0)/Math.max(D.size,1),X=[...D.values()].map(U=>({communities:U.communities,count:U.count,dominantKind:[...U.kinds].sort((B,V)=>V[1]-B[1]||B[0].localeCompare(V[0]))[0]?.[0]??"unknown",...U.count>W*2?{highCoupling:!0}:{}})).sort((U,B)=>B.count-U.count),J=U=>F.includes(U),Z={selected:[...F],...$?{pathScope:$}:{}};if(J("packages")){let U=new Map;for(let B of M){let V=P.posix.dirname(B.filePath);U.set(V,(U.get(V)??0)+1)}Z.packages=[...U].map(([B,V])=>({name:P.posix.basename(B),path:B,symbols:V})).sort((B,V)=>V.symbols-B.symbols||B.path.localeCompare(V.path)).slice(0,k)}if(J("layers")){let U=new Map,B=V=>V.split("/").find(te=>/^(api|ui|web|domain|service|data|db|infra|infrastructure|test|tests)$/i.test(te))?.toLowerCase()??"core";for(let V of M){let te=B(V.filePath),le=U.get(te)??{symbols:0,files:new Set};le.symbols+=1,le.files.add(V.filePath),U.set(te,le)}Z.layers=[...U].map(([V,te])=>({name:V,symbols:te.symbols,files:[...te.files].sort()})).sort((V,te)=>te.symbols-V.symbols||V.name.localeCompare(te.name)).slice(0,k)}if(J("boundaries")){let U=new Map;for(let B of b){let V=P.posix.dirname(B.callerFile),te=P.posix.dirname(B.calleeFile??"");if(V===te)continue;let le=`${V}\0${te}\0${B.kind}`,ue=U.get(le)??{from:V,to:te,kind:B.kind,count:0};ue.count+=1,U.set(le,ue)}Z.boundaries=[...U.values()].sort((B,V)=>V.count-B.count||B.from.localeCompare(V.from)).slice(0,k)}if(J("hotspots")){let U=_m(x,m,d);Z.hotspots=[...U.hubs.filter(B=>I(B.filePath)).map(B=>({symbol:B.symbol,file:B.filePath,role:"hub",score:B.degree})),...U.bridges.filter(B=>I(B.filePath)).map(B=>({symbol:B.symbol,file:B.filePath,role:"bridge",score:B.betweenness}))].sort((B,V)=>V.score-B.score).slice(0,k)}if(J("entryPoints")){let U=new Set(b.map(B=>`${B.calleeSymbol}\0${B.calleeFile}`));Z.entryPoints=M.filter(B=>!U.has(`${B.name}\0${B.filePath}`)||/(^|\/)(main|index|server|cli)\.[^.]+$/i.test(B.filePath)).map(B=>({symbol:B.name,file:B.filePath,kind:B.kind})).slice(0,k)}if(J("languages")){let U=new Map,B=dn();for(let V of M){let te=await B(V.filePath);U.set(te,(U.get(te)??0)+1)}Z.languages=[...U].map(([V,te])=>({name:V,symbols:te})).sort((V,te)=>te.symbols-V.symbols||V.name.localeCompare(te.name)).slice(0,k)}let Y={detailLevel:E?"minimal":"standard",communities:N,couplingPairs:X,facets:Z,...E?{}:{edges:z}};return ft(Ro,L,{generation:ne,result:structuredClone(Y)},Ac),S(),v([{architectureOverview:Y}])}case"triggers_of":{let S=h.query(`SELECT callerSymbol, calleeSymbol, callerFile, calleeFile, line FROM "references" WHERE kind = 'schedules' AND (callerSymbol = ? OR calleeSymbol = ?)`),E=S.all(n,n).map($=>{let p=$.callerSymbol===n;return{symbol:p?$.calleeSymbol:$.callerSymbol,file:(p?$.calleeFile:$.callerFile)??void 0,line:$.line,kind:"schedules"}});return S.finalize(),v(E)}case"publishers_of":case"listeners_of":case"consumers_of":{let S=e==="publishers_of"?"publishes":e==="listeners_of"?"listens":"consumes",E=h.query('SELECT DISTINCT callerSymbol, callerFile, line FROM "references" WHERE kind = ? AND calleeSymbol = ? AND callerSymbol IS NOT NULL'),$=E.all(S,n).map(p=>({symbol:p.callerSymbol,file:p.callerFile,line:p.line,kind:S}));return E.finalize(),v($)}case"handlers_of":{let S=h.query('SELECT DISTINCT calleeSymbol, calleeFile, line FROM "references" WHERE callerSymbol = ? AND calleeSymbol IS NOT NULL'),E=S.all(n).map($=>({symbol:$.calleeSymbol,file:$.calleeFile??void 0,line:$.line}));return S.finalize(),v(E)}case"endpoints_for":{let S=h.query(`SELECT DISTINCT r.callerSymbol AS callerSymbol, r.line AS line FROM "references" r WHERE r.calleeSymbol = ? AND r.callerSymbol IN (SELECT name FROM symbols WHERE kind = 'endpoint')`),E=S.all(n).map($=>({symbol:$.callerSymbol,kind:"endpoint",line:$.line}));return S.finalize(),v(E)}case"children_of":{let S=ai(h,n,g.path);if(S.length>0)return v(S);let E=h.query("SELECT filePath, startLine, endLine FROM symbols WHERE name = ? AND kind = 'class' ORDER BY (endLine - startLine) DESC LIMIT 1"),$=E.get(n);if(E.finalize(),!$)return v([]);let p=h.query("SELECT name, kind, startLine, endLine FROM symbols WHERE filePath = ? AND startLine >= ? AND endLine <= ? ORDER BY startLine"),F=p.all($.filePath,$.startLine,$.endLine).filter(L=>!(L.name===n&&L.startLine===$.startLine)).map(L=>({symbol:L.name,kind:L.kind,line:L.startLine,file:$.filePath}));return p.finalize(),v(F)}default:throw new Error(`unknown query pattern: ${String(e)}`)}},async rename(e,n,s,i=!1,o=!0,r={}){let c=await Ge(s),a=P.resolve(s),l=To(c,a,e,r);if(l.ambiguity)return{oldName:e,newName:n,applied:!1,refused:l.ambiguity.message,ambiguity:l.ambiguity,preview:{pattern:"rename_preview",target:e,to:n,count:0,results:[],ambiguity:l.ambiguity},diff:"",filesChanged:[]};let u=await this.query("rename_preview",e,s,n,void 0,void 0,void 0,r),f={...l.selected?{identity:be(a,l.selected)}:{},oldName:e,newName:n,applied:!1,preview:u,diff:"",filesChanged:[]},m=[...new Set(u.results.filter(L=>L.kind==="definition"&&L.file).map(L=>L.file))];if(m.length>1)return f.refused=`ambiguous: "${e}" has ${m.length} distinct definition files (${m.join(", ")}); refusing to rename in v1`,f;let d=[...new Set(u.results.filter(L=>L.file).map(L=>L.file))];if(d.length===0)return f.refused=`no edit sites: "${e}" was not found in the index`,f;let y;try{y=q.realpathSync(a)}catch{y=a}let g=L=>{let T=P.resolve(a,L),x=P.relative(a,T);if(x.startsWith("..")||P.isAbsolute(x))return!1;try{let I=q.realpathSync(T),M=P.relative(y,I);if(M.startsWith("..")||P.isAbsolute(M))return!1}catch{return!1}return!0};for(let L of d)if(!g(L))return f.refused=`path escape: edit-site file "${L}" resolves outside the repo root`,f;let h=c.query("SELECT filePath FROM symbols WHERE name = ? AND filePath = ? LIMIT 1");for(let L of d)if(h.get(n,L))return h.finalize(),f.refused=`naming collision: "${n}" already exists as a symbol in "${L}"; refusing to rename (shadowing risk)`,f;h.finalize();let w=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),k=new RegExp(`\\b${w}\\b`,"g"),_=new Map,R=new Map;for(let L of u.results){if(!L.file||typeof L.line!="number")continue;let T=_.get(L.file);if(T||(T=new Set,_.set(L.file,T)),T.add(L.line),L.kind==="import"){let x=R.get(L.file);x||(x=new Set,R.set(L.file,x)),x.add(L.line)}}let v=[],S=new Map,E=new Map,$=[];for(let[L,T]of _){let x=P.resolve(a,L),I;try{I=q.readFileSync(x)}catch{continue}let M=R.get(L),b=I.toString("utf-8").split(`
449
+ `),A=[],C=!1;for(let O of[...T].sort((N,j)=>N-j)){let N=O-1;if(N<0||N>=b.length)continue;let j=b[N];k.lastIndex=0;let z=M?.has(O)?lh(j,k,n):j.replace(k,n);z!==j&&(b[N]=z,C=!0,A.push(`@@ -${O},1 +${O},1 @@`,`-${j}`,`+${z}`))}C&&(S.set(L,b.join(`
450
+ `)),E.set(L,I),$.push(L),v.push(`--- a/${L}`,`+++ b/${L}`,...A))}if(f.diff=v.join(`
451
+ `),!i)return f;let p=o?rh(a):null,F=null;if(!o)f.verification={ran:!1,skipped:"typecheck verification disabled"};else if(!p)f.verification={ran:!1,skipped:"no tsconfig.json \u2014 not a TS/JS repo; skipping typecheck verification"};else{let L=xc(p,a);L.available?F=L:f.verification={ran:!1,command:p,skipped:"typechecker could not be run; skipping typecheck verification"}}for(let L of $){let T=P.resolve(a,L),x=S.get(L),I=P.join(P.dirname(T),`.${P.basename(T)}.knodin-rename-${process.pid}-${Date.now()}.tmp`);q.writeFileSync(I,x,"utf-8"),q.renameSync(I,T)}if(F&&p){let L=xc(p,a),T=L.available?ch(F.diagnostics,L.diagnostics):[];if(T.length>0){for(let x of $){let I=E.get(x);I&&q.writeFileSync(P.resolve(a,x),I)}return f.refused=`type errors introduced: renaming "${e}" -> "${n}" added ${T.length} typecheck error(s); rolled back ${$.length} file(s)`,f.verification={ran:!0,command:p,baselineErrors:F.diagnostics.length,postApplyErrors:L.diagnostics.length,newDiagnostics:T,rolledBack:!0},f}f.verification=L.available?{ran:!0,command:p,baselineErrors:F.diagnostics.length,postApplyErrors:L.diagnostics.length,newDiagnostics:[],rolledBack:!1}:{ran:!1,command:p,skipped:"typechecker could not be run after the edit; rename left applied"}}return $.length>0&&await this.index(s,$),f.applied=!0,f.filesChanged=$,f},async close(){for(let e of li.values())await e.close();li.clear();for(let e of ui.values())e.closed=!0,e.timer&&(clearTimeout(e.timer),e.timer=null),await e.drain(),e.pending.size>0&&await e.drain();ui.clear();for(let e of Mt.values())e.close();Mt.clear(),No.clear(),Dt.clear(),zn.clear(),Bn.clear(),Wn.clear(),Co.clear(),Ro.clear(),Io.clear(),cn.clear(),Mo.clear(),Po.clear(),Qa(),Do.clear(),jo.clear(),zo.clear(),Ho.clear(),Uo.clear()}};return dh(t)}import Kc from"node:fs";import Xc from"node:path";function fh(){return process.platform==="win32"?[process.env.ProgramFiles,process.env["ProgramFiles(x86)"]].filter(e=>!!e).flatMap(e=>[Xc.join(e,"Git","cmd","git.exe"),Xc.join(e,"Git","bin","git.exe")]):["/usr/bin/git","/usr/local/bin/git","/opt/homebrew/bin/git"]}function Ze(){let t=fh().find(e=>{try{return Kc.accessSync(e,Kc.constants.X_OK),!0}catch{return!1}});if(!t)throw new Error("Git was not found in a trusted installation directory; install Git in a standard system location");return t}import{spawnSync as Qc}from"node:child_process";import Bt from"node:fs";import Se from"node:path";var mh=[".tsx",".jsx",".java",".cs",".go",".rs",".py",".ts",".js",".mjs",".cjs",".kt",".kts",".swift",".rb",".php",".scala",".c",".cc",".cpp",".h",".hpp"],Qn=4*1024*1024,ph=1024*1024,hh=256*1024,gh=4096,yh=64,bh=16384,wh=128*1024,Sh=10,el=50,Eh=8,kh=25;function bn(t,e,n,s,i){let o=e??n;if(!Number.isInteger(o)||o<s||o>i)throw new Error(`knodin diagnose: ${t} must be an integer from ${s} to ${i}`);return o}function vh(t){let e=t.trim().replaceAll(" "," ");return e.length<=500?e:`${e.slice(0,499)}\u2026`}function xh(t){return!` \r
452
+ "'\`()[]{}<>|=,`.includes(t)}function es(t,e,n){let s=e;for(;s<t.length&&n.includes(t[s]??"");)s++;return s}function Zc(t,e){let n=e;for(;n<t.length;){let s=t.codePointAt(n)??-1;if(s<48||s>57)break;n++}return{value:n===e?null:Number(t.slice(e,n)),next:n}}function Th(t){let e=es(t,0,`"'),`);return e=es(t,e," "),t.startsWith("line ",e)?e+=5:t.startsWith(":line ",e)?e+=6:e=es(t,e,":([]"),es(t,e," [")}function Rh(t,e){let n=t.slice(e,e+48).toLowerCase(),s=Zc(n,Th(n));if(s.value===null)return{line:null,column:null};let i=es(n,s.next,":, ["),o=Zc(n,i);return{line:s.value,column:o.value}}function $h(t,e,n){let s=mh.find(a=>e.startsWith(a,n));if(!s)return null;let i=n+s.length,o=n-1;for(;o>=0&&xh(t[o]??"");)o--;let r=t.slice(o+1,i);if(r.startsWith("file://")&&(r=r.slice(7)),!r||r===s||r.length>gh)return null;let c=Rh(t,i);return{path:r,line:c.line,column:c.column,evidence:vh(t)}}function _h(t,e=el){let n=[],s=new Set;for(let i of t.split(/\r?\n/)){let o=i.slice(0,32768),r=o.toLowerCase();for(let c=0;c<r.length;c++){let a=$h(o,r,c);if(!a)continue;let l=`${a.path}:${a.line??""}:${a.column??""}`;if(!s.has(l)&&(s.add(l),n.push(a),n.length>=e))return n}}return n}function tr(t,e){return Qc(Ze(),["-C",t,"ls-files","--error-unmatch","--",e],{encoding:"utf8",timeout:3e3,maxBuffer:65536}).status===0}function Ah(t){let n=t.replaceAll("\\","/").replace(/^[A-Za-z]:/,"").split("/").filter(Boolean);if(n.includes(".."))return[];let s=[];for(let i=Math.max(0,n.length-yh);i<n.length;i++){let o=n.slice(i).join("/");o&&s.push(o)}return s}function tl(t,e){let n=Bt.realpathSync(t),s=Bt.realpathSync(Se.join(t,e)),i=Se.relative(n,s);return i!==".."&&!i.startsWith(`..${Se.sep}`)&&!Se.isAbsolute(i)}function Jc(t,e){try{return tr(t,e)?tl(t,e)?{file:e}:{reason:"outside-repository"}:{reason:"not-indexed"}}catch{return{reason:"outside-repository"}}}function Fh(t,e){return[...new Set(t.results.map(({filePath:n})=>n).filter(n=>Se.posix.basename(n)===e))].sort((n,s)=>n.localeCompare(s))}async function Lh(t,e,n){let s=Ah(n.path);if(s.length===0)return{reason:"outside-repository"};for(let a of s)if(tr(e,a))return Jc(e,a);let i=Se.posix.basename(s[0]??""),o=i.slice(0,Math.max(1,i.lastIndexOf("."))),r=await t.search(o,e,100,{includeSource:!1,federate:!1}),c=Fh(r,i);return c.length===1&&!r.hasMore?Jc(e,c[0]??""):c.length>1||r.hasMore&&c.length>0?{reason:"ambiguous",candidates:c}:{reason:"not-indexed"}}function Nh(t,e){let n=t.filter(s=>s.symbol&&s.file&&s.line!==void 0&&s.endLine!==void 0);return n.length===0?null:e===null?[...n].sort((s,i)=>(s.line??0)-(i.line??0))[0]??null:[...n].filter(s=>(s.line??0)<=e&&(s.endLine??0)>=e).sort((s,i)=>(s.endLine??0)-(s.line??0)-((i.endLine??0)-(i.line??0))||(i.line??0)-(s.line??0))[0]??null}function er(t,e){return t.results.filter(n=>!!n.symbol).slice(0,e).map(n=>({identity:n.identity??null,symbol:n.symbol??"",file:n.file??null,kind:n.kind??null,line:n.line??null,confidence:n.impactEdge?.confidence??null}))}function Ch(t){let e=t.indexOf("=");return e<0?null:t.slice(e+1).trim().replace(/^["']|["']$/g,"")||null}function Yc(t,e){let n=!1;for(let s of t.split(/\r?\n/)){let i=s.trim();if(i.startsWith("[")&&i.endsWith("]")){n=e.includes(i.slice(1,-1).trim());continue}let o=i.indexOf("=");if(n&&o>=0&&i.slice(0,o).trim()==="name")return Ch(i)}return null}function Oh(t,e){let n=`<${e}>`,s=`</${e}>`,i=t.indexOf(n);if(i<0)return null;let o=t.indexOf(s,i+n.length);return o<0?null:t.slice(i+n.length,o).trim()||null}function Ih(t,e,n){if(t==="npm")try{let s=JSON.parse(n);return typeof s.name=="string"&&s.name?s.name:null}catch{return null}if(t==="python")return Yc(n,["project","tool.poetry"]);if(t==="cargo")return Yc(n,["package"]);if(t==="maven"){let s=n.indexOf("</parent>");return Oh(s>=0?n.slice(s+9):n,"artifactId")}return t==="go"?n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.startsWith("module "))?.slice(7).trim()||null:Se.basename(e,Se.extname(e))}function Mh(t){let e;try{e=Bt.opendirSync(t);for(let n=0;n<1024;n++){let s=e.readSync();if(!s)break;if(s.isFile()&&s.name.toLowerCase().endsWith(".csproj"))return s.name}}catch{return null}finally{e?.closeSync()}return null}function Ph(t){let e=Se.extname(t).toLowerCase();return e===".py"?"python":e===".rs"?"cargo":e===".go"?"go":[".java",".kt",".kts"].includes(e)?"maven":e===".cs"?"dotnet":[".js",".jsx",".ts",".tsx",".mjs",".cjs"].includes(e)?"npm":null}function Dh(t,e,n,s){let i=Se.posix.join(e==="."?"":e,n);try{if(!tr(t,i)||!tl(t,i))return null;let o=Bt.statSync(Se.join(t,i));if(!o.isFile()||o.size>hh)return null;let r=Bt.readFileSync(Se.join(t,i),"utf8");return{name:Ih(s,i,r),manifest:i,kind:s}}catch{return null}}function jh(t,e){let n=Ph(e),s=[["package.json","npm"],["pyproject.toml","python"],["pom.xml","maven"],["Cargo.toml","cargo"],["go.mod","go"]];s.sort((o,r)=>+(r[1]===n)-+(o[1]===n));let i=Se.dirname(e);for(;i!==".."&&!Se.isAbsolute(i);){let o=n==="dotnet"?Mh(Se.join(t,i)):null,r=[...s];o&&r.unshift([o,"dotnet"]);for(let[a,l]of r){let u=Dh(t,i,a,l);if(u)return u}let c=Se.dirname(i);if(c===i)break;i=c}return null}function zh(t,e,n){let s=Qc(Ze(),["-C",t,"log",`-${n}`,"--format=%H%x09%aI%x09%an%x09%s","--",e],{encoding:"utf8",timeout:5e3,maxBuffer:131072});return s.status!==0?[]:s.stdout.trim().split(`
453
+ `).filter(Boolean).map(i=>{let[o="",r="",c="",...a]=i.split(" ");return{commit:o,at:r,author:c,subject:a.join(" ")}})}function Bh(t,e){if(Buffer.byteLength(t)<=e)return t;let n="",s=0;for(let i of t){let o=Buffer.byteLength(i);if(s+o>e)break;n+=i,s+=o}return n}function Hh(t,e,n,s,i){let o=Se.join(t,e),r;try{let m=Bt.statSync(o);if(!m.isFile()||m.size>ph)return{snippet:null,truncated:!0,omittedBytes:0};r=Bt.readFileSync(o,"utf8").split(/\r?\n/)}catch{return{snippet:null,truncated:!0,omittedBytes:0}}let c=Math.max(1,n-s),a=Math.min(r.length,n+s),l=r.slice(c-1,a).map((m,d)=>`${c+d}: ${m.slice(0,2e3)}`).join(`
454
+ `),u=Buffer.byteLength(l);if(i<=0)return{snippet:null,truncated:!0,omittedBytes:u};let f=Bh(l,i);return f?{snippet:{file:e,startLine:c,endLine:a,content:f},truncated:f!==l,omittedBytes:u-Buffer.byteLength(f)}:{snippet:null,truncated:!0,omittedBytes:u}}function Uh(t,e){if([e.artifactId!==void 0,e.text!==void 0].filter(Boolean).length!==1)throw new Error("knodin diagnose requires exactly one of artifactId or text");if(e.artifactId){let i=Ci(t,e.artifactId,{byteBudget:Qn}),o=i.complete||i.range.totalLines<=i.range.endLine?i:Ci(t,e.artifactId,{endLine:i.range.totalLines,byteBudget:Qn});return{kind:"artifact",artifactId:e.artifactId,content:o.content,bytes:o.bytes,complete:o.complete}}let s=$r(t,{text:e.text,lineBudget:1e4,byteBudget:Qn,maxInputBytes:Qn,retain:!1,redactSecrets:!0});return{kind:"text",artifactId:null,content:s.content,bytes:s.output.bytes,complete:s.complete}}async function Wh(t,e,n,s,i){if(!s?.symbol)return{tests:[],upstream:[],downstream:[],omitted:0};let o=s.identity?{identity:s.identity,file:n}:{file:n},r=(f,m)=>t.query(f,s.symbol??"",e,void 0,i,f==="impact"?2:void 0,void 0,o,m),[c,a,l]=await Promise.all([r("tests_for"),r("impact",{direction:"upstream",includeTests:!0}),r("impact",{direction:"downstream",includeTests:!0})]),u={tests:er(c,i),upstream:er(a,i),downstream:er(l,i)};return{...u,omitted:Math.max(0,c.count-u.tests.length)+Math.max(0,a.count-u.upstream.length)+Math.max(0,l.count-u.downstream.length)}}function qh(t){return t?.symbol?{identity:t.identity??null,symbol:t.symbol,kind:t.kind??"unknown",line:t.line??null,endLine:t.endLine??null,signature:t.signature??null,evidenceQuality:t.evidenceQuality??null}:null}async function Gh(t,e,n,s,i){let o=await t.query("file_summary",s,e,void 0,200),r=Nh(o.results,n.line),c=await Wh(t,e,s,r,i.relationLimit),a=n.line??r?.line??1;return{diagnostic:{reference:n,file:s,package:jh(e,s),owner:qh(r),tests:c.tests,upstream:c.upstream,downstream:c.downstream,recentChanges:i.recentCommitLimit>0?zh(e,s,i.recentCommitLimit):[]},source:Hh(e,s,a,i.contextLines,i.remainingContextBytes),omittedRelations:c.omitted}}function Vh(t,e,n,s){let i=["Static graph relationships and recent commits are diagnostic candidates, not runtime-causality proof."];return t||i.push(`Only the first ${Qn} analyzed bytes were available.`),e===0&&i.push("No repository-contained code-path reference was detected in the analyzed output."),n&&i.push("Source snippets were omitted or shortened to honor the context byte budget."),s!=="fresh"&&i.push(`Graph freshness is ${s}; refresh before strong claims.`),i}function Kh(t,e,n,s,i){return t===0?"unresolved":e>0||!n||s||i!=="fresh"?"partial":"resolved"}async function oE(t,e,n){let s=bn("maxDiagnostics",n.maxDiagnostics,Sh,1,el),i=bn("diagnosticOffset",n.diagnosticOffset,0,0,1e6),o=bn("contextLines",n.contextLines,2,0,10),r=bn("contextByteBudget",n.contextByteBudget,bh,256,wh),c=bn("relationLimit",n.relationLimit,Eh,1,kh),a=bn("recentCommitLimit",n.recentCommitLimit,3,0,10),l=Uh(e,n),u=_h(l.content,Number.MAX_SAFE_INTEGER),f=u.slice(i,i+s),m=Math.max(0,u.length-i-f.length),d=[],y=[],g=[],h=0,w=!1,k=0,_=0;for(let p of f){let F=await Lh(t,e,p);if(!F.file){y.push({reference:p,reason:F.reason??"not-indexed",...F.candidates?{candidates:F.candidates}:{}});continue}let L=await Gh(t,e,p,F.file,{relationLimit:c,recentCommitLimit:a,contextLines:o,remainingContextBytes:r-h});L.source.snippet&&(g.push(L.source.snippet),h+=Buffer.byteLength(L.source.snippet.content)),w||=L.source.truncated,k+=L.omittedRelations,_+=L.source.omittedBytes,d.push(L.diagnostic)}let R=await t.status(e,{audit:"cached"}),v=Kh(d.length,y.length+m,l.complete,w,R.freshness.state),S=[];m>0&&S.push("diagnostic-item-budget"),k>0&&S.push("relation-item-budget"),w&&S.push("context-byte-budget"),l.complete||S.push("input-byte-budget");let E=[...d.length===0?["no-safe-source-reference"]:[],...y.length>0?["unresolved-source-reference"]:[],...S,...R.freshness.state!=="fresh"?[`freshness-${R.freshness.state}`]:[]],$=d.reduce((p,F)=>p+F.tests.length+F.upstream.length+F.downstream.length,0);return{schemaVersion:1,status:v,input:{kind:l.kind,artifactId:l.artifactId,bytes:l.bytes,complete:l.complete},diagnostics:d,unresolved:y,contextBundle:{byteBudget:r,usedBytes:h,truncated:w,snippets:g},freshness:R.freshness,confidence:{level:d.length===0?"refused":v==="resolved"?"exact":"qualified",reasons:E},omissions:{diagnostics:m,relations:k,contextBytes:_,reasons:S,continuation:m>0&&l.artifactId?{artifactId:l.artifactId,nextDiagnostic:i+f.length}:null},telemetry:{commandRerun:!1,referencesDetected:u.length,resolved:d.length,unresolved:y.length,caps:{diagnostics:s,relationsPerKind:c,contextBytes:r},returned:{diagnostics:d.length,relations:$,contextBytes:h}},limitations:Vh(l.complete,f.length,w,R.freshness.state)}}function Xh(t){if(Object.values(t.orphaned).some(s=>s>0))return!0;let e=new Set(t.lifecycle?.issues??[]),n=["indexed file no longer exists: ","indexed file is no longer eligible: ","indexed snapshot differs from disk: "];return t.missing.records.some(s=>!e.has(s)&&!n.some(i=>s.startsWith(i)))}function Zh(t){return t.freshness?.state==="queued"?"queued":t.freshness?.state==="indexing"||t.status==="indexing"?"indexing":t.schemaVersion===0?t.coverage.sourceFiles===0?"empty-repository":"not-initialized":t.coverage.sourceFiles===0?"empty-repository":t.coverage.indexedFiles===0?"empty-index":t.status==="repair-needed"&&Xh(t)?"repair-needed":null}async function aE(t,e){try{let n=await e(t),s=Zh(n);return s?{available:!1,status:"unavailable",state:s,graph:n,remediation:n.repairSteps}:{available:!0,state:n.lifecycle&&n.lifecycle.status!=="healthy"?"lifecycle-degraded":"healthy",graph:n}}catch(n){return{available:!1,status:"unavailable",state:"unknown",remediation:["Run `knodin doctor` and `knodin status --deep`."],error:n instanceof Error?n.message:String(n)}}}function Jh(t){return Array.isArray(t.results)?t.results.length===0:typeof t.count=="number"?t.count===0:typeof t.changedFileCount=="number"?t.changedFileCount===0:!!(typeof t.summary=="string"&&/\bnot found\b/i.test(t.summary)||typeof t.refused=="string"&&/\b(?:not found|no edit sites|no matches)\b/i.test(t.refused))}function cE(t,e="healthy",n){if(t==null)return{status:"no-match",result:t??null,...n?{freshness:n}:{},availability:{state:"no-match",graphState:e,outcome:"no-match"}};if(Array.isArray(t))return{status:t.length===0?"no-match":"ok",results:t,...n?{freshness:n}:{},availability:{state:t.length===0?"no-match":e,graphState:e,outcome:t.length===0?"no-match":"matches"}};if(typeof t!="object")return{result:t,...n?{freshness:n}:{},availability:{state:e,outcome:"complete"}};let s=t,i=Jh(s)&&s.ambiguity===void 0;return{...s,...n?{freshness:n}:{},...i&&s.status===void 0?{status:"no-match"}:{},availability:{state:i?"no-match":e,graphState:e,outcome:i?"no-match":"matches"}}}import sl from"node:child_process";import Yh from"node:crypto";import Ht from"node:fs";import Pe from"node:path";function nr(t,e){return sl.execFileSync("git",e,{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","pipe"]})}function yi(t){try{return Ht.realpathSync(t)}catch{return Pe.resolve(t)}}function il(t){let e=nr(t,["rev-parse","--path-format=absolute","--git-common-dir"]).trim();return Pe.resolve(t,e)}function ol(t){return Pe.join(il(t),"knodin","worktrees.json")}function nl(){return{schemaVersion:1,graphState:"per-worktree",entries:[]}}function sr(t){try{let e=JSON.parse(Ht.readFileSync(ol(t),"utf-8"));return e.schemaVersion===1&&Array.isArray(e.entries)?e:nl()}catch{return nl()}}function rl(t,e){let n=ol(t);Ht.mkdirSync(Pe.dirname(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;Ht.writeFileSync(s,`${JSON.stringify(e,null,2)}
455
+ `,{mode:384}),Ht.renameSync(s,n)}function ir(t,e,n){let s=n;try{s=Pe.resolve(e,nr(e,["rev-parse","--path-format=absolute","--git-dir"]).trim())}catch{}return Yh.createHash("sha256").update(`${il(t)}\0${s}`).digest("hex").slice(0,24)}function bi(t){let e=nr(t,["worktree","list","--porcelain","-z"]).split("\0"),n=[];for(let s of e){if(s.startsWith("worktree ")){n.push({path:Pe.resolve(s.slice(9)),classification:n.length===0?"main":"linked",head:null,branch:null,locked:!1,prunable:null});continue}let i=n.at(-1);i&&(s.startsWith("HEAD ")?i.head=s.slice(5):s.startsWith("branch ")?i.branch=s.slice(7).replace(/^refs\/heads\//,""):s==="detached"?i.branch=null:s.startsWith("locked")?i.locked=!0:s.startsWith("prunable ")&&(i.prunable=s.slice(9)))}return n}function al(t){let e=Pe.resolve(t),n=bi(e).find(c=>yi(c.path)===yi(e));if(!n)throw new Error(`knodin worktrees: ${e} is not a registered Git worktree`);let s=sr(e),i=new Date().toISOString(),o=ir(e,n.path,n.classification),r=s.entries.find(c=>c.identity===o);r?(r.path=n.path,r.lastSeenAt=i,delete r.removedAt):s.entries.push({identity:o,path:n.path,classification:n.classification,registeredAt:i,lastSeenAt:i}),s.entries.sort((c,a)=>c.path.localeCompare(a.path)),rl(e,s)}async function pE(t,e){let n=Pe.resolve(t),s=bi(n),i=sr(n),o=new Set(s.map(c=>c.path)),r=[];for(let c of s){let a=ir(n,c.path,c.classification),l=i.entries.some(m=>m.identity===a),u=Ht.existsSync(Pe.join(c.path,".knodin","db.sqlite")),f=null;if(u)try{f=(await e(c.path)).lastIndexedHead||null}catch{f=null}r.push({...c,identity:a,registered:l,graphInitialized:u,indexedHead:f,freshness:f===null||c.head===null?"unknown":f===c.head?"fresh":"stale",removedAt:null})}for(let c of i.entries)o.has(c.path)||r.push({identity:c.identity,path:c.path,classification:c.classification,head:null,branch:null,locked:!1,prunable:"registered worktree is absent from Git's worktree inventory",registered:!0,graphInitialized:Ht.existsSync(Pe.join(c.path,".knodin","db.sqlite")),indexedHead:null,freshness:"removed",removedAt:c.removedAt??null});return r.sort((c,a)=>c.path.localeCompare(a.path)),{schemaVersion:1,graphState:"per-worktree",worktrees:r}}function Qh(t){let e=Pe.resolve(t),n=bi(e),s=sr(e),i=new Date().toISOString(),o=new Set,r=[],c=[];for(let l of n){let u=ir(e,l.path,l.classification);o.add(u);let f=s.entries.find(m=>m.identity===u);f?(f.removedAt&&c.push(l.path),f.path=l.path,f.lastSeenAt=i,delete f.removedAt):(s.entries.push({identity:u,path:l.path,classification:l.classification,registeredAt:i,lastSeenAt:i}),r.push(l.path))}let a=[];for(let l of s.entries)!o.has(l.identity)&&!l.removedAt&&(l.removedAt=i,a.push(l.path));return s.entries.sort((l,u)=>l.path.localeCompare(u.path)),rl(e,s),{schemaVersion:1,added:r,restored:c,removed:a}}function hE(t,e,n){let s=Pe.resolve(t),i=Pe.resolve(e),o=bi(s).find(r=>yi(r.path)===yi(i));if(!o)throw new Error(`knodin worktrees remove: ${i} is not a registered Git worktree`);if(o.classification==="main")throw new Error("knodin worktrees remove: refusing to remove the main worktree");return n?{schemaVersion:1,target:i,dryRun:!0,removed:!1}:(sl.execFileSync("git",["worktree","remove",i],{cwd:s,stdio:["ignore","pipe","pipe"]}),Qh(s),{schemaVersion:1,target:i,dryRun:!1,removed:!0})}import hl from"node:child_process";import eg from"node:crypto";import K from"node:fs";import G from"node:path";var Si="KNODIN MANAGED HOOK",Ut=["post-commit","post-checkout","post-merge","post-rewrite"],tg=1048576,gl="last-refresh-failure",ar=class extends Error{indexResult;constructor(e){let n=e.verification.missing.files[0]??e.verification.missing.records[0],s=n?` First issue: ${n}.`:"";super(`knodin init: lifecycle hooks were installed, but ${e.verification.issueCount.toLocaleString()} graph issue(s) remain.${s} Run \`knodin repair\`.`),this.name="InitializationHealthError",this.indexResult=e}};function ng(t){if(typeof t!="object"||t===null)return!1;let e=t,n=e.verification;return Array.isArray(e.indexed)&&Array.isArray(e.unchanged)&&typeof n=="object"&&n!==null&&typeof n.status=="string"&&typeof n.issueCount=="number"&&Array.isArray(n.missing?.files)&&Array.isArray(n.missing?.records)}function Re(t,e,n="utf-8"){return hl.execFileSync("git",e,{cwd:t,encoding:n,stdio:["ignore","pipe","ignore"]})}var Ei=2048,or=8*1024*1024;function rr(t){try{let e=K.readdirSync(t,{withFileTypes:!0});if(e.length>Ei)throw new Error(`${t}: configure mutation audit exceeds ${Ei} managed entries`);return e}catch(e){if(e.code==="ENOENT")return[];throw e}}function sg(t){let e=Re(t,["rev-parse","--path-format=absolute","--git-common-dir"]).trim(),n=G.isAbsolute(e)?e:G.resolve(t,e),s=Re(t,["rev-parse","--path-format=absolute","--git-path","info/exclude"]).trim(),i=G.isAbsolute(s)?s:G.resolve(t,s),o=cr(t),r=new Map,c=d=>{let y=G.resolve(d.absolute);r.has(y)||r.set(y,{...d,absolute:y})};for(let d of["AGENTS.md","GEMINI.md",".mcp.json",".codex",".codex/config.toml",".gemini",".gemini/settings.json",".agents",".agents/mcp_config.json",".gitignore",".claude",".claude/hooks",".claude/hooks/nudge.sh",".claude/settings.example.json",".knodin",".knodin/integration.json",".knodin/indexer.log",".knodin/indexer.log.1","lefthook-local.yml","lefthook-local.yaml",".lefthook-local.yml",".lefthook-local.yaml",".config/lefthook-local.yml",".config/lefthook-local.yaml"])c({absolute:G.join(t,d),label:d});for(let d of[".knodin/hooks",".knodin/hooks/background-index.sh",".knodin/hooks/manager-dispatch.sh",".knodin/hooks/events",".knodin/hooks/last-refresh-event",".knodin/hooks/last-refresh-failure",".knodin/hooks/refresh.lock",".knodin/hooks/refresh.lock/pid"])c({absolute:G.join(t,d),label:d});for(let d of rr(G.join(t,".knodin","hooks","events")))c({absolute:G.join(t,".knodin","hooks","events",d.name),label:`.knodin/hooks/events/${d.name}`});c({absolute:G.join(n,"config"),label:".git/config"}),c({absolute:i,label:".git/info/exclude"}),c({absolute:G.join(n,"knodin"),label:".git/knodin"}),c({absolute:G.join(n,"knodin","worktrees.json"),label:".git/knodin/worktrees.json"});let a=G.join(n,"hooks"),l=G.join(n,"knodin-hooks");c({absolute:a,label:".git/hooks"}),c({absolute:l,label:".git/knodin-hooks"});let u=G.resolve(o)===G.resolve(a)?".git/hooks":G.resolve(o)===G.resolve(l)?".git/knodin-hooks":"effective-git-hooks";c({absolute:o,label:u});for(let d of[{absolute:a,label:".git/hooks"},{absolute:l,label:".git/knodin-hooks"},{absolute:o,label:u}])for(let y of rr(d.absolute))c({absolute:G.join(d.absolute,y.name),label:`${d.label}/${y.name}`});for(let d of Ut)c({absolute:G.join(o,d),label:`${u}/${d}`}),c({absolute:G.join(o,`${d}.knodin-original`),label:`${u}/${d}.knodin-original`});for(let d of[{absolute:a,label:".git/hooks"},{absolute:l,label:".git/knodin-hooks"}])for(let y of Ut)c({absolute:G.join(d.absolute,y),label:`${d.label}/${y}`}),c({absolute:G.join(d.absolute,`${y}.knodin-original`),label:`${d.label}/${y}.knodin-original`});let f=kl(t),m=f?vl(t,f):null;if(m&&xl(t,m)){let d=G.join(t,m);for(let y of rr(d)){if(!y.isFile()||Ut.includes(y.name))continue;let g=G.join(d,y.name);(K.statSync(g).mode&73)!==0&&c({absolute:G.join(l,y.name),label:`.git/knodin-hooks/${y.name}`})}}if(r.size>Ei)throw new Error(`configure mutation audit exceeds ${Ei} managed paths`);return[...r.values()]}function yl(t,e=!1){try{let n=K.lstatSync(t);if(n.isDirectory())return`directory:${n.mode&511}`;if(n.isSymbolicLink()){let i=K.readlinkSync(t),o=K.realpathSync(t);return`symlink:${n.mode&511}:${i}:${yl(o,e)}`}if(!n.isFile())throw new Error(`${t}: unsupported filesystem entry`);if(n.size>or&&!e)throw new Error(`${t}: configure mutation audit refuses files larger than ${or} bytes`);if(n.size>or)return`oversized-file:${n.mode&511}:${n.size}`;let s=eg.createHash("sha256").update(K.readFileSync(t)).digest("hex");return`file:${n.mode&511}:${n.size}:${s}`}catch(n){if(n.code==="ENOENT")return null;throw n}}function cl(t,e=!1){let n=new Map;for(let s of t){let i=yl(s.absolute,e);i!==null&&n.set(s.label,i)}return n}function ig(t,e){return[...new Set([...t.keys(),...e.keys()])].sort().flatMap(n=>{let s=t.get(n),i=e.get(n);return s===i?[]:[{path:n,action:s===void 0?"created":i===void 0?"removed":"modified"}]})}function ki(t){return`'${t.replaceAll("'","'\\''")}'`}function vi(t,e){let n=e.indexOf("--"),s=n<0?[...e,"-z"]:[...e.slice(0,n),"-z",...e.slice(n)];return Re(t,s,"utf-8").split("\0").filter(Boolean)}function ll(t,e,n){if(!/^[0-9a-fA-F]{40,64}$/.test(e)||!/^[0-9a-fA-F]{40,64}$/.test(n))throw new Error("knodin hook refresh: invalid Git object id");return vi(t,["diff","--name-only",e,n,"--"])}async function TE(t,e,n){let s=G.resolve(t),i=[],o;try{if(e.kind==="commit")i=vi(s,["diff-tree","--root","--no-commit-id","--name-only","-r","HEAD"]);else if(e.kind==="checkout"||e.kind==="merge")i=ll(s,e.before,e.after);else{let c=G.join(s,".knodin","hooks"),a=G.resolve(e.inputPath),l=G.relative(c,a);if(l===""||l===".."||l.startsWith(`..${G.sep}`)||G.isAbsolute(l))throw new Error("knodin hook refresh: rewrite input must be inside .knodin/hooks");let[u,f,m]=await Promise.all([K.promises.realpath(c),K.promises.realpath(a),K.promises.lstat(a)]),d=G.relative(u,f);if(m.isSymbolicLink()||!m.isFile()||d===""||d===".."||d.startsWith(`..${G.sep}`)||G.isAbsolute(d))throw new Error("knodin hook refresh: rewrite input must be a regular file inside .knodin/hooks");o=a;let y=(await K.promises.readFile(a,"utf-8")).split(/\r?\n/).map(g=>g.trim().split(/\s+/)).filter(g=>g.length>=2);for(let[g,h]of y)i.push(...ll(s,g,h))}let r=[...new Set(i.map(c=>c.replaceAll("\\","/")))].filter(Ct).sort();return r.length>0&&await n(s,r),r}finally{o&&await K.promises.rm(o,{force:!0})}}function bl(t){let e=t.map(ki).join(" ");return`#!/bin/sh
456
+ # knodin packaged background refresh. Generated by knodin init.
457
+ set -u
458
+ REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)"
459
+ [ -n "$REPO_ROOT" ] || exit 0
460
+ cd "$REPO_ROOT" || exit 0
461
+ mkdir -p "$REPO_ROOT/.knodin"
462
+ LOCK_DIR="$REPO_ROOT/.knodin/hooks/refresh.lock"
463
+ EVENT_DIR="$REPO_ROOT/.knodin/hooks/events"
464
+ LAST_EVENT_PATH="$REPO_ROOT/.knodin/hooks/last-refresh-event"
465
+ FAILURE_PATH="$REPO_ROOT/.knodin/hooks/${gl}"
466
+ FAILURE_TMP="$FAILURE_PATH.$$"
467
+ mkdir -p "$EVENT_DIR"
468
+ if [ "$#" -gt 0 ]; then
469
+ EVENT_TMP="$EVENT_DIR/$(date +%s).$$.$PPID.compat.tmp"
470
+ EVENT_SEQUENCE="$(date +%s).$$.$PPID"
471
+ EVENT_WORKTREE="$REPO_ROOT"
472
+ EVENT_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
473
+ {
474
+ for EVENT_ARG in "$@"; do
475
+ printf '%s\\n' "$EVENT_ARG"
476
+ done
477
+ printf 'sequence=%s\\nworktree=%s\\nat=%s\\n' "$EVENT_SEQUENCE" "$EVENT_WORKTREE" "$EVENT_AT"
478
+ } > "$EVENT_TMP"
479
+ mv "$EVENT_TMP" "$EVENT_TMP.event"
480
+ fi
481
+ if ! mkdir "$LOCK_DIR" 2>/dev/null; then
482
+ if [ -f "$LOCK_DIR/pid" ]; then
483
+ LOCK_PID="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
484
+ if [ -n "$LOCK_PID" ] && ! kill -0 "$LOCK_PID" 2>/dev/null; then
485
+ rm -rf "$LOCK_DIR"
486
+ mkdir "$LOCK_DIR" 2>/dev/null || exit 0
487
+ else
488
+ exit 0
489
+ fi
490
+ else
491
+ exit 0
492
+ fi
493
+ fi
494
+ printf '%s\\n' "$$" > "$LOCK_DIR/pid"
495
+ trap 'rm -rf "$LOCK_DIR"; rm -f "$FAILURE_TMP"' EXIT HUP INT TERM
496
+ LOG_PATH="$REPO_ROOT/.knodin/indexer.log"
497
+ if [ -f "$LOG_PATH" ]; then
498
+ LOG_BYTES="$(wc -c < "$LOG_PATH" 2>/dev/null | tr -d '[:space:]')"
499
+ case "$LOG_BYTES" in ''|*[!0-9]*) LOG_BYTES=0 ;; esac
500
+ if [ "$LOG_BYTES" -ge ${tg} ]; then
501
+ mv -f "$LOG_PATH" "$LOG_PATH.1"
502
+ fi
503
+ fi
504
+ while :; do
505
+ EVENT="$(find "$EVENT_DIR" -type f -name '*.event' -print 2>/dev/null | LC_ALL=C sort | head -n 1)"
506
+ [ -n "$EVENT" ] || break
507
+ KIND="$(sed -n '1p' "$EVENT")"
508
+ ARG1="$(sed -n '2p' "$EVENT")"
509
+ ARG2="$(sed -n '3p' "$EVENT")"
510
+ if [ "$KIND" = "commit" ]; then
511
+ ${e} --repo "$REPO_ROOT" hook-refresh commit --json >> "$LOG_PATH" 2>&1
512
+ elif [ "$KIND" = "checkout" ] || [ "$KIND" = "merge" ]; then
513
+ ${e} --repo "$REPO_ROOT" hook-refresh "$KIND" "$ARG1" "$ARG2" --json >> "$LOG_PATH" 2>&1
514
+ elif [ "$KIND" = "rewrite" ]; then
515
+ ${e} --repo "$REPO_ROOT" hook-refresh rewrite "$ARG1" --json >> "$LOG_PATH" 2>&1
516
+ else
517
+ printf 'knodin background refresh: invalid queued event %s\\n' "$KIND" >> "$LOG_PATH"
518
+ false
519
+ fi
520
+ STATUS=$?
521
+ if [ "$STATUS" -eq 0 ]; then
522
+ cp "$EVENT" "$LAST_EVENT_PATH"
523
+ rm -f "$EVENT" "$FAILURE_PATH"
524
+ else
525
+ {
526
+ printf 'knodin background refresh failed with exit code %s.\\n' "$STATUS"
527
+ printf 'Pending event retained at %s.\\n' "$EVENT"
528
+ printf 'See .knodin/indexer.log for details.\\n'
529
+ } > "$FAILURE_TMP"
530
+ mv -f "$FAILURE_TMP" "$FAILURE_PATH"
531
+ exit "$STATUS"
532
+ fi
533
+ done
534
+ `}function ul(t){let e=G.join(t,".knodin","hooks","events");try{return K.readdirSync(e).filter(n=>n.endsWith(".event"))}catch{return[]}}function og(t){try{let e=Number(K.readFileSync(G.join(t,".knodin","hooks","refresh.lock","pid"),"utf-8"));return!Number.isInteger(e)||e<=0?!1:(process.kill(e,0),!0)}catch{return!1}}function rg(t,e){if(ul(t).length===0)return{state:"fresh",queuedEvents:0};let s=hl.spawnSync(e,[],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:3e4});if(s.status!==0){let o=s.error?.message||s.stderr.trim()||`exit ${s.status??"unknown"}`;throw new Error(`knodin init: queued lifecycle refresh could not be drained (${o}); run ${e} after resolving .knodin/hooks/last-refresh-failure`)}let i=ul(t);if(i.length===0)return{state:"fresh",queuedEvents:0};if(og(t))return{state:"running",queuedEvents:i.length};if(i.length>0)throw new Error("knodin init: queued lifecycle events remain after refresh; run `knodin wait --fresh`, then retry initialization");return{state:"fresh",queuedEvents:0}}function wl(t,e){let n=e?e.startsWith("repo:")?`"$REPO_ROOT"/${ki(e.slice(5))}`:ki(e):"",s=e?`KNODIN_WRAPPER_ACTIVE=1 ${n} "$@"${t==="post-rewrite"?' < "$REWRITE_INPUT"':""} || ORIGINAL_STATUS=$?`:":",i="";t==="post-commit"&&(i="trigger_knodin commit"),t==="post-checkout"&&(i='[ "${3:-0}" = "1" ] && trigger_knodin checkout "${1:-}" "${2:-}"'),t==="post-merge"&&(i=`BEFORE="$(git rev-parse ORIG_HEAD 2>/dev/null || true)"
535
+ AFTER="$(git rev-parse HEAD 2>/dev/null || true)"
536
+ [ -n "$BEFORE" ] && [ -n "$AFTER" ] && trigger_knodin merge "$BEFORE" "$AFTER"`);let o=e?`KNODIN_WRAPPER_ACTIVE=1 ${n} "$@"
537
+ exit $?`:"exit 0",r=t==="post-rewrite"?`if [ ! -x "$BACKGROUND" ]; then
538
+ ${o}
539
+ fi
540
+ REWRITE_INPUT="$(mktemp "$REPO_ROOT/.knodin/hooks/rewrite-input.XXXXXX")" || exit 0
541
+ cat > "$REWRITE_INPUT"
542
+ `:"";return t==="post-rewrite"&&(i='trigger_knodin rewrite "$REWRITE_INPUT"'),`#!/bin/sh
543
+ # ${Si}: ${t}
544
+ REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)"
545
+ [ -n "$REPO_ROOT" ] || exit 0
546
+ BACKGROUND="$REPO_ROOT/.knodin/hooks/background-index.sh"
547
+ ORIGINAL_STATUS=0
548
+ trigger_knodin() {
549
+ [ -x "$BACKGROUND" ] || return 0
550
+ EVENT_KIND="\${1:-}"
551
+ EVENT_BEFORE="\${2:-}"
552
+ EVENT_AFTER="\${3:-}"
553
+ if [ "$EVENT_KIND" = "commit" ]; then
554
+ EVENT_BEFORE="$(git rev-parse HEAD^ 2>/dev/null || true)"
555
+ EVENT_AFTER="$(git rev-parse HEAD 2>/dev/null || true)"
556
+ set -- commit "$EVENT_BEFORE" "$EVENT_AFTER"
557
+ elif [ "$EVENT_KIND" = "rewrite" ] && [ -f "\${2:-}" ]; then
558
+ EVENT_BEFORE="$(sed -n '1{s/ .*//;p;}' "$2")"
559
+ EVENT_AFTER="$(sed -n '1{s/^[^ ]* //;s/ .*//;p;}' "$2")"
560
+ fi
561
+ EVENT_DIR="$REPO_ROOT/.knodin/hooks/events"
562
+ mkdir -p "$EVENT_DIR" || return 0
563
+ EVENT_TMP="$EVENT_DIR/$(date +%s).$$.$PPID.tmp"
564
+ EVENT_PATH="$EVENT_TMP.event"
565
+ EVENT_SEQUENCE="$(date +%s).$$.$PPID"
566
+ EVENT_WORKTREE="$REPO_ROOT"
567
+ EVENT_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
568
+ {
569
+ for EVENT_ARG in "$@"; do
570
+ printf '%s\\n' "$EVENT_ARG"
571
+ done
572
+ printf 'sequence=%s\\nworktree=%s\\nat=%s\\nbefore=%s\\nafter=%s\\n' \\
573
+ "$EVENT_SEQUENCE" "$EVENT_WORKTREE" "$EVENT_AT" "$EVENT_BEFORE" "$EVENT_AFTER"
574
+ } > "$EVENT_TMP" || return 0
575
+ mv "$EVENT_TMP" "$EVENT_PATH" || return 0
576
+ if [ "\${KNODIN_HOOK_FOREGROUND:-0}" = "1" ]; then
577
+ "$BACKGROUND"
578
+ else
579
+ nohup "$BACKGROUND" >/dev/null 2>&1 &
580
+ fi
581
+ }
582
+ ${r}${s}
583
+ ${i}
584
+ exit "$ORIGINAL_STATUS"
585
+ `}async function Sl(t){if(!K.existsSync(t))return;let e=await K.promises.readFile(t,"utf-8");if(!e.includes("call_lefthook()"))return;let n=e.match(/^call_lefthook run "([^"\r\n]+)" "\$@"$/m);n&&await K.promises.writeFile(t,e.replace(n[0],`call_lefthook run "${n[1]}" --no-auto-install "$@"`),"utf-8")}async function ag(t,e,n=void 0){let s=G.join(t,e),i=n??null;if(n===void 0&&K.existsSync(s)){let r=await K.promises.readFile(s,"utf-8");if(r.startsWith(`#!/bin/sh
586
+ # ${Si}: ${e}
587
+ `))i=r.match(/^# knodin original: (.+)$/m)?.[1]??null;else{let c=`${s}.knodin-original`,a=(await K.promises.stat(s)).mode;await K.promises.copyFile(s,c),await K.promises.rm(s,{force:!0});let l=await K.promises.readFile(c,"utf-8");for(let u=1;;u++){let f=`${c}.${u}`;if(!K.existsSync(f))break;let m=await K.promises.readFile(f,"utf-8");(m===l||m.includes(Si))&&await K.promises.rm(f,{force:!0})}(a&73)!==0&&(i=c)}}i&&await Sl(i);let o=wl(e,i);i&&(o=o.replace(`
588
+ REPO_ROOT=`,`
589
+ # knodin original: ${i}
590
+ REPO_ROOT=`)),await K.promises.writeFile(s,o,{encoding:"utf-8",mode:493}),await K.promises.chmod(s,493)}var El="knodin.originalHooksPath";function cr(t){let e;try{e=Re(t,["rev-parse","--path-format=absolute","--git-path","hooks"]).trim()}catch{e=Re(t,["rev-parse","--git-path","hooks"]).trim()}return G.isAbsolute(e)?e:G.resolve(t,e)}function kl(t){try{return Re(t,["config","--local","--get",El]).trim()||null}catch{try{return Re(t,["config","--local","--get","core.hooksPath"]).trim()||null}catch{return null}}}function vl(t,e){let n=G.isAbsolute(e)?e:G.resolve(t,e),s=G.relative(t,n).replaceAll("\\","/");return!s||s===".."||s.startsWith("../")||G.isAbsolute(s)?null:s}function xl(t,e){try{return vi(t,["ls-files","--",e]).length>0}catch{return!1}}function cg(t){return`#!/bin/sh
591
+ # ${Si}: tracked-hook passthrough
592
+ REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)"
593
+ [ -n "$REPO_ROOT" ] || exit 0
594
+ ORIGINAL="$REPO_ROOT"/${ki(t)}
595
+ [ -x "$ORIGINAL" ] || exit 0
596
+ exec "$ORIGINAL" "$@"
597
+ `}async function lg(t){let e=kl(t),n=e?vl(t,e):null;if(!e||!n||!xl(t,n))return{hooksDir:cr(t),trackedHooksDir:null};let s=Re(t,["rev-parse","--git-common-dir"]).trim(),i=G.isAbsolute(s)?s:G.resolve(t,s),o=G.join(i,"knodin-hooks");await K.promises.mkdir(o,{recursive:!0}),Re(t,["config","--local",El,e]),Re(t,["config","--local","core.hooksPath",o]);let r=G.join(t,n);for(let c of await K.promises.readdir(r,{withFileTypes:!0})){if(!c.isFile()||Ut.includes(c.name))continue;let a=G.join(r,c.name);if(((await K.promises.stat(a)).mode&73)===0)continue;let u=G.join(o,c.name);await K.promises.writeFile(u,cg(`${n}/${c.name}`),{encoding:"utf-8",mode:493}),await K.promises.chmod(u,493)}return{hooksDir:o,trackedHooksDir:n}}var ug=`#!/bin/sh
598
+ # Example Claude Code hook: suggest local graph context for broad manual searches.
599
+ read -r INPUT_PAYLOAD
600
+ case "$INPUT_PAYLOAD" in
601
+ *grep*|*find*|*Glob*|*ReadFile*) REASON="For cold or unfamiliar work, call the connected knodin MCP gateway's context or explain operation before broad traversal; use the CLI only as a fallback." ;;
602
+ *) REASON="Proceeding with tool execution." ;;
603
+ esac
604
+ printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","permissionDecisionReason":"%s"}}\\n' "$REASON"
605
+ `,dg=`{
606
+ "comment": "Template only: opt in to local knodin context nudges.",
607
+ "hooks": {
608
+ "PreToolUse": [{
609
+ "matcher": "Bash|Read|Glob",
610
+ "hooks": [{"type": "command", "command": "./.claude/hooks/nudge.sh", "timeout": 5}]
611
+ }]
612
+ }
613
+ }
614
+ `,wi="<!-- knodin:start -->\n## knodin \u2014 Local Code Intelligence\n\nThis repository is indexed locally by knodin. Start with `knodin status`; if it reports `repair-needed`, follow its repair steps before relying on graph evidence. Use `knodin repair` for graph damage and `knodin init` for displaced lifecycle hooks.\n\n- When the single connected knodin MCP tool is available, use it directly. For cold or unfamiliar work, call its `context` operation before broad Read/Grep/Glob traversal. Use shell commands only as a fallback when the gateway is unavailable.\n- Before a meaningful edit, call the gateway's `query` operation with the `impact` pattern (CLI fallback: `knodin query impact <symbol> --direction upstream`) and report material risk to the user.\n- Use gateway operations `explain`, `review`, and `query` for source-evidenced context. CLI fallbacks are `knodin explain`, `knodin review --scope compare`, and `knodin rename`.\n- Direct reads are appropriate for files just authored in the current session; do not force a graph round trip when the agent already has fresh source context.\n- Run `knodin index <changed-files>` while working when you need immediately fresh graph evidence. Managed Git hooks installed by `knodin init` refresh the graph after commits, checkouts, merges, and rewrites.\n- Keep output truthful: local graph evidence can be stale or ambiguous; say so and repair/reindex instead of claiming certainty.\n\n<!-- knodin:end -->\n";async function lr(t,e){let n=G.resolve(t,e),s=G.relative(t,n);if(s.startsWith("..")||G.isAbsolute(s))throw new Error(`${e}: managed file must stay inside the repository`);let i=t;for(let o of s.split(G.sep)){i=G.join(i,o);try{if((await K.promises.lstat(i)).isSymbolicLink())throw new Error(`${e}: refusing to follow a symbolic link`)}catch(r){if(r.code==="ENOENT")break;throw r}}}async function dl(t,e="AGENTS.md"){await lr(t,e);let n=G.join(t,e),s="",i=!0;try{s=await K.promises.readFile(n,"utf-8")}catch(u){if(u.code!=="ENOENT")throw u;i=!1}let o="<!-- knodin:start -->",r="<!-- knodin:end -->",c=s.indexOf(o),a=s.indexOf(r),l=c>=0&&a>=c?`${s.slice(0,c)}${wi}${s.slice(a+r.length).replace(/^\r?\n/,"")}`:s.length>0?`${s.trimEnd()}
615
+
616
+ ${wi}`:wi;return l===s?null:(await K.promises.writeFile(n,l,"utf-8"),{path:e,action:i?"modified":"created"})}async function fl(t,e="AGENTS.md"){try{return(await K.promises.readFile(G.join(t,e),"utf-8")).includes(wi)}catch{return!1}}function fg(t){let e=t.indexOf("<!-- knodin:start -->"),n=t.indexOf("<!-- knodin:end -->",e);if(e<0||n<e)return null;let s=t.slice(0,e),i=t.slice(n+19);return s.length===0&&/^\r?\n$/.test(i)?"":`${s}${i}`}function Rt(t,e){try{return vi(t,["ls-files","--",e]).length>0}catch{return!1}}async function ml(t,e){let n=[...new Set(e)].filter(d=>!Rt(t,d)).sort();if(n.length===0)return[];let s=Re(t,["rev-parse","--git-path","info/exclude"]).trim(),i=G.isAbsolute(s)?s:G.resolve(t,s),o="";try{o=await K.promises.readFile(i,"utf-8")}catch(d){if(d.code!=="ENOENT")throw d}let r="# knodin:start",c="# knodin:end",a=o.replace(/(?:^|\n)# knodin:start\n[\s\S]*?\n# knodin:end\n?/,`
617
+ `),l=new Set(a.split(/\r?\n/)),u=n.filter(d=>!l.has(d)),f=a&&!a.endsWith(`
618
+ `)?`${a}
619
+ `:a,m=u.length>0?`${r}
620
+ ${u.join(`
621
+ `)}
622
+ ${c}
623
+ `:"";return await K.promises.mkdir(G.dirname(i),{recursive:!0}),await K.promises.writeFile(i,`${f}${m}`,"utf-8"),u}async function pl(t){let e=Re(t,["rev-parse","--git-path","info/exclude"]).trim(),n=G.isAbsolute(e)?e:G.resolve(t,e),s;try{s=await K.promises.readFile(n,"utf-8")}catch(o){if(o.code==="ENOENT")return;throw o}let i=s.replace(/(?:^|\n)# knodin:start\n[\s\S]*?\n# knodin:end\n?/,`
624
+ `);await K.promises.writeFile(n,i,"utf-8")}async function mg(t,e=!1){let n=[];for(let i of["AGENTS.md","GEMINI.md"]){let o=G.join(t,i),r=Rt(t,i);try{await lr(t,i);let c=await K.promises.readFile(o,"utf-8"),a=c.indexOf("<!-- knodin:start -->"),l=c.indexOf("<!-- knodin:end -->",a),u=fg(c);if(!r){u!==null&&(u.length>0?(await K.promises.writeFile(o,u,"utf-8"),n.push({path:i,action:"modified"})):(await K.promises.rm(o,{force:!0}),n.push({path:i,action:"removed"})));continue}if(e&&u!==null){await K.promises.writeFile(o,u,"utf-8"),n.push({path:i,action:"modified"});continue}let f=Re(t,["show",`HEAD:${i}`]);a>=0&&l>=a&&!f.includes("<!-- knodin:start -->")&&`${c.slice(0,a)}${c.slice(l+19)}`.replace(/\n{3,}/g,`
625
+
626
+ `).trimEnd()===f.trimEnd()&&await K.promises.writeFile(o,f)}catch{}}let s=G.join(t,".gitignore");try{let o=(await K.promises.readFile(s,"utf-8")).replace(/(?:^|\n)# knodin:start\n\.knodin\/\n# knodin:end\n?/g,`
627
+ `).trim();if(Rt(t,".gitignore")){let r=Re(t,["show","HEAD:.gitignore"]);e?await K.promises.writeFile(s,o?`${o}
628
+ `:""):o===r.trim()&&await K.promises.writeFile(s,r,"utf-8")}else o?await K.promises.writeFile(s,`${o}
629
+ `,"utf-8"):await K.promises.rm(s,{force:!0})}catch{}for(let i of[".claude/hooks/nudge.sh",".claude/settings.example.json"]){if(Rt(t,i))continue;let o=G.join(t,i);try{let r=await K.promises.readFile(o,"utf-8");(i.endsWith("nudge.sh")&&r===ug||i.endsWith("settings.example.json")&&r===dg)&&await K.promises.rm(o,{force:!0})}catch{}}return n}function ts(t){try{let e=JSON.parse(K.readFileSync(G.join(t,".knodin","integration.json"),"utf-8"));if((e.scope==="personal"||e.scope==="team"||e.scope==="cli-only")&&Array.isArray(e.agents))return{scope:e.scope,agents:e.agents}}catch{}return null}function pg(t,e){try{let n=t;for(let o of e.split(G.sep))if(n=G.join(n,o),K.lstatSync(n).isSymbolicLink())return!1;let s=K.readFileSync(G.join(t,e),"utf-8"),i=s.indexOf("<!-- knodin:start -->");return i>=0&&s.indexOf("<!-- knodin:end -->",i)>=i}catch{return!1}}function RE(t){let e=ts(t),s=[{agent:"claude",path:".mcp.json",marker:'"knodin"'},{agent:"codex",path:".codex/config.toml",marker:'mcp_servers."knodin"'},{agent:"gemini",path:".gemini/settings.json",marker:'"knodin"'},{agent:"antigravity",path:".agents/mcp_config.json",marker:'"knodin"'},{agent:"codex",path:"AGENTS.md",marker:"<!-- knodin:start -->",managedGuidance:!0},{agent:"gemini",path:"GEMINI.md",marker:"<!-- knodin:start -->",managedGuidance:!0}].map(({agent:r,path:c,marker:a,managedGuidance:l})=>{try{return{agent:r,path:c,present:l?pg(t,c):K.readFileSync(G.join(t,c),"utf-8").includes(a)}}catch{return{agent:r,path:c,present:!1}}}),i=s.filter(({present:r})=>r).map(({agent:r})=>r),o=[...new Set([...e?.agents??[],...i])];return!e&&o.length===0?null:{scope:e?.scope??"repository-detected",agents:o,receiptPresent:e!==null,configurations:s}}async function hg(t,e){await K.promises.writeFile(G.join(t,".knodin","integration.json"),`${JSON.stringify(e,null,2)}
630
+ `,"utf-8")}async function gg(t){if(Rt(t,".knodin"))return;await lr(t,".gitignore");let e=G.join(t,".gitignore"),n="";try{n=await K.promises.readFile(e,"utf-8")}catch(i){if(i.code!=="ENOENT")throw i}if(n.split(/\r?\n/).includes(".knodin/"))return;let s=n&&!n.endsWith(`
631
+ `)?`${n}
632
+ `:n;await K.promises.writeFile(e,`${s}# knodin:start
633
+ .knodin/
634
+ # knodin:end
635
+ `,"utf-8")}function yg(t){return[["AGENTS.md","<!-- knodin:start -->"],["GEMINI.md","<!-- knodin:start -->"],[".gitignore","# knodin:start"],[".mcp.json",'"knodin"'],[".codex/config.toml","# knodin:start"],[".gemini/settings.json",'"knodin"'],[".agents/mcp_config.json",'"knodin"']].some(([n,s])=>{if(!Rt(t,n))return!1;try{return K.readFileSync(G.join(t,n),"utf-8").includes(s)}catch{return!1}})}async function Tl(t,e){let n=G.resolve(t),s=e.scope??"personal",i=ts(n);if(Re(n,["rev-parse","--is-inside-work-tree"]).trim()!=="true")throw new Error(`knodin init: not a Git worktree: ${n}`);if(!G.isAbsolute(e.command[0]))throw new Error("knodin init: packaged runtime command must be an absolute path");let o=e.auditConfigurationChanges?sg(n):[],r=cl(o);if(s!=="team"&&!e.allowTrackedTransition&&yg(n))throw new Error("knodin init: tracked team integration is active; use `knodin configure --scope personal` or `--scope cli-only` for an explicit commit-ready transition");let c=G.join(n,".knodin","hooks"),a=await lg(n),l=a.hooksDir;await Promise.all([K.promises.mkdir(c,{recursive:!0}),K.promises.mkdir(l,{recursive:!0})]);let u=G.join(c,"background-index.sh");await K.promises.writeFile(u,bl(e.command),{encoding:"utf-8",mode:493}),await K.promises.chmod(u,493);let f=oa(n);for(let E of Ut){let $;if(a.trackedHooksDir){let p=`${a.trackedHooksDir}/${E}`,F=G.join(n,p);try{let L=await K.promises.stat(F);$=L.isFile()&&(L.mode&73)!==0?`repo:${p}`:null}catch{$=null}}await ag(l,E,$)}for(let E of await K.promises.readdir(l,{withFileTypes:!0}))E.isFile()&&await Sl(G.join(l,E.name));let m=await e.index(n,{onProgress:e.onProgress});if(ng(m)&&m.verification.status!=="healthy")throw new ar(m);let d=rg(n,u);await K.promises.rm(G.join(c,gl),{force:!0});let y=[];s==="team"?y=(await Promise.all([dl(n,"AGENTS.md"),dl(n,"GEMINI.md")])).filter($=>$!==null):y=await mg(n,e.allowTrackedTransition);let g=e.agents??[],h={codex:".codex/config.toml",gemini:".gemini/settings.json",antigravity:".agents/mcp_config.json"},w=[],k=[];if(s==="personal"&&e.allowTrackedTransition&&i?.scope==="team"){let E=Mi({repo:n,scope:"cli-only",agents:["claude","codex","gemini","antigravity"],run:e.runAgentCommand});if(E.failed.length>0)throw new Error(`knodin configure: could not remove tracked team integration: ${E.failed[0]?.message}`);E.removed.includes("claude")&&k.push({system:"claude-local-mcp",state:"removal-attempted"})}let _=s==="team"?g:g.filter(E=>{let $=E==="claude"?".mcp.json":h[E];return!$||!Rt(n,$)||s==="cli-only"&&e.allowTrackedTransition?!0:(e.allowTrackedTransition&&i?.scope==="team"||w.push({agent:E,message:`${$} is tracked; personal mode left it unchanged and did not exclude it`}),!1)}),R=Mi({repo:n,scope:s,agents:_,run:e.runAgentCommand});s==="personal"&&R.configured.includes("claude")&&k.push({system:"claude-local-mcp",state:"configured-or-present"}),s==="cli-only"&&R.removed.includes("claude")&&!k.some(({system:E,state:$})=>E==="claude-local-mcp"&&$==="removal-attempted")&&k.push({system:"claude-local-mcp",state:"removal-attempted"}),R.failed.push(...w),await hg(n,{scope:s,agents:R.configured}),s==="team"?(await gg(n),await pl(n)):s==="cli-only"&&await pl(n);let v=s==="team"?[]:await ml(n,[...Rt(n,".knodin")?[]:[".knodin/"],...R.projectFiles]);if(f){let E=await ml(n,[f.localConfig]);v=[...new Set([...v,...E])].sort()}al(n);let S=ig(r,cl(o,!0));return{scope:s,knodin:".knodin",database:".knodin/db.sqlite",backgroundIndexer:".knodin/hooks/background-index.sh",hooksDirectory:G.relative(n,l)||".",gitHooks:[...Ut],claudeSettings:null,agentInstructions:s==="team"?"AGENTS.md":null,agentIntegration:R,agentInstructionChanges:y,filesystemChanges:S,externalConfigurationOutcomes:k,excluded:v,lifecycleRefresh:d,hookManagerIntegration:f}}async function bg(t,e,n){try{let[s,i]=await Promise.all([K.promises.readFile(t,"utf-8"),K.promises.stat(t)]);return i.isFile()&&s===e&&(!n||(i.mode&73)!==0)}catch{return!1}}async function Rl(t,e,n="personal"){let s=G.resolve(t);if(!G.isAbsolute(e[0]))return!1;let i;try{if(Re(s,["rev-parse","--is-inside-work-tree"]).trim()!=="true")return!1;i=cr(s)}catch{return!1}let o=gs(s);if((await Promise.all(Ut.map(async l=>{let u=G.join(i,l);try{let[f,m]=await Promise.all([K.promises.readFile(u,"utf-8"),K.promises.stat(u)]),d=f.match(/^# knodin original: (.+)$/m)?.[1]??null,y=wl(l,d);return d&&(y=y.replace(`
636
+ REPO_ROOT=`,`
637
+ # knodin original: ${d}
638
+ REPO_ROOT=`)),m.isFile()&&(m.mode&73)!==0&&(f===y||o.configured&&ys(f))}catch{return!1}}))).some(l=>!l))return!1;let c=n!=="team"||await fl(s,"AGENTS.md")&&await fl(s,"GEMINI.md"),a=ts(s)?.scope===n;return await bg(G.join(s,".knodin","hooks","background-index.sh"),bl(e),!0)&&c&&a&&(o.localConfig===null||o.configured)}import wg from"node:crypto";import de from"node:fs";import Be from"node:path";import{encode as dr}from"gpt-tokenizer/encoding/o200k_base";var ss="gpt-tokenizer@3.4.0:o200k_base",NE=t=>dr(t).length,Al=30,xi=".knodin-telemetry.jsonl";function $l(t){return t.length===0?0:t.split(/\r?\n/).length}function Sg(t){return`repo_${wg.createHash("sha256").update(de.realpathSync(t)).digest("hex").slice(0,16)}`}function wn(t,e,n){let s=de.realpathSync(t),i=Be.resolve(s,e);if(i!==s&&!i.startsWith(`${s}${Be.sep}`))throw new Error(`knodin telemetry ${n}: path must stay inside the repository`);let o=Be.relative(s,i),r=s;for(let c of o===""?[]:o.split(Be.sep)){r=Be.join(r,c);let a;try{a=de.lstatSync(r)}catch(l){if(l.code==="ENOENT")break;throw l}if(a.isSymbolicLink())throw new Error(n==="persist"?"knodin telemetry: refusing symlinked persistence path":`knodin telemetry ${n}: refusing symlinked path`)}return{repo:s,target:i}}function fr(t,e){de.mkdirSync(Be.dirname(t),{recursive:!0,mode:448});let n=`${t}.${process.pid}.${Date.now()}.tmp`;de.writeFileSync(n,e,{mode:384,flag:"wx"}),de.renameSync(n,t)}function Fl(t,e){if(!Number.isInteger(t)||t<1||t>3650)throw new Error("knodin telemetry: retention days must be an integer from 1 to 3650");return e.getTime()-t*864e5}function _l(t,e){return t===0?e===0?0:Number.NEGATIVE_INFINITY:Math.round((t-e)/t*1e4)/100}function Eg(t,e,n){if(!["query:file_summary","query:batch_outline"].includes(e))return[];let s=e==="query:file_summary"?[n.target]:Array.isArray(n.results)?n.results.map(r=>r.file):[],i=de.realpathSync(t),o=new Set;for(let r of s){if(typeof r!="string"||!r)continue;let c=Be.resolve(i,r),a;try{a=de.realpathSync(c)}catch{continue}a!==i&&!a.startsWith(`${i}${Be.sep}`)||de.statSync(a).isFile()&&o.add(a)}return[...o].sort()}function CE(t){let e=JSON.stringify(t.output),n={contract:"actual-operation-response",bytes:Buffer.byteLength(e),tokens:dr(e).length,lines:$l(e)},s=Eg(t.repo,t.operation,t.output),i=s.length>0?s.map(y=>de.readFileSync(y,"utf-8")).join(`
639
+ `):null,o=i===null?null:{contract:"executed-full-file-read",bytes:Buffer.byteLength(i),tokens:dr(i).length,fileCount:s.length,lines:$l(i)},r=typeof t.output.status=="string"?t.output.status:void 0,c=t.output.availability,a=t.output.freshness,l=t.output.fidelity,u=Be.join(de.realpathSync(t.repo),".knodin","db.sqlite"),f=Math.round((performance.now()-t.startedAt)*100)/100,m=r!==void 0&&["error","failed","unavailable","blocked","timeout"].includes(r)||c?.state==="unavailable"?"error":"success",d=null;return typeof l=="number"?d=l:typeof l?.percent=="number"&&(d=l.percent),{schemaVersion:2,at:new Date().toISOString(),repositoryId:Sg(t.repo),operation:t.operation,...t.executionProfile?{executionProfile:t.executionProfile}:{},latencyMs:f,rssBytes:process.memoryUsage().rss,temperature:"cold",outcome:m,agentRoundTrips:1,indexStorageBytes:de.existsSync(u)?de.statSync(u).size:null,indexingMs:t.operation.startsWith("index")?f:null,freshnessFailure:t.output.staleness==="stale"||typeof a?.state=="string"&&a.state!=="fresh"||c?.state==="unavailable",compressionFidelity:d,confidence:o?"measured":"unavailable",truncated:t.truncated,detailMode:t.detailMode,tokenizer:ss,schemaTokens:t.schemaTokens,optimized:n,baseline:o,savings:o?{bytes:o.bytes-n.bytes,tokens:o.tokens-n.tokens,bytePercent:_l(o.bytes,n.bytes),tokenPercent:_l(o.tokens,n.tokens)}:null}}function ns(t,e){if(t.length===0)return 0;let n=[...t].sort((s,i)=>s-i);return n[Math.min(n.length-1,Math.ceil(n.length*e)-1)]??0}function ur(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Ll(t){let e=t.filter(({savings:n})=>n!==null);return{calls:t.length,successes:t.filter(({outcome:n})=>n!=="error").length,errors:t.filter(({outcome:n})=>n==="error").length,measuredBaselines:e.length,measuredTokensAvoided:e.reduce((n,s)=>n+(s.savings?.tokens??0),0),latencyP50Ms:ns(t.map(({latencyMs:n})=>n),.5),latencyP95Ms:ns(t.map(({latencyMs:n})=>n),.95),freshnessFailures:t.filter(({freshnessFailure:n})=>n===!0).length,compressionFidelitySamples:t.filter(({compressionFidelity:n})=>typeof n=="number").length,compressionFidelityP50:ns(t.flatMap(({compressionFidelity:n})=>typeof n=="number"?[n]:[]),.5),indexStorageBytes:Math.max(0,...t.map(({indexStorageBytes:n})=>n??0)),indexingMs:t.reduce((n,s)=>n+(s.indexingMs??0),0)}}function OE(t,e,n=".knodin/telemetry-report.html"){let{repo:s,target:i}=wn(t,n,"report"),o=new Map;for(let d of e){let y=o.get(d.operation)??[];y.push(d),o.set(d.operation,y)}let r=[...o].sort(([d],[y])=>d.localeCompare(y)).map(([d,y])=>{let g=y.filter(({savings:w})=>w!==null),h=g.reduce((w,k)=>w+(k.savings?.tokens??0),0);return`<tr><td>${ur(d)}</td><td>${y.length}</td><td>${y.filter(({outcome:w})=>w==="error").length}</td><td>${g.length}</td><td>${h}</td><td>${ns(y.map(({latencyMs:w})=>w),.5)}</td><td>${ns(y.map(({latencyMs:w})=>w),.95)}</td></tr>`}).join(""),c=Ll(e),a=new Map;for(let d of e){let y=typeof d.at=="string"?d.at.slice(0,10):"unknown",g=a.get(y)??{calls:0,tokens:0};g.calls+=1,g.tokens+=d.savings?.tokens??0,a.set(y,g)}let l=[...a].sort(([d],[y])=>d.localeCompare(y)).map(([d,y])=>`<tr><td>${ur(d)}</td><td>${y.calls}</td><td>${y.tokens}</td></tr>`).join(""),u=new Map;for(let d of e)d.repositoryId&&u.set(d.repositoryId,(u.get(d.repositoryId)??0)+1);let f=[...u].sort(([d],[y])=>d.localeCompare(y)).map(([d,y])=>`<tr><td>${ur(d)}</td><td>${y}</td></tr>`).join(""),m=`<!doctype html><meta charset="utf-8"><meta name="color-scheme" content="light dark"><title>knodin telemetry</title><style>:root{color-scheme:light dark;--line:#d0d7de;--card:#f6f8fa}body{font:14px system-ui;margin:2rem;max-width:76rem}section{background:var(--card);padding:1rem;margin:1rem 0;border-radius:.5rem}table{border-collapse:collapse;width:100%}th,td{padding:.55rem;border-bottom:1px solid var(--line);text-align:left}@media(prefers-color-scheme:dark){:root{--line:#30363d;--card:#161b22}}</style><h1>knodin local telemetry</h1><p>Tokenizer: ${ss}. Local, opt-in, metadata-only; source, raw output, command text, usernames, and paths are not persisted.</p><section><h2>Summary</h2><p>Total measured tokens avoided: ${c.measuredTokensAvoided}</p><p>Calls: ${c.calls}; successes: ${c.successes}; errors: ${c.errors}; measured baselines: ${c.measuredBaselines}</p><p>Latency p50 / p95: ${c.latencyP50Ms} / ${c.latencyP95Ms} ms</p><p>Freshness failures: ${c.freshnessFailures}; compression fidelity samples / p50: ${c.compressionFidelitySamples} / ${c.compressionFidelityP50}; indexing time: ${c.indexingMs} ms; index storage: ${c.indexStorageBytes} bytes</p></section><section><h2>Operation breakdown</h2><table><thead><tr><th>Operation</th><th>Calls</th><th>Errors</th><th>Measured baselines</th><th>Net tokens saved</th><th>p50 ms</th><th>p95 ms</th></tr></thead><tbody>${r}</tbody></table></section><section><h2>Time series</h2><table><thead><tr><th>Day</th><th>Calls</th><th>Tokens avoided</th></tr></thead><tbody>${l}</tbody></table></section><section><h2>Repository breakdown</h2><table><thead><tr><th>Private repository id</th><th>Calls</th></tr></thead><tbody>${f}</tbody></table></section><p>Use <code>knodin telemetry export</code> for the machine-readable evidence bundle and <code>knodin telemetry clear</code> to delete persisted records.</p>`;return fr(i,m),{outputPath:Be.relative(s,i),records:e.length,operations:o.size}}function Nl(t){return{schemaVersion:t.schemaVersion,at:t.at,repositoryId:t.repositoryId,operation:t.operation,...t.executionProfile&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(t.executionProfile)?{executionProfile:t.executionProfile}:{},latencyMs:t.latencyMs,rssBytes:t.rssBytes,temperature:t.temperature,outcome:t.outcome,agentRoundTrips:t.agentRoundTrips,indexStorageBytes:t.indexStorageBytes,indexingMs:t.indexingMs,freshnessFailure:t.freshnessFailure,compressionFidelity:t.compressionFidelity,confidence:t.confidence,truncated:t.truncated,detailMode:t.detailMode,tokenizer:t.tokenizer,schemaTokens:t.schemaTokens,optimized:{contract:"actual-operation-response",bytes:t.optimized.bytes,tokens:t.optimized.tokens,lines:t.optimized.lines},baseline:t.baseline?{contract:"executed-full-file-read",bytes:t.baseline.bytes,tokens:t.baseline.tokens,fileCount:t.baseline.fileCount,lines:t.baseline.lines}:null,savings:t.savings?{bytes:t.savings.bytes,tokens:t.savings.tokens,bytePercent:t.savings.bytePercent,tokenPercent:t.savings.tokenPercent}:null}}function mr(t,e=xi,n,s=new Date){let{target:i}=wn(t,e,"read");if(!de.existsSync(i))return[];let o=de.readFileSync(i,"utf-8").split(/\r?\n/).filter(Boolean).map((c,a)=>{try{return JSON.parse(c)}catch{throw new Error(`knodin telemetry read: malformed JSONL record at line ${a+1}`)}}).filter(c=>typeof c.operation=="string"&&c.tokenizer===ss&&typeof c.optimized?.tokens=="number").map(Nl);if(n===void 0)return o;let r=Fl(n,s);return o.filter(({at:c})=>typeof c!="string"||Date.parse(c)>=r)}function IE(t,e,n=Al,s=new Date,i=xi){let{target:o}=wn(t,i,"persist"),r=mr(t,i);r.push(Nl({...e,at:e.at??s.toISOString()}));let c=Fl(n,s),a=r.filter(({at:l})=>typeof l!="string"||Date.parse(l)>=c);return fr(o,a.length===0?"":`${a.map(l=>JSON.stringify(l)).join(`
640
+ `)}
641
+ `),{records:a.length,retentionDays:n}}function ME(t,e=xi,n=Al,s=new Date){let{repo:i,target:o}=wn(t,e,"status"),r=de.existsSync(o),c=mr(i,e,n,s),a=c.map(({at:l})=>typeof l=="string"?l:null).filter(l=>l!==null).sort((l,u)=>l.localeCompare(u));return{schemaVersion:1,enabledByDefault:!1,localOnly:!0,persisted:r,inputPath:Be.relative(i,o),records:c.length,bytes:r?de.statSync(o).size:0,retentionDays:n,oldestAt:a[0]??null,newestAt:a.at(-1)??null,tokenizer:ss}}function PE(t,e,n=".knodin/telemetry-export.json"){let{repo:s,target:i}=wn(t,n,"export"),o={schemaVersion:1,generatedAt:new Date().toISOString(),privacy:"local-metadata-only",tokenizer:ss,methodology:{measured:"actual operation response versus executed repository-contained full-file read",modeled:null,unknownBaselines:"null"},summary:Ll(e),records:e};return fr(i,`${JSON.stringify(o,null,2)}
642
+ `),{outputPath:Be.relative(s,i),records:e.length,summary:o.summary}}function DE(t,e=xi){let{target:n}=wn(t,e,"clear");if(!de.existsSync(n))return{removed:!1,records:0,bytes:0};let s=mr(t,e).length,i=de.statSync(n).size;return de.unlinkSync(n),{removed:!0,records:s,bytes:i}}import Ti from"node:child_process";function hr(){return process.env.KNODIN_GH_BIN||"gh"}var kg=30,Ol="number,title,updatedAt,reviewDecision,statusCheckRollup,files,headRefName",vg=`${Ol},baseRefName,state,mergeCommit,url,isDraft`,xg="knodin prs requires the GitHub CLI ('gh') on PATH \u2014 install it, then run 'gh auth login'.",Tg="knodin prs requires an authenticated 'gh' \u2014 run 'gh auth login' (gh auth status failed).";function pr(t,e){if(e.length>256)return!1;let n=0,s=0,i=-1,o=0;for(;n<t.length;)if(s<e.length&&(e[s]==="?"||e[s]===t[n]))n++,s++;else if(s<e.length&&e[s]==="*")i=s++,o=n;else if(i>=0)s=i+1,n=++o;else return!1;for(;s<e.length&&e[s]==="*";)s++;return s===e.length}function BE(){let t=hr(),e=Ti.spawnSync(t,["auth","status"],{encoding:"utf-8",env:process.env});return e.error?xg:e.status!==0?Tg:null}var Rg=`${Ol},state`;function $g(t,e){let n=hr(),s=Ti.spawnSync(n,["pr","view",String(e),"--json",Rg],{cwd:t,encoding:"utf-8",env:process.env});if(s.error||s.status!==0)return null;let i=(s.stdout??"").toString().trim();if(!i)return null;let o=JSON.parse(i);return o.state!=="OPEN"?null:o}function Il(t){if(!t||t.length===0)return"none";let e=new Set(["FAILURE","CANCELLED","TIMED_OUT","ERROR","ACTION_REQUIRED","STARTUP_FAILURE"]),n=!1;for(let s of t){let i=(s.conclusion??"").toUpperCase(),o=(s.state??"").toUpperCase(),r=(s.status??"").toUpperCase();if(e.has(i)||o==="FAILURE"||o==="ERROR")return"fail";(o==="PENDING"||r&&r!=="COMPLETED")&&(n=!0)}return n?"pending":"pass"}function Ml(t,e,n=Date.now()){if(e==="fail"||t.reviewDecision==="CHANGES_REQUESTED")return"BLOCKED";if(e==="pending")return"PENDING";let s=Date.parse(t.updatedAt),i=(n-s)/(1e3*60*60*24);return Number.isFinite(i)&&i>kg?"STALE":"READY"}async function Pl(t,e,n){let s=(t.files??[]).map(l=>l.path).filter(Boolean);if(s.length===0)return null;let i=[];for(let l of s)(await e.query("file_summary",l,n)).count>0&&i.push(l);if(i.length===0)return null;let o=await e.query("impact",i.join(","),n,void 0,void 0,void 0,void 0,void 0,{mode:"file"}),r=new Set(i);for(let l of o.results)l.file&&r.add(l.file);let c=await e.map(n,"standard"),a=[];for(let l of c.communities)(l.files??[]).some(f=>r.has(f))&&a.push(l.name);return{symbolCount:o.count,files:[...r],communities:a}}async function _g(t,e,n){let s=await Pl(t,e,n);return s?{symbols:s.symbolCount,communities:s.communities.length}:{symbols:"\u2013",communities:"\u2013"}}async function Ag(t,e,n){let s=await Pl(t,e,n);return s?{files:s.files,communities:s.communities}:{files:[],communities:[]}}async function HE(t,e,n,s=50){let i=$g(t,n);if(!i)return{error:`knodin prs: PR #${n} not found among open PRs`};let o=Il(i.statusCheckRollup),r=Ml(i,o),c=await Ag(i,e,t);return{number:i.number,title:i.title,status:r,ci:o,updatedAt:i.updatedAt,impact:c}}function $t(t,e){let n=Ti.spawnSync(hr(),e,{cwd:t,encoding:"utf-8",env:process.env});return n.error?{value:null,error:n.error instanceof Error?n.error.message:String(n.error)}:n.status!==0?{value:null,error:(n.stderr??"").toString().trim()||`gh ${e.join(" ")} failed`}:{value:(n.stdout??"").toString().trim(),error:null}}function Fg(t,e,n){if(!e&&!n)return{commits:null,error:null};if(!e||!n)return{commits:null,error:"both --base and --head are required for revision auditing"};let s=Ti.spawnSync("git",["rev-list",`${e}..${n}`],{cwd:t,encoding:"utf-8"});return s.status!==0?{commits:null,error:(s.stderr??"").toString().trim()||`unable to resolve ${e}..${n}`}:{commits:new Set((s.stdout??"").toString().split(/\r?\n/).filter(Boolean)),error:null}}function Cl(t,e,n){if(t==="~ALL")return!0;if(t==="~DEFAULT_BRANCH")return n===e;let s=`refs/heads/${e}`;return t===e||t===s||pr(e,t)||pr(s,t)}function Lg(t,e,n){if(t.target!=="branch"||t.enforcement!=="active")return!1;let s=t.conditions?.ref_name;if((s?.exclude??[]).some(r=>Cl(r,e,n)))return!1;let o=s?.include??[];return o.length===0||o.some(r=>Cl(r,e,n))}function Ng(t,e,n,s){let i=$t(t,["api",`repos/${e}/rulesets?includes_parents=true`]);if(i.error)return{checks:null,error:i.error};let o;try{if(o=JSON.parse(i.value||"[]"),!Array.isArray(o))throw new Error("expected an array")}catch(c){return{checks:null,error:`invalid ruleset list JSON (${c instanceof Error?c.message:String(c)})`}}let r=[];for(let c of o){if(c.id===void 0)continue;let a=$t(t,["api",`repos/${e}/rulesets/${c.id}?includes_parents=true`]);if(a.error)return{checks:null,error:`ruleset ${c.id}: ${a.error}`};let l;try{l=JSON.parse(a.value||"{}")}catch(u){return{checks:null,error:`ruleset ${c.id}: invalid JSON (${u instanceof Error?u.message:String(u)})`}}if(Lg(l,n,s))for(let u of l.rules??[]){if(u.type==="required_status_checks")for(let f of u.parameters?.required_status_checks??[])r.push({...f,source:"ruleset",rulesetId:l.id??c.id,rulesetName:l.name??c.name??null,ruleType:u.type});if(u.type==="workflows")for(let f of u.parameters?.workflows??[])r.push({...f,context:f.path??null,source:"ruleset",rulesetId:l.id??c.id,rulesetName:l.name??c.name??null,ruleType:u.type})}}return{checks:r,error:null}}function Cg(t,e,n,s){let i=[],o=null,r=$t(t,["api",`repos/${e}/branches/${encodeURIComponent(n.baseRefName??"")}/protection/required_status_checks`]);if(r.error?.includes("HTTP 404")){let d=Ng(t,e,n.baseRefName??"",s);d.error?i.push(`PR #${n.number} required checks: classic protection unavailable (${r.error}); rulesets: ${d.error}`):o=d.checks}else if(r.error)i.push(`PR #${n.number} required checks: ${r.error}`);else try{let d=JSON.parse(r.value||"{}");o=d.checks??d.contexts??[]}catch(d){i.push(`PR #${n.number} required checks: invalid JSON (${d instanceof Error?d.message:String(d)})`)}let[c,a]=e.split("/",2),l=$t(t,["api","graphql","-f","query=query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100){nodes{isResolved isOutdated}pageInfo{hasNextPage}}}}}","-F",`owner=${c}`,"-F",`name=${a}`,"-F",`number=${n.number}`]),u=null;if(l.error)i.push(`PR #${n.number} review threads: ${l.error}`);else try{let y=JSON.parse(l.value||"{}").data?.repository?.pullRequest?.reviewThreads;y?.pageInfo?.hasNextPage?i.push(`PR #${n.number} review threads: incomplete response exceeds 100 threads`):u=(y?.nodes??[]).filter(g=>!g.isResolved&&!g.isOutdated).length}catch(d){i.push(`PR #${n.number} review threads: invalid JSON (${d instanceof Error?d.message:String(d)})`)}let f=$t(t,["api",`repos/${e}/git/ref/heads/${encodeURIComponent(n.headRefName)}`]),m=f.error?f.error.includes("HTTP 404")?!1:null:!0;return f.error&&m===null&&i.push(`PR #${n.number} head branch: ${f.error}`),{requiredChecks:o,unresolvedActionableThreads:u,headBranchSurvives:m,errors:i}}async function UE(t,e,n={}){let s=[],i=$t(t,["repo","view","--json","nameWithOwner,url,defaultBranchRef"]);i.error&&s.push(`repository: ${i.error}`);let o=null,r=null,c=null;try{let R=JSON.parse(i.value||"{}");o=R.nameWithOwner??null,r=R.url?new URL(R.url).host:null,c=R.defaultBranchRef?.name??null}catch(R){s.push(`repository: invalid JSON (${R instanceof Error?R.message:String(R)})`)}let a=$t(t,["api",...r?["--hostname",r]:[],"user","--jq",".login"]);a.error&&s.push(`authentication: ${a.error}`);let l=a.value;if(n.expectedLogin&&l&&n.expectedLogin!==l&&s.push(`authenticated login mismatch: expected ${n.expectedLogin}, resolved ${l}`),!o||!l||s.some(R=>R.includes("login mismatch")))return{schemaVersion:1,status:"unavailable",repository:o,host:r,authenticatedAs:l,resultCount:null,pullRequests:[],errors:s};let u=n.state??"open";["open","merged","closed","all"].includes(u)||s.push(`pull requests: unsupported state ${u}`),n.range&&!/^\d+\.\.\d+$/.test(n.range)&&s.push(`pull requests: invalid range ${n.range}; expected N..N`);let f=Fg(t,n.base,n.head);if(f.error&&s.push(`revision range: ${f.error}`),s.length>0)return{schemaVersion:1,status:"unavailable",repository:o,host:r,authenticatedAs:l,resultCount:null,pullRequests:[],errors:s};let m=$t(t,["pr","list","--state",u,"--limit",String(n.limit??50),"--json",vg]);if(m.error)return s.push(`pull requests: ${m.error}`),{schemaVersion:1,status:"unavailable",repository:o,host:r,authenticatedAs:l,resultCount:null,pullRequests:[],errors:s};let d;try{d=m.value?JSON.parse(m.value):[]}catch(R){s.push(`pull requests: invalid JSON (${R instanceof Error?R.message:String(R)})`),d=[]}let y=n.branches??null,g=n.range?.match(/^(\d+)\.\.(\d+)$/),h=g?Number(g[1]):null,w=g?Number(g[2]):null,k=d.filter(R=>(!y||pr(R.headRefName,y))&&(h===null||w===null||R.number>=h&&R.number<=w)&&(f.commits===null||R.mergeCommit?.oid!==void 0&&f.commits.has(R.mergeCommit.oid))),_=[];for(let R of k){let v=Il(R.statusCheckRollup),S=Cg(t,o,R,c);s.push(...S.errors),_.push({number:R.number,title:R.title,state:R.state??u.toUpperCase(),head:R.headRefName,base:R.baseRefName??null,mergeCommit:R.mergeCommit?.oid??null,url:R.url??null,isDraft:R.isDraft??!1,reviewDecision:R.reviewDecision,approval:R.reviewDecision==="APPROVED",ci:v,triageStatus:Ml(R,v),observedChecks:R.statusCheckRollup??[],requiredChecks:S.requiredChecks,unresolvedActionableThreads:S.unresolvedActionableThreads,headBranchSurvives:S.headBranchSurvives,impact:await _g(R,e,t)})}return{schemaVersion:1,status:s.length>0?"partial":"ok",repository:o,host:r,authenticatedAs:l,state:u,resultCount:_.length,pullRequests:_,errors:s,revisionRange:n.base&&n.head?{base:n.base,head:n.head,commitCount:f.commits?.size??null}:null,limitations:["review-thread evidence is intentionally incomplete when a PR exceeds 100 threads"]}}import{createHash as Og,createHmac as Bl,randomBytes as Ig,timingSafeEqual as Mg}from"node:crypto";import $e from"node:fs";import De from"node:path";var Hl=["locate","outline","evidence","expand"],Pg=65536,Dl=16384,Dg=100,jl=1600;function zl(t){return Og("sha256").update(t).digest("hex")}function jg(t,e){if(!e||De.isAbsolute(e))throw new Error("file must be a repository-relative path");let n=$e.realpathSync(t),s=De.resolve(n,e),i=De.relative(n,s).split(De.sep).join("/");if(!i||i===".."||i.startsWith("../"))throw new Error("file must be a repository-relative path");if(i===".knodin"||i.startsWith(".knodin/"))throw new Error("progressive evidence refuses internal knodin state");let o=n;for(let l of i.split("/"))if(o=De.join(o,l),$e.lstatSync(o).isSymbolicLink())throw new Error("progressive evidence refuses symlinked paths");let r=$e.realpathSync(s),c=De.relative(n,r);if(c===".."||c.startsWith(`..${De.sep}`)||De.isAbsolute(c))throw new Error("file must remain within the repository");let a=$e.lstatSync(r);if(!a.isFile()||a.isSymbolicLink())throw new Error("progressive evidence requires a regular repository file");return{absolute:r,relative:i,root:n}}function zg(t){let e=De.join(t,".knodin");if($e.existsSync(e)&&$e.lstatSync(e).isSymbolicLink())throw new Error("progressive evidence refuses a symlinked .knodin directory");$e.mkdirSync(e,{recursive:!0,mode:448});let n=De.join(e,"progressive-evidence.key");if(!$e.existsSync(n))try{$e.writeFileSync(n,Ig(32).toString("hex"),{flag:"wx",mode:384})}catch(i){if(i.code!=="EEXIST")throw i}if($e.lstatSync(n).isSymbolicLink())throw new Error("progressive evidence refuses a symlinked handle key");let s=$e.readFileSync(n,"utf8");if(!/^[a-f0-9]{64}$/.test(s))throw new Error("invalid progressive evidence handle key");return{secret:Buffer.from(s,"hex"),path:n}}function is(t,e){let n=Buffer.from(JSON.stringify(t)).toString("base64url"),s=Bl("sha256",e).update(n).digest("hex");return`pev1.${n}.${s}`}function Bg(t,e){if(t.length>2048)throw new Error("invalid continuation handle");let[n,s,i,o]=t.split(".");if(n!=="pev1"||!s||!i||o!==void 0)throw new Error("invalid continuation handle");let r=Bl("sha256",e).update(s).digest("hex"),c=Buffer.from(i),a=Buffer.from(r);if(c.length!==a.length||!Mg(c,a))throw new Error("invalid continuation handle");let l;try{l=JSON.parse(Buffer.from(s,"base64url").toString("utf8"))}catch{throw new Error("invalid continuation handle")}if(!l||typeof l!="object")throw new Error("invalid continuation handle");let u=l;if(u.v!==1||typeof u.path!="string"||!/^[a-f0-9]{64}$/.test(u.hash??"")||!Number.isSafeInteger(u.bytes)||(u.bytes??-1)<0||!Number.isSafeInteger(u.nextLine)||(u.nextLine??0)<1||!Number.isSafeInteger(u.relatedOffset)||(u.relatedOffset??-1)<0||!Number.isSafeInteger(u.outlineOffset)||(u.outlineOffset??-1)<0||!Hl.includes(u.nextLevel))throw new Error("invalid continuation handle");return u}function Ri(t,e,n){let s=t??e;if(!Number.isSafeInteger(s)||s<1)throw new Error(`${n} must be positive`);return s}function Ul(t){let e=[],n=/^(?:export\s+)?(?:async\s+)?(?:function|class|interface|type|enum|const|let|var)\s+[A-Za-z_$][\w$]*/;for(let s=0;s<t.length;s++){if(!n.test(t[s]??""))continue;let i=0,o=!1,r=s;for(let c=s;c<t.length;c++){for(let a of t[c]??"")a==="{"?(i++,o=!0):a==="}"&&i--;if(r=c,!o||i<=0)break}e.push({signature:(t[s]??"").trim(),line:s+1,endLine:r+1})}return e}function Hg(t,e,n){let s=Ul(n).map(({signature:r})=>/\b(?:function|class|interface|type|enum|const|let|var)\s+([\w$]+)/.exec(r)?.[1]).filter(r=>!!r);if(s.length===0)return[];let i=[],o=r=>{for(let c of $e.readdirSync(r,{withFileTypes:!0}).sort((a,l)=>a.name.localeCompare(l.name))){if([".git",".knodin","node_modules"].includes(c.name)||c.isSymbolicLink())continue;let a=De.join(r,c.name);if(c.isDirectory()){o(a);continue}let l=De.relative(t,a).split(De.sep).join("/");if(!(!c.isFile()||l===e||!/\.(?:[cm]?[jt]sx?|py|java|cs|go|rs)$/.test(l)))for(let[u,f]of $e.readFileSync(a,"utf8").split(`
643
+ `).entries())s.some(m=>new RegExp(`\\b${m}\\b`).test(f))&&i.push({file:l,line:u+1,kind:/(?:^|\/)(?:test|tests|__tests__)(?:\/|$)|\.(?:test|spec)\./.test(l)?"test-reference":"source-reference",evidence:f,confidence:"heuristic"})}};return o(t),i}function Ug(t,e,n,s,i){return e&&e.path!==i?"full-renamed-baseline":e&&(e.hash!==n||e.bytes!==s)?"full-stale-baseline":!t.baselineHash&&t.baselineBytes===void 0?"full-missing-baseline":!t.baselineHash||t.baselineBytes===void 0?"full-incomplete-baseline":/^[a-f0-9]{64}$/.test(t.baselineHash)?e?t.baselineHash!==n||t.baselineBytes!==s?"full-hash-mismatch":"hash-match-omission":"full-unverified-baseline":"full-hash-mismatch"}function KE(t){if(!Hl.includes(t.level))throw new Error("invalid progressive evidence level");let{absolute:e,relative:n,root:s}=jg(t.repo,t.file),i=zg(s),o=$e.statSync(e),r=$e.statSync(i.path);if(o.dev===r.dev&&o.ino===r.ino)throw new Error("progressive evidence refuses an alias of internal knodin state");let c=$e.readFileSync(e,"utf8"),a=zl(c),l=Buffer.byteLength(c),u=c.split(`
644
+ `),f=i.secret,m=t.continuation?Bg(t.continuation,f):void 0,d=!m||m.path===n&&m.hash===a&&m.bytes===l,y=!!(m&&!d),g=d?m:void 0;if(m&&m.nextLevel!==t.level)throw new Error(`continuation requires ${m.nextLevel}, not ${t.level}`);if(g&&(t.level==="evidence"||t.level==="expand")&&t.startLine!==void 0&&t.startLine!==g.nextLine)throw new Error("continuation source range does not match its next line");if(m&&(t.level==="locate"||t.level==="outline")&&(m.path!==n||m.hash!==a||m.bytes!==l))throw new Error("stale or renamed continuation");let h=Math.min(Ri(t.byteLimit,Pg,"byteLimit"),Ri(t.tokenLimit,Dl,"tokenLimit")*4),w=Ri(t.tokenLimit,Dl,"tokenLimit"),k=Ri(t.itemLimit,Dg,"itemLimit");if(h<jl)throw new Error(`progressive evidence byte/token budget must allow at least ${jl} bytes`);let _=["identity","location"],R=["outline","source","related"],v="requested-level",S=t.level!=="expand",E,$,p,F,L=1,T=1,x="full",I="exact",M=g?.outlineOffset??0,b=0;if(t.level==="outline"){let z=Ul(u);b=z.length,E=z.slice(M,M+k),_=[..._,"outline"],R=[...M+E.length<z.length?["outline-tail"]:[],"source","related"],T=z.length,S=!0}else if(t.level==="evidence"||t.level==="expand"){if(x=Ug(t,m,a,l,n),t.level==="evidence"&&x==="hash-match-omission")_=[..._,"hash-verification"],R=["source","related"],v="verified-baseline-current",S=!0;else{let D=y?1:t.startLine??g?.nextLine??1;if(!Number.isSafeInteger(D)||D<1||D>u.length+1)throw new Error("invalid source range");if(D===u.length+1&&t.level==="expand")L=D,R=[],S=!1;else{let H=y?u.length:t.endLine??u.length;if(!Number.isSafeInteger(H)||H<D)throw new Error("invalid source range");let W=Math.min(H,u.length,D+k-1);F={startLine:D,endLine:W},p=u.slice(D-1,W).join(`
645
+ `),_=[..._,"source"],L=W+1,S=W<u.length||t.level!=="expand",R=W<u.length?["source-tail","related"]:t.level==="expand"?[]:["related"],v=W<u.length?"hard-item-budget":"requested-level"}T=u.length}if(t.level==="expand"){let D=Hg(s,n,u),H=g?.relatedOffset??0,W=F?F.endLine-F.startLine+1:0,X=Math.max(0,k-W);$=L>u.length?D.slice(H,H+X):[],$.length>0&&(_=[..._,"related"],I="heuristic"),H+$.length<D.length&&(R=[...R,"related-tail"],S=!0,v="hard-item-budget"),T=u.length+D.length}}let A=t.level==="locate"?"outline":t.level==="outline"?M+(E?.length??0)<b?"outline":"evidence":S&&L<=u.length?t.level:"expand",C=is({v:1,path:n,hash:a,bytes:l,nextLine:1,nextLevel:"evidence",outlineOffset:0,relatedOffset:0},f),O=S?is({v:1,path:n,hash:a,bytes:l,nextLine:L,nextLevel:A,outlineOffset:M+(E?.length??0),relatedOffset:(g?.relatedOffset??0)+($?.length??0)},f):null,N={protocol:"knodin-progressive-evidence-v1",level:t.level,file:n,identity:`file_${zl(n).slice(0,24)}`,contentHash:a,contentBytes:l,returned:_,omitted:R,reason:v,more:S,continuation:O,evidenceHandle:C,freshness:"fresh",confidence:I,pathTaken:x,location:{path:n,lines:u.length},...E?{outline:E}:{},...$?{related:$}:{},...p!==void 0?{source:p,sourceRange:F}:{},budget:{byteLimit:h,tokenLimit:w,itemLimit:k,serializedBytes:0,estimatedTokens:0,returnedItems:(E?.length??(F?F.endLine-F.startLine+1:1))+($?.length??0),totalItems:T,truncated:R.length>0}},j=()=>{for(let z=0;z<4;z++)N.budget.serializedBytes=Buffer.byteLength(JSON.stringify(N)),N.budget.estimatedTokens=Math.ceil(N.budget.serializedBytes/4)};for(j();N.budget.serializedBytes>h&&N.related?.length;)N.related.pop(),N.more=!0,N.reason="hard-byte-budget",N.omitted.includes("related-tail")||N.omitted.push("related-tail"),N.related.length===0&&(N.returned=N.returned.filter(z=>z!=="related")),N.continuation=is({v:1,path:n,hash:a,bytes:l,nextLine:L,nextLevel:"expand",outlineOffset:0,relatedOffset:(g?.relatedOffset??0)+N.related.length},f),N.budget.returnedItems--,N.budget.truncated=!0,j();for(;N.budget.serializedBytes>h&&N.outline?.length;)N.outline.pop(),N.more=!0,N.reason="hard-byte-budget",N.omitted.includes("outline-tail")||N.omitted.unshift("outline-tail"),N.continuation=is({v:1,path:n,hash:a,bytes:l,nextLine:1,nextLevel:"outline",outlineOffset:M+N.outline.length,relatedOffset:0},f),N.budget.returnedItems--,N.budget.truncated=!0,j();for(;N.budget.serializedBytes>h&&N.sourceRange&&N.sourceRange.endLine>=N.sourceRange.startLine;){N.sourceRange.endLine--,N.sourceRange.endLine<N.sourceRange.startLine?(delete N.source,delete N.sourceRange,N.returned=N.returned.filter(D=>D!=="source")):N.source=u.slice(N.sourceRange.startLine-1,N.sourceRange.endLine).join(`
646
+ `),N.more=!0,N.reason="hard-byte-budget",N.omitted.includes("source-tail")||N.omitted.unshift("source-tail");let z=N.sourceRange?.endLine?N.sourceRange.endLine+1:y?1:t.startLine??g?.nextLine??1;N.continuation=is({v:1,path:n,hash:a,bytes:l,nextLine:z,nextLevel:t.level,outlineOffset:0,relatedOffset:g?.relatedOffset??0},f),N.budget.returnedItems=Math.max(0,N.budget.returnedItems-1),N.budget.truncated=!0,j()}if(N.budget.serializedBytes>h)throw new RangeError("progressive evidence response exceeds the hard byte/token budget");return N}import{spawn as Wl}from"node:child_process";import Wt from"node:process";var Wg=768*1024*1024,ql=64*1024,Gl=1e3,qg=250;function gr(t,e){return t.length>=ql?t:`${t}${e.toString("utf-8")}`.slice(0,ql)}function Vl(t){if(!(!Number.isSafeInteger(t)||t<=1))try{Wt.kill(Wt.platform==="win32"?t:-t,"SIGTERM")}catch{}}function Kl(t){if(!(!Number.isSafeInteger(t)||t<=1))try{Wt.kill(Wt.platform==="win32"?t:-t,"SIGKILL")}catch{}}function Gg(t){if(!t||typeof t!="object")return!1;let e=t,n=e.result;return e.type==="rss"&&Number.isSafeInteger(e.rssBytes)&&Number(e.rssBytes)>=0||e.type==="result"&&!!n&&typeof n?.repository=="string"&&typeof n.message=="string"&&["initialized","updated","already-current","skipped","failed"].includes(String(n.status))}async function YE(t){let e=t.memoryLimitBytes??Wg;if(!Number.isSafeInteger(e)||e<128*1024*1024)throw new Error("repository init memory limit must be an integer of at least 128 MiB");if(t.command.length===0||!t.command[0])throw new Error("repository init worker command is empty");return await new Promise(n=>{let s="",i=0,o,r=!1,c=!1,a=!1,l=!1,u=Wl(t.command[0],[...t.command.slice(1),"__repository-init-worker",t.repository],{cwd:t.repository,detached:Wt.platform!=="win32",env:{...Wt.env,KNODIN_INTERNAL_INIT_MEMORY_LIMIT_BYTES:String(e)},stdio:["ignore","ignore","pipe","ipc"]});u.stderr?.on("data",y=>{s=gr(s,y)});let f=y=>{if(i=Math.max(i,y),y<=e||r)return;r=!0;let g=u.pid??0;Vl(g),setTimeout(()=>Kl(g),Gl).unref()};u.on("message",y=>{if(Gg(y)){if(y.type==="result"){o=y.result;return}f(y.rssBytes)}});let m=setInterval(()=>{let y=u.pid;if(Wt.platform==="win32"||!y||l||a)return;l=!0;let g=Wl("/bin/ps",["-o","rss=","-p",String(y)],{stdio:["ignore","pipe","ignore"]}),h="";g.stdout?.on("data",w=>{h=gr(h,w)}),g.on("close",()=>{if(l=!1,a)return;let w=Number.parseInt(h.trim(),10);Number.isSafeInteger(w)&&w>=0&&f(w*1024)}),g.on("error",()=>{l=!1})},qg);m.unref(),u.on("error",y=>{s=gr(s,Buffer.from(y.message))});let d=setTimeout(()=>{c=!0;let y=u.pid??0;Vl(y),setTimeout(()=>Kl(y),Gl).unref()},t.timeoutMs??30*6e4);d.unref(),u.on("close",(y,g)=>{if(a)return;if(a=!0,clearTimeout(d),clearInterval(m),r){n({repository:t.repository,status:"failed",message:`memory ceiling exceeded (${i} > ${e} bytes); worker terminated`,peakRssBytes:i,memoryLimitBytes:e});return}if(c){n({repository:t.repository,status:"failed",message:"isolated initialization timed out; worker process tree terminated",peakRssBytes:i,memoryLimitBytes:e});return}if(o){n({...o,repository:t.repository,peakRssBytes:i,memoryLimitBytes:e});return}let h=s.trim().replace(/\s+/g," "),w=g?`signal ${g}`:`exit ${y??"unknown"}`,k=h?`: ${h}`:"";n({repository:t.repository,status:"failed",message:`isolated initialization failed (${w})${k}`,peakRssBytes:i,memoryLimitBytes:e})})})}var Vg=new TextEncoder,Xl=256,Kg=128;function Le(t){return Vg.encode(JSON.stringify(t)).byteLength}function yr(t,e){return t==null||!Number.isFinite(t)?e:Math.max(1,Math.trunc(t))}function os(t,e="$"){return Array.isArray(t)?[{path:e,value:t},...t.flatMap((n,s)=>os(n,`${e}/${s}`))]:!t||typeof t!="object"?[]:Object.entries(t).flatMap(([n,s])=>os(s,`${e}/${n}`))}function br(t,e="$"){if(!t||typeof t!="object")return[];let n=Array.isArray(t)?t.entries():Object.entries(t),s=[];for(let[i,o]of n){let r=`${e}/${String(i)}`;typeof o=="string"?s.push({parent:t,key:i,path:r,value:o}):s.push(...br(o,r))}return s}var Xg=new Set(["identity","symbol","file","filePath","error","status","operation","kind","name","target","to"]);function Zl(t){return typeof t.key!="string"||!Xg.has(t.key)}function Jl(t,e,n,s){let i=yr(n.bytes,s.bytes),o=yr(n.tokens,s.tokens),r=Math.min(i,o*4);if(r<Xl)throw new RangeError(`response budget must allow at least ${Xl} serialized bytes (64 estimated tokens)`);let c=yr(n.items,s.items),a=structuredClone(t),l=Array.isArray(a)?{results:a}:a&&typeof a=="object"?a:{result:a},u={},f=!1,m=os(l),d=[...m].sort((g,h)=>g.path.split("/").length-h.path.split("/").length||g.path.localeCompare(h.path)).slice(0,Kg);for(let g of d)u[g.path]=g.value.length;for(let g of m)g.value.length>c&&(g.value.splice(c),f=!0);let y={byteLimit:r,tokenLimit:o,itemLimit:c,serializedBytes:0,estimatedTokens:0,truncated:!1,totals:u,...m.length>d.length?{omittedTotalPaths:m.length-d.length}:{}};for(l.responseBudget=y;Le(l)>r;){let g=br(l).filter(k=>!k.path.startsWith("$/responseBudget")&&k.value.length>0&&Zl(k)).sort((k,_)=>_.value.length-k.value.length)[0];if(!g)break;let h=`
647
+ \u2026 [truncated]`;if(g.value.length<=h.length+1){Array.isArray(g.parent)?g.parent.splice(g.key,1):delete g.parent[g.key],f=!0;continue}let w=Math.max(0,Math.floor((g.value.length-h.length)/2));g.parent[g.key]=`${g.value.slice(0,w)}${h}`,f=!0}for(;Le(l)>r;){let g=os(l).filter(h=>!h.path.startsWith("$/responseBudget")&&h.value.length>0).sort((h,w)=>Le(w.value)-Le(h.value))[0];if(!g)break;g.value.pop(),f=!0}for(y.truncated=f,f&&(y.continuation={operation:e,after:"returned-items",instruction:`Repeat ${e} with a narrower selector, larger budget, or query drill-down.`}),y.serializedBytes=Le(l),y.estimatedTokens=Math.ceil(y.serializedBytes/4),Le(l)>r&&y.continuation&&(y.continuation.instruction="Narrow or increase budget.",y.serializedBytes=Le(l),y.estimatedTokens=Math.ceil(y.serializedBytes/4));Le(l)>r;){let g=br(l).filter(w=>!w.path.startsWith("$/responseBudget")&&w.value.length>0&&Zl(w)).sort((w,k)=>k.value.length-w.value.length)[0];if(!g)break;let h=`
648
+ \u2026 [truncated]`;if(g.value.length<=h.length+1)Array.isArray(g.parent)?g.parent.splice(g.key,1):delete g.parent[g.key];else{let w=Math.max(0,Math.floor((g.value.length-h.length)/2));g.parent[g.key]=`${g.value.slice(0,w)}${h}`}y.truncated=!0}for(y.serializedBytes=Le(l),y.estimatedTokens=Math.ceil(y.serializedBytes/4);Le(l)>r;){let g=os(l).filter(h=>!h.path.startsWith("$/responseBudget")&&h.value.length>0).sort((h,w)=>Le(w.value)-Le(h.value))[0];if(!g)break;g.value.pop(),y.truncated=!0,y.serializedBytes=Le(l),y.estimatedTokens=Math.ceil(y.serializedBytes/4)}for(let g=0;g<8;g++){let h=Le(l),w=Math.ceil(h/4);if(y.serializedBytes===h&&y.estimatedTokens===w)break;y.serializedBytes=h,y.estimatedTokens=w}if(Le(l)>r)throw new RangeError(`response budget ${r} cannot preserve the ${e} response contract; narrow the request or increase the budget`);return l}import as from"node:child_process";import kr from"node:crypto";import fe from"node:fs";import ce from"node:path";var cs=4,Yl=32,Sr=16*1024,Ql=1024*1024,Zg=20,Jg=new Set([".git",".knodin","node_modules"]);function ck(t){let e=Math.min(t.byteBudget??65536,(t.tokenBudget??16384)*4);return Math.max(1,Math.min(t.itemBudget??100,Math.floor(e/256)))}var Yg=[".circleci/config.yml",".github/workflows",".gitlab-ci.yml",".mcp.json",".vscode/mcp.json","AGENTS.md","CLAUDE.md","Jenkinsfile","azure-pipelines.yml","sonar-project.properties"],Qg=[{path:"lefthook.yml",manager:"lefthook",readPaths:["lefthook.yml"]},{path:"lefthook.yaml",manager:"lefthook",readPaths:["lefthook.yaml"]},{path:".husky",manager:"husky",readPaths:[".husky/pre-commit",".husky/commit-msg",".husky/pre-push"]},{path:".pre-commit-config.yaml",manager:"pre-commit",readPaths:[".pre-commit-config.yaml"]}],ey=64*1024;function ty(t,e){try{let n=/^[^@/:]+@[^:]+:.+/.test(e)?e.replace(/^([^@/:]+)@([^:]+):/,"ssh://$1@$2/"):e,s=new URL(n),i=s.pathname.replace(/^\//,"").split("/")[0];return!s.hostname||!i?void 0:{name:t,host:s.hostname.toLowerCase(),owner:i}}catch{return}}async function lk(t){let e=[];for(let c of Yg)try{await fe.promises.lstat(ce.join(t,c)),e.push(c)}catch{}let n,s;for(let c of Qg)try{await fe.promises.lstat(ce.join(t,c.path)),n||(n=c.manager,s=!1);let a=ey;for(let l of c.readPaths){if(a===0||s)break;try{let u=await fe.promises.lstat(ce.join(t,l));if(!u.isFile())continue;let f=await fe.promises.open(ce.join(t,l),"r");try{let m=Buffer.alloc(Math.min(u.size,a)),{bytesRead:d}=await f.read(m,0,m.length,0);a-=d,s=/(?:^|[^\w-])aidev-track(?:$|[^\w-])/m.test(m.subarray(0,d).toString("utf8"))}finally{await f.close()}}catch{}}break}catch{}let i=[];try{let c=as.execFileSync(Ze(),["remote","-v"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:Sr}),a=new Set;for(let l of c.split(`
649
+ `)){let[u,f]=l.trim().split(/\s+/);if(!u||!f||a.has(u))continue;let m=ty(u,f);m&&(a.add(u),i.push(m))}}catch{}i.sort((c,a)=>c.name.localeCompare(a.name));let o=[e.includes(".github/workflows")?"github-actions":void 0,e.includes(".gitlab-ci.yml")?"gitlab-ci":void 0,e.includes(".circleci/config.yml")?"circleci":void 0,e.includes("azure-pipelines.yml")?"azure-pipelines":void 0,e.includes("Jenkinsfile")?"jenkins":void 0].filter(c=>!!c),r=e.filter(c=>c==="AGENTS.md"||c==="CLAUDE.md");return{...n?{hookManager:n}:{},...e.length?{markerFiles:e}:{},...i.length?{remotes:i}:{},...o.length?{ciProviders:o}:{},...r.length?{agentConfigs:r}:{},...s===void 0?{}:{aidevTrackReferenced:s}}}function uk(t,e,n){return e?{...t,signals:n}:t}function ny(t){return as.execFileSync(Ze(),["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}function ls(t){return t instanceof Error?t.message:String(t)}function vr(t){if(!Number.isInteger(t)||t<0||t>Yl)throw new Error(`knodin repos: --depth must be an integer between 0 and ${Yl}`)}function nu(t){let e=as.execFileSync(Ze(),["worktree","list","--porcelain","-z"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),n=[];for(let s of e.split("\0"))if(s.startsWith("worktree "))n.push({path:ce.resolve(s.slice(9)),main:n.length===0});else if(s.startsWith("prunable ")){let i=n.at(-1);i&&(i.stale=s.slice(9))}return n}async function sy(t,e={}){let n=e.depth??cs,s=e.linkedWorktrees??"skip",i=await iu(t,n,s),o=(await Promise.all(t.map(async m=>{try{return await fe.promises.realpath(ce.resolve(m))}catch{return ce.resolve(m)}}))).sort((m,d)=>m.localeCompare(d)),r=new Map;for(let m of i.repositories)try{let d=nu(m),y=d.find(({main:g})=>g)?.path??m;for(let g of d)r.set(g.path,y)}catch{r.set(m,m)}let c=new Set(i.repositories),a=i.repositories.filter(m=>(r.get(m)??m)===m),l=a.filter(m=>!a.some(d=>d!==m&&m.startsWith(`${d}${ce.sep}`))).sort((m,d)=>m.localeCompare(d)),u=i.repositories.map(m=>{let d=r.get(m)??m;if(d!==m)return{path:m,classification:"linked-worktree",mainWorktree:d};if(a.some(h=>h!==m&&m.startsWith(`${h}${ce.sep}`)&&c.has(h)))return{path:m,classification:"nested-repository",mainWorktree:m};let g=o.some(h=>l.find(w=>w===h||w.startsWith(`${h}${ce.sep}`))===m);return{path:m,classification:g?"main-worktree":"unrelated-repository",mainWorktree:m}}).filter(({classification:m})=>s==="include"||m!=="linked-worktree"),f={"linked-worktree":0,"main-worktree":1,"nested-repository":2,"unrelated-repository":3};return u.sort((m,d)=>f[m.classification]-f[d.classification]||m.path.localeCompare(d.path)),{repositories:u,issues:i.issues,emptyRoots:i.emptyRoots,staleLinkedWorktrees:i.staleWorktrees}}function qt(t,e,n){let s=t[e+1];if(s===void 0)throw new Error(`knodin repos: ${n} requires a value`);return s}function su(t,e){if(e!=="skip"&&e!=="include")throw new Error("knodin repos: --linked-worktrees must be skip or include");t.linkedWorktrees=e}function iy(t,e,n,s,i){if(t.startsWith("--include=")||t.startsWith("--exclude="))return(t.startsWith("--include=")?i.include:i.exclude).push(...t.slice(t.indexOf("=")+1).split(",").filter(Boolean)),e;if(t.startsWith("--depth="))return i.depth=Number(t.slice(8)),e;if(t.startsWith("--linked-worktrees="))return su(i,t.slice(19)),e;if(t.startsWith("--manifest="))return i.manifestPath=ce.resolve(n,t.slice(11)),e;if(t.startsWith("--"))throw new Error(`knodin repos: unknown option ${t}`);return s==="search"&&i.query===void 0?i.query=t:i.roots.push(ce.resolve(n,t)),e}function oy(t,e,n,s,i){let o=t[e]??"";switch(o){case"--dry-run":return i.dryRun=!0,e;case"--json":return i.json=!0,e;case"--signals":return i.signals=!0,e;case"--allow-partial":return i.allowPartial=!0,e;case"--root":return i.roots.push(ce.resolve(n,qt(t,e,o))),e+1;case"--include":case"--exclude":return(o==="--include"?i.include:i.exclude).push(...qt(t,e,o).split(",").filter(Boolean)),e+1;case"--items":case"--bytes":case"--tokens":{let r=Number(qt(t,e,o));if(!Number.isInteger(r)||r<1)throw new Error(`knodin repos: ${o} requires a positive integer`);return o==="--items"&&(i.itemBudget=r),o==="--bytes"&&(i.byteBudget=r),o==="--tokens"&&(i.tokenBudget=r),e+1}case"--cursor":return i.cursor=qt(t,e,o),e+1;case"--manifest":return i.manifestPath=ce.resolve(n,qt(t,e,o)),e+1;case"--depth":return i.depth=Number(qt(t,e,o)),e+1;case"--linked-worktrees":return su(i,qt(t,e,o)),e+1}return iy(o,e,n,s,i)}function ry(t){if(!t||!["discover","init","status","doctor","search"].includes(t))throw new Error("knodin repos requires discover, init, status, doctor, or search");return t}function dk(t,e){let n=ry(t[0]),s={depth:cs,dryRun:!1,json:!1,linkedWorktrees:"skip",roots:[],include:[],exclude:[],allowPartial:!1,signals:!1},i=1;for(;i<t.length;)i=oy(t,i,e,n,s)+1;if(vr(s.depth),n==="search"&&!s.query?.trim())throw new Error("knodin repos search requires a non-empty <query>");if(s.roots.length===0)if(n==="search")s.roots.push(e);else throw new Error(`knodin repos ${n} requires at least one <root>`);if(s.dryRun&&n!=="init")throw new Error(`knodin repos ${n}: --dry-run applies only to init`);if(s.manifestPath&&n!=="init")throw new Error(`knodin repos ${n}: --manifest applies only to init`);if(s.signals&&n!=="discover")throw new Error(`knodin repos ${n}: --signals applies only to discover`);if(n!=="search"&&n!=="init"&&(s.include.length>0||s.exclude.length>0))throw new Error(`knodin repos ${n}: repository selectors apply only to init or search`);if(n!=="search"&&!(n==="discover"&&s.signals)&&(s.allowPartial||s.itemBudget||s.byteBudget||s.tokenBudget||s.cursor))throw new Error(`knodin repos ${n}: search options apply only to search`);if(n==="discover"&&s.cursor)throw new Error("knodin repos discover: --cursor applies only to search");return{command:n,...s}}async function ay(t){let e=ce.join(t,".git");try{await fe.promises.lstat(e)}catch(s){if(s.code==="ENOENT")return;throw s}let n=await fe.promises.realpath(ny(t));return n===t?n:void 0}async function cy(t,e,n){if(t.level>=e)return[];let s=await fe.promises.readdir(t.directory,{withFileTypes:!0});return s.sort((i,o)=>i.name.localeCompare(o.name)),s.flatMap(i=>!i.isDirectory()||Jg.has(i.name)||i.name===".worktrees"&&n==="skip"?[]:[{directory:ce.join(t.directory,i.name),level:t.level+1}])}async function ly(t,e,n){let s=new Set,i=[],o=new Map,r=!1,c=[{directory:t,level:0}];for(let a of c)try{let l=await ay(a.directory);if(l){s.add(l),r=!0;for(let u of nu(l))(u.stale||!fe.existsSync(u.path))&&o.set(u.path,u.stale??"registered worktree path no longer exists")}c.push(...await cy(a,e,n))}catch(l){i.push({path:a.directory,message:ls(l)})}return{repositories:[...s],issues:i,staleWorktrees:[...o],found:r}}async function iu(t,e=cs,n="skip"){vr(e);let s=new Set,i=[],o=[],r=new Set,c=new Map;for(let f of[...t].sort((m,d)=>m.localeCompare(d))){let m;try{if(m=await fe.promises.realpath(ce.resolve(f)),!(await fe.promises.stat(m)).isDirectory())throw new Error("not a directory")}catch(y){i.push({path:ce.resolve(f),message:ls(y)});continue}if(r.has(m))continue;r.add(m);let d=await ly(m,e,n);for(let y of d.repositories)s.add(y);i.push(...d.issues);for(let[y,g]of d.staleWorktrees)c.set(y,g);!d.found&&d.issues.length===0&&o.push(m)}let a=[...s];a.sort((f,m)=>f.localeCompare(m));let l=[...i];l.sort((f,m)=>f.path.localeCompare(m.path));let u=[...o];return u.sort((f,m)=>f.localeCompare(m)),{repositories:a,issues:l,emptyRoots:u,staleWorktrees:[...c].map(([f,m])=>({path:f,message:m})).sort((f,m)=>f.path.localeCompare(m.path))}}function uy(t,e,n,s){let i=t[e]??"";switch(i){case"--dry-run":return s.dryRun=!0,e;case"--json":return s.json=!0,e;case"--depth":{let o=t[e+1];if(o===void 0)throw new Error("knodin fleet init: --depth requires a value");return s.depth=Number(o),e+1}}if(i.startsWith("--depth="))return s.depth=Number(i.slice(8)),e;if(i==="--worktrees"||i.startsWith("--worktrees=")){let o=i==="--worktrees"?t[e+1]:i.slice(12);if(o!=="skip"&&o!=="include")throw new Error("knodin fleet init: --worktrees must be skip or include");return s.worktrees=o,i==="--worktrees"?e+1:e}if(i.startsWith("--"))throw new Error(`knodin fleet init: unknown option ${i}`);return s.roots.push(ce.resolve(n,i)),e}function fk(t,e){if(t[0]!=="init")throw new Error("knodin fleet requires `init`");let n={depth:cs,dryRun:!1,json:!1,worktrees:"skip",roots:[]},s=1;for(;s<t.length;)s=uy(t,s,e,n)+1;if(vr(n.depth),n.roots.length===0)throw new Error("knodin fleet init requires at least one <root>");return n}function Er(t,e){try{return as.execFileSync(Ze(),e,{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function dy(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString().replace(/\/$/,"")}catch{return t.replace(/^[^@/\s]+@(?=[^:/\s]+[:/])/,"").replace(/\.git$/,"")}}function rs(t){let e=dy(Er(t,["remote","get-url","origin"])),n=Er(t,["rev-list","--max-parents=0","HEAD"]).split(`
650
+ `)[0]??"",s=e||`${n}:${ce.basename(t)}`;return`repo_${kr.createHash("sha256").update(s).digest("hex").slice(0,20)}`}var fy={".c":"c",".cc":"cpp",".cpp":"cpp",".cs":"csharp",".go":"go",".java":"java",".js":"javascript",".jsx":"javascript",".kt":"kotlin",".php":"php",".py":"python",".rb":"ruby",".rs":"rust",".swift":"swift",".ts":"typescript",".tsx":"typescript"};function wr(t,e){let n=t.findIndex(s=>s.localeCompare(e)>0);n===-1?t.push(e):t.splice(n,0,e),t.length>Zg&&t.pop()}function eu(t,e){t.count+=1;let n=fy[ce.extname(e).toLowerCase()];n&&!t.languages.includes(n)&&t.languages.push(n),["package.json","pyproject.toml","Cargo.toml","go.mod"].includes(e)&&t.manifests.add(e);let s=e.replaceAll("\\","/"),i=ce.posix.basename(s).toLowerCase(),o=/\.(?:md|mdx|txt|rst|adoc|asciidoc)$/i.test(i);/^readme(?:\.|$)/.test(i)&&wr(t.documentCandidates.readme,e),o&&(/^(?:architecture|design)(?:\.|$)/.test(i)||/^adr[-_.]?\d/i.test(i)||s.toLowerCase().split("/").some(r=>r==="architecture"||r==="adr"||r==="adrs"))&&wr(t.documentCandidates.architecture,e),o&&/^(?:roadmap|backlog)(?:\.|$)/.test(i)&&wr(t.documentCandidates.roadmap,e)}function my(t){return new Promise((e,n)=>{let s={count:0,languages:[],manifests:new Set,documentCandidates:{readme:[],architecture:[],roadmap:[]}},i=as.spawn(Ze(),["ls-files","-z"],{cwd:t,stdio:["ignore","pipe","pipe"]}),o=Buffer.alloc(0),r="",c=!1,a=l=>{c||(c=!0,i.kill(),n(l))};i.stdout.on("data",l=>{if(c)return;o=Buffer.concat([o,l]);let u=o.indexOf(0);for(;u>=0;)eu(s,o.subarray(0,u).toString("utf-8")),o=o.subarray(u+1),u=o.indexOf(0);o.length>Ql&&a(new Error(`git ls-files returned a path over ${Ql} bytes`))}),i.stderr.on("data",l=>{r.length<Sr&&(r+=l.toString("utf-8").slice(0,Sr-r.length))}),i.on("error",a),i.on("close",(l,u)=>{if(!c){if(c=!0,l!==0){let f=u?`signal ${u}`:`exit ${l??"unknown"}`,m=r.trim()||"no diagnostic";n(new Error(`git ls-files failed (${f}): ${m}`));return}o.length>0&&eu(s,o.toString("utf-8")),s.languages.sort((f,m)=>f.localeCompare(m)),e(s)}})})}function py(t,e){let n=[["package.json","name"],["pyproject.toml","name"],["Cargo.toml","name"],["go.mod","module"]],s=[];for(let[i,o]of n)if(e.has(i))try{let r=fe.readFileSync(ce.join(t,i),"utf-8");if(i==="package.json"){let c=JSON.parse(r).name;typeof c=="string"&&s.push(c)}else{let a=new RegExp(String.raw`^${o}[ \t]*(?:=[ \t]*)?["']?([^"'\s]+)`,"m").exec(r);a?.[1]&&s.push(a[1])}}catch{}return[...new Set(s)].sort((i,o)=>i.localeCompare(o))}function $i(t){try{return fe.realpathSync(ce.resolve(t))}catch{return ce.resolve(t)}}async function hy(t,e){try{let n=await e.status(t),s=await e.lastIndexedHead?.(t)??n.lastIndexedHead??"",i=n.indexGeneration===void 0?n.verification.verifiedAt:String(n.indexGeneration),o="healthy";return n.status!=="healthy"?o=n.status:n.coverage.sourceFiles>0&&n.coverage.indexedFiles===0?o="empty-index":n.lifecycle&&n.lifecycle.status!=="healthy"&&(o="lifecycle-degraded"),{health:o,lastIndexedHead:s,indexGeneration:i,errors:[],remediation:o==="healthy"?[]:n.repairSteps}}catch(n){return{health:"unknown",lastIndexedHead:"",indexGeneration:null,errors:[ls(n)],remediation:[]}}}function gy(t,e){return t===""?"unknown":t===e?"fresh":"stale"}async function yy(t,e){let n=rs(t.path),s=rs(t.mainWorktree),i=fe.existsSync(ce.join(t.path,".knodin","db.sqlite")),o=Er(t.path,["rev-parse","HEAD"]),r;try{r=await my(t.path)}catch(y){let g=`tracked-file inventory failed: ${ls(y)}`;return{schemaVersion:1,id:n,...e.exposePaths===!1?{}:{path:t.path},classification:t.classification,mainWorktreeId:s,initialization:i?"initialized":"not-initialized",health:"unknown",head:o,lastIndexedHead:"",freshness:"unknown",indexGeneration:null,languages:[],packageIdentities:[],systemMemberships:[...e.systemMemberships?.(t.path)??[]].sort((h,w)=>h.localeCompare(w)),documentCandidates:{readme:[],architecture:[],roadmap:[]},errors:[g],remediation:[`verify git ls-files in ${t.path}`,"retry repository inventory"]}}let c=r.count===0?"empty-repository":"not-initialized",a=i&&r.count>0?await hy(t.path,e):{health:c,lastIndexedHead:"",indexGeneration:null,errors:[],remediation:[]},l=[...a.remediation],{health:u,lastIndexedHead:f,indexGeneration:m,errors:d}=a;return u==="not-initialized"&&l.push(`knodin init --repo ${t.path}`),(u==="empty-index"||u==="repair-needed")&&l.push("knodin repair"),{schemaVersion:1,id:n,...e.exposePaths===!1?{}:{path:t.path},classification:t.classification,mainWorktreeId:s,initialization:i?"initialized":"not-initialized",health:u,head:o,lastIndexedHead:f,freshness:gy(f,o),indexGeneration:m,languages:r.languages,packageIdentities:py(t.path,r.manifests),systemMemberships:[...e.systemMemberships?.(t.path)??[]].sort((y,g)=>y.localeCompare(g)),documentCandidates:r.documentCandidates,errors:d,remediation:[...new Set(l)]}}function by(t){return Buffer.from(JSON.stringify({version:1,...t})).toString("base64url")}function wy(t,e){if(!t)return{repository:0,offset:0};try{let n=JSON.parse(Buffer.from(t,"base64url").toString("utf-8"));if(n.version!==1||n.hash!==e||!Number.isInteger(n.repository)||!Number.isInteger(n.offset)||(n.repository??-1)<0||(n.offset??-1)<0)throw new Error("invalid cursor");return{repository:n.repository??0,offset:n.offset??0}}catch{throw new Error("knodin repos search: cursor does not match this query and selection")}}function Sy(t,e,n){return t>0?"partial":e>0?"ok":n>0?"no-match":"unavailable"}function tu(t,e,n,s){return Jl(t,"repositories:search",{bytes:e,tokens:n,items:s},{bytes:e,tokens:n,items:s})}function Ey(t,e,n){return{repositoryId:t.id,...n===!1?{}:{repositoryPath:t.path},identity:e.identity,symbol:e.symbol,kind:e.kind,file:e.filePath,sourceEvidence:e.source.slice(0,4e3),sourceTruncated:e.source.length>4e3,confidence:e.rrfScore||e.similarity,freshness:t.freshness,health:"healthy"}}async function ky(t,e,n,s){let{query:i,itemLimit:o,effectiveBytes:r,results:c,omissions:a,selected:l,options:u}=s,f=await u.search(i,t.path??"",o-c.length+1,n);for(let[m,d]of f.results.entries()){if(c.length>=o)return{repository:e,offset:n+m};let y=Ey(t,d,u.exposePaths),g=JSON.stringify({results:[...c,y],omissions:a,repositories:l});if(Buffer.byteLength(g)>r)return{repository:e,offset:n+m};c.push(y)}if(f.hasMore)return{repository:e,offset:n+f.results.length}}async function vy(t,e,n,s,i,o){let r=[],c=[];for(let[a,l]of t.entries()){if(l.health!=="healthy"){c.push({repositoryId:l.id,state:l.health==="no-match"?"unknown":l.health,reason:l.errors[0]??`repository graph is ${l.health}`,remediation:l.remediation});continue}if(a<e.repository)continue;let u=a===e.repository?e.offset:0,f=await ky(l,a,u,{query:n,itemLimit:s,effectiveBytes:i,results:r,omissions:c,selected:t,options:o});if(f)return{results:r,omissions:c,next:f}}return{results:r,omissions:c}}async function mk(t,e,n){let s=await sy(t,n),i=new Set((n.include??[]).flatMap(S=>[S,$i(S)])),o=new Set((n.exclude??[]).flatMap(S=>[S,$i(S)])),r=new Map(s.repositories.map(S=>[S.path,rs(S.path)])),c=(S,E)=>E===S.path||$i(E)===S.path||E===r.get(S.path),a=(n.include??[]).filter(S=>!s.repositories.some(E=>c(E,S)));if(a.length>0)throw new Error(`knodin repos search: include selector(s) matched no discovered repository: ${a.join(", ")}`);let l=s.repositories.filter(S=>{let E=r.get(S.path)??rs(S.path);return(i.size===0||i.has(E)||i.has(S.path))&&!o.has(E)&&!o.has(S.path)}),u=[];for(let S of l)u.push(await yy(S,n));let f=kr.createHash("sha256").update(JSON.stringify([e,u.map(({id:S})=>S)])).digest("hex").slice(0,20),m=wy(n.cursor,f),d=Math.min(Math.max(n.itemBudget??25,1),1e3);if(n.byteBudget!==void 0&&n.byteBudget<1024)throw new Error("knodin repos search: byte budget must be at least 1024");if(n.tokenBudget!==void 0&&n.tokenBudget<256)throw new Error("knodin repos search: token budget must be at least 256");let y=n.byteBudget??65536,g=n.tokenBudget??16384,h=Math.min(y,g*4),{results:w,omissions:k,next:_}=await vy(u,m,e,d,h,n);if(k.length>0&&n.allowPartial!==!0)return tu({schemaVersion:1,status:"unavailable",query:e,results:[],repositories:u,omissions:k},y,g,d);let v={schemaVersion:1,status:Sy(k.length,w.length,u.length),query:e,results:w,repositories:u,omissions:k,..._?{cursor:by({hash:f,..._})}:{}};return tu(v,y,g,d)}function xy(t,e){return e?"managed installation updated; healthy graph preserved":t?"managed installation and graph updated":"managed installation and graph initialized"}function Ty(t,e,n){return e&&n?{repository:t,status:"skipped",message:"dry-run: would verify graph health before deciding whether to update"}:{repository:t,status:"skipped",plannedStatus:e?"updated":"initialized",message:e?"dry-run: would update managed installation":"dry-run: would initialize"}}function Ry(t,e,n){return kr.createHash("sha256").update(JSON.stringify({repositories:t,depth:e,worktrees:n})).digest("hex")}function $y(t,e){if(!t||!fe.existsSync(t))return null;let n=JSON.parse(fe.readFileSync(t,"utf-8"));if(n.schemaVersion!==1||n.signature!==e||!Array.isArray(n.completed))throw new Error(`knodin repos init: ${t} does not match this repository selection and policy`);return n}function _y(t,e,n){fe.mkdirSync(ce.dirname(t),{recursive:!0,mode:448});let s=`${t}.${process.pid}.tmp`,i={schemaVersion:1,signature:e,completed:n,updatedAt:new Date().toISOString()};fe.writeFileSync(s,`${JSON.stringify(i,null,2)}
651
+ `,{encoding:"utf-8",mode:384,flag:"wx"}),fe.renameSync(s,t)}async function Ay(t,e){try{if(e.indexMode?.(t)==="provenance-only")return{repository:t,status:"skipped",message:"provenance-only policy: graph indexing and lifecycle hooks require an explicit index: full override"};if(!e.dryRun&&e.isolatedInitialize)return await e.isolatedInitialize(t);let n=fe.existsSync(ce.join(t,".knodin","db.sqlite")),s=ts(t),i=s?.scope??"personal",o=[...new Set([...e.agents??[],...s?.agents??[]])],r=await Rl(t,e.command,i);if(e.dryRun)return Ty(t,n,r);let c=n?await e.status(t):null;if(r&&c?.status==="healthy")return{repository:t,status:"already-current",message:"managed installation and graph are healthy"};let a=c?.status==="healthy";return await Tl(t,{command:e.command,index:a?async()=>{}:e.index,scope:i,agents:o}),{repository:t,status:n?"updated":"initialized",message:xy(n,a)}}catch(n){return{repository:t,status:"failed",message:ls(n)}}}async function pk(t,e){let n=e.depth??cs,s=e.worktrees??"skip",i=await iu(t,n,s),o=new Map(i.repositories.map(g=>[g,rs(g)])),r=(g,h)=>h===g||$i(h)===g||h===o.get(g),c=(e.include??[]).filter(g=>!i.repositories.some(h=>r(h,g)));if(c.length>0)throw new Error(`knodin repos init: include selector(s) matched no discovered repository: ${c.join(", ")}`);let a=i.repositories.filter(g=>((e.include?.length??0)===0||(e.include??[]).some(h=>r(g,h)))&&!(e.exclude??[]).some(h=>r(g,h))),l=Ry(a,n,s),u=e.manifestPath?ce.resolve(e.manifestPath):void 0,f=$y(u,l),m=new Map((f?.completed??[]).map(g=>[g.repository,g])),d=i.issues.map(g=>({repository:g.path,status:"failed",message:`discovery failed: ${g.message}`}));for(let g of i.emptyRoots)d.push({repository:g,status:"skipped",message:`no Git worktree found within depth ${n}`});for(let g of i.staleWorktrees)d.push({repository:g.path,status:"skipped",message:`stale worktree metadata: ${g.message}`});for(let g of a){let h=m.get(g);if(h){d.push(h);continue}let w=await Ay(g,e);d.push(w),u&&!e.dryRun&&(w.status==="initialized"||w.status==="updated"||w.status==="already-current")&&(m.set(g,w),_y(u,l,[...m.values()]))}d.sort((g,h)=>g.repository.localeCompare(h.repository));let y=d.filter(({peakRssBytes:g})=>g!==void 0);return{exitCode:d.some(({status:g})=>g==="failed")?1:0,worktrees:s,results:d,resources:{isolated:e.isolatedInitialize!==void 0&&!e.dryRun,peakRepositoryRssBytes:y.length>0?Math.max(...y.map(({peakRssBytes:g})=>g??0)):null,memoryLimitBytes:y.find(({memoryLimitBytes:g})=>g!==void 0)?.memoryLimitBytes??null,memoryLimitFailures:d.filter(({message:g})=>g.includes("memory ceiling exceeded")).length},...u?{manifest:{path:u,resumed:f!==null,completed:m.size,total:a.length}}:{}}}function hk(t){let e=Math.max(15,...t.results.map(({status:r})=>r.length)),n=t.results.map(r=>{let c=r.message?` \u2014 ${r.message}`:"";return`${r.status.padEnd(e)} ${r.repository}${c}`}),s=new Map;for(let r of t.results)s.set(r.status,(s.get(r.status)??0)+1);let o=["initialized","updated","already-current","skipped","failed"].filter(r=>s.has(r)).map(r=>`${s.get(r)} ${r}`);return n.push(`${t.results.length} entries: ${o.join(", ")}; .worktrees policy=${t.worktrees}`),`${n.join(`
652
+ `)}
653
+ `}import Uy from"node:crypto";import Ye from"node:fs";import Wy from"node:os";import Ee from"node:path";import{parseDocument as qy}from"yaml";import Fy from"node:child_process";import Ly from"node:crypto";import _i from"node:fs";import Ai from"node:path";var Ny=5e3,Cy=2*1024*1024;function Fi(t){try{return Fy.execFileSync(Ze(),["ls-files","-z"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split("\0").filter(Boolean).sort((e,n)=>e.localeCompare(n)).slice(0,Ny)}catch{return[]}}function Li(t,e){return t.slice(0,e).split(`
654
+ `).length}function Je(t,e,n){let s=[];for(let i of t.matchAll(e))s.push({...n(i),line:Li(t,i.index??0)});return s}function Oy(t,e){if(t==="package.json")try{let n=JSON.parse(e),s=[];for(let i of["dependencies","devDependencies","peerDependencies"]){let o=n[i];if(!(typeof o!="object"||o===null))for(let r of Object.keys(o).sort((c,a)=>c.localeCompare(a)))s.push({type:"depends_on",target:`pkg:npm/${encodeURIComponent(r)}`,line:Li(e,Math.max(e.indexOf(`"${r}"`),0)),adapter:"package-manifest",confidence:1})}return s}catch{return[]}return t==="go.mod"?e.split(/\r?\n/).flatMap((n,s)=>{let[i,o]=n.trim().split(/\s+/,2);return!i?.includes(".")||!o?.startsWith("v")?[]:[{type:"depends_on",target:`pkg:golang/${i}`,line:s+1,adapter:"package-manifest",confidence:1}]}):t==="Cargo.toml"||t==="pyproject.toml"?Je(e,/^([A-Za-z0-9_.-]+)[ \t]*=[ \t]*(?:["'{])/gm,n=>({type:"depends_on",target:`pkg:${t==="Cargo.toml"?"cargo":"pypi"}/${n[1]}`,adapter:"package-manifest",confidence:.9})):[]}function Iy(t,e){let n=t.toLowerCase();return/openapi|swagger/.test(n)&&/\.(json|ya?ml)$/.test(n)?Je(e,/^[ \t]{0,8}(\/[^:\s]+)[ \t]*:/gm,s=>({type:"provides_api",target:`openapi:${s[1]}`,adapter:"openapi",confidence:1})):/asyncapi/.test(n)?Je(e,/^[ \t]{2,8}([^:\s]+)[ \t]*:/gm,s=>({type:"publishes_event",target:`asyncapi:${s[1]}`,adapter:"asyncapi",confidence:.9})):n.endsWith(".graphql")||n.endsWith(".gql")?Je(e,/^[ \t]*(?:type|interface|input)[ \t]+([A-Za-z_]\w*)/gm,s=>({type:"provides_api",target:`graphql:${s[1]}`,adapter:"graphql",confidence:1})):n.endsWith(".proto")?Je(e,/^[ \t]*service[ \t]+([A-Za-z_]\w*)/gm,s=>({type:"provides_api",target:`protobuf:${s[1]}`,adapter:"protobuf",confidence:1})):[]}function My(t,e){let n=t.toLowerCase(),s=[];return n.endsWith(".tf")&&s.push(...Je(e,/^[ \t]*source[ \t]*=[ \t]*"([^"\r\n]+)"/gm,i=>({type:"depends_on",target:`terraform:${i[1]}`,adapter:"terraform",confidence:1})),...Je(e,/^[ \t]*backend[ \t]+"([^"\r\n]+)"/gm,i=>({type:"reads_output",target:`terraform-state:${i[1]}`,adapter:"terraform",confidence:.9})),...Je(e,/^[ \t]*output[ \t]+"([^"\r\n]+)"/gm,i=>({type:"provisions",target:`terraform-output:${i[1]}`,adapter:"terraform",confidence:1}))),/\.(ya?ml|tpl)$/.test(n)&&s.push(...Je(e,/^[ \t]*image:[ \t]*["']?([^"'\s]+)["']?/gm,i=>({type:"uses_image",target:`oci:${i[1]}`,adapter:n.includes("helm")||n.includes("chart")?"helm":"kubernetes",confidence:1}))),s}function Py(t,e){let n=t.toLowerCase();if(n.endsWith(".map"))try{let s=JSON.parse(e);return Array.isArray(s.sources)?s.sources.flatMap(i=>typeof i=="string"?[{type:"generated_from",target:`file:${i}`,line:1,adapter:"source-map",confidence:1}]:[]):[]}catch{return[]}if(/(?:^|\/)(?:bom|sbom)(?:\.[^/]*)?\.json$/.test(n))try{let s=JSON.parse(e);return Array.isArray(s.components)?s.components.flatMap(i=>{if(!i||typeof i!="object")return[];let o=i.purl;return typeof o=="string"?[{type:"depends_on",target:o,line:Li(e,Math.max(e.indexOf(o),0)),adapter:"cyclonedx-sbom",confidence:1}]:[]}):[]}catch{return[]}return n.endsWith(".intoto.jsonl")||n.includes("provenance")?Je(e,/"uri"[ \t]*:[ \t]*"([^"\r\n]+)"/g,s=>({type:"generated_from",target:s[1]??"unknown",adapter:"slsa-provenance",confidence:1})):[]}function Dy(t,e,n){let s=[];for(let[i,o]of n)for(let r of t.matchAll(/(["'`])([^"'`\n]+)\1/g)){let c=r[2];!c||Ai.resolve(e,c)!==Ai.resolve(i)||s.push({type:"references_path",target:o,line:Li(t,r.index??0),adapter:"exact-path-literal",confidence:1})}return s.push(...Je(t,/\b(?:process\.env\.|os\.environ\[["'])([A-Z][A-Z0-9_]{2,})/g,i=>({type:"reads_config",target:`config:${i[1]}`,adapter:"configuration-key",confidence:.85}))),s}function ou(t,e,n=new Map){let s=[];for(let i of Fi(e)){let o=Ai.join(e,i),r;try{r=_i.statSync(o)}catch{continue}if(!r.isFile()||r.size>Cy)continue;let c;try{c=_i.readFileSync(o,"utf-8")}catch{continue}let a=[...Oy(i,c),...Iy(i,c),...My(i,c),...Py(i,c),...Dy(c,e,n)];for(let l of a)s.push({type:l.type,from:t,to:l.target,targetIdentity:l.target,evidence:{location:`${i}:${l.line}`,line:l.line,adapter:l.adapter,kind:"extracted",confidence:l.confidence,freshness:"current",indexGeneration:null}})}return s.sort((i,o)=>`${i.from}\0${i.type}\0${i.to}\0${i.evidence.location}`.localeCompare(`${o.from}\0${o.type}\0${o.to}\0${o.evidence.location}`))}async function jy(t){let e=Ly.createHash("sha256");return await new Promise((n,s)=>{let i=_i.createReadStream(t);i.on("data",o=>e.update(o)),i.on("error",s),i.on("end",n)}),e.digest("hex")}function zy(t){let e=new Map,n=[...t].sort((s,i)=>s.id.localeCompare(i.id));for(let s of n)for(let i of Fi(s.path)){let o=Ai.join(s.path,i);try{let r=_i.statSync(o);if(!r.isFile())continue;let c=e.get(r.size)??[];c.push({repositoryId:s.id,file:i,absolute:o}),e.set(r.size,c)}catch{}}return e}async function By(t){let e=new Map;for(let n of t){let s=await jy(n.absolute),i=e.get(s)??[];i.push(n),e.set(s,i)}return e}function Hy(t){if(new Set(t.map(({repositoryId:i})=>i)).size<2)return[];let n=[...t].sort((i,o)=>`${i.repositoryId}\0${i.file}`.localeCompare(`${o.repositoryId}\0${o.file}`)),s=n[0];return s?n.slice(1).flatMap(i=>i.repositoryId===s.repositoryId?[]:[{type:"duplicate_candidate",from:i.repositoryId,to:s.repositoryId,targetIdentity:s.repositoryId,evidence:{location:i.file,adapter:"streaming-sha256",kind:"inferred",confidence:1,freshness:"current",indexGeneration:null}}]):[]}async function ru(t){let e=[];for(let n of zy(t).values()){if(n.length<2)continue;let s=await By(n);for(let i of s.values())e.push(...Hy(i))}return e.sort((n,s)=>`${n.from}\0${n.to}\0${n.evidence.location}`.localeCompare(`${s.from}\0${s.to}\0${s.evidence.location}`))}var Gy=["depends_on","provides_api","consumes_api","deploys","provisions","reads_output","references_path","reads_config","publishes_event","consumes_event","uses_image","generated_from","vendored_from","mirror_of","duplicate_candidate"];function mt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Vy(t){let e=qy(Ye.readFileSync(t,"utf-8"),{prettyErrors:!0,strict:!0,uniqueKeys:!0});if(e.errors.length>0)throw new Error(`${t}: ${e.errors.map(({message:n})=>n).join("; ")}`);return e.toJS({maxAliasCount:25})}function lu(t){try{return Vy(t)}catch(e){if(e.code==="ENOENT")return{};throw e}}function Sn(t,e){if(typeof t!="string"||t.trim()==="")throw new Error(`${e} must be a string`);return t}function au(t){let e=t.replaceAll("\\","/");for(;e.endsWith("/");)e=e.slice(0,-1);e||=".";let n=Ee.posix.basename(e).replace(/[^a-zA-Z0-9._-]+/g,"-")||"repository",s=Uy.createHash("sha256").update(e).digest("hex").slice(0,10);return`legacy-${n}-${s}`}function Ky(t,e){if(t===void 0)return"source";if(t==="source"||t==="generated"||t==="vendored"||t==="mirrored")return t;throw new Error(`repositories[${e}].role is unsupported`)}function Xy(t,e){let n=mt(t),s=Ky(n.role,e),i=n.index==="full"||n.index==="provenance-only"?n.index:void 0,o=s==="generated"||s==="vendored"||s==="mirrored";return{id:Sn(n.id,`repositories[${e}].id`),role:s,indexMode:i??(o?"provenance-only":"full"),policySource:i?"knodin.yaml":"role-default"}}function Zy(t,e){let n=mt(t),s=(Array.isArray(n.components)?n.components:[]).map((i,o)=>{let r=mt(i);return{id:Sn(r.id,`systems[${e}].components[${o}].id`),repository:typeof r.repository=="string"?r.repository:void 0,type:typeof r.type=="string"?r.type:"component"}});return{id:Sn(n.id,`systems[${e}].id`),components:s}}function Jy(t,e,n){let s=Ee.join(t,".knodin","federation.json"),i;try{i=mt(JSON.parse(Ye.readFileSync(s,"utf-8")))}catch(u){if(u.code==="ENOENT")return!1;throw u}let o=Array.isArray(i.repos)?i.repos:[],r=e.find(({path:u})=>u===t),c=e.length===1?e[0]:void 0,a=r?.id??(c&&c.path===void 0?c.id:void 0)??au(".");e.some(({id:u})=>u===a)||e.push({id:a,role:"source",indexMode:"full",policySource:"role-default",path:t,pathSource:"legacy-federation"});let l=!1;for(let u of o){if(typeof u!="string")continue;l=!0;let f=Ee.resolve(t,u),m=au(u);e.some(d=>d.path===f)||e.push({id:m,role:"source",indexMode:"full",policySource:"role-default",path:f,pathSource:"legacy-federation"}),n.push({type:"depends_on",from:a,to:m,targetIdentity:m,evidence:{location:".knodin/federation.json",adapter:"legacy-federation",kind:"compatibility",confidence:1,freshness:"current",indexGeneration:null}})}return l}function Yy(t,e){let n=mt(lu(Ee.join(e,"knodin","repositories.yaml"))),s=mt(n.repositories);for(let i of t){let o=s[i.id];if(typeof o=="string"){if(!Ee.isAbsolute(o))throw new Error(`personal repository path for ${i.id} must be absolute; team config keeps paths out of knodin.yaml`);i.path=Ee.normalize(o),i.pathSource="personal-config"}}}function xr(t,e,n){return t.path?t.path:e.length===1&&t.id===e[0]?.id?n:void 0}function Qy(t,e){let n=new Map(t.map(s=>[xr(s,t,e)??"",s.id]).filter(([s])=>s!==""&&Ye.existsSync(s)));return t.flatMap(s=>{let i=xr(s,t,e);return!i||!Ye.existsSync(i)?[]:ou(s.id,i,n)})}function eb(t,e){let n=t.trim();if(!n||n.startsWith("#"))return[];let[s,...i]=n.split(/\s+/);return s?i.flatMap(o=>o==="linguist-generated"||o==="linguist-generated=true"?[{category:"generated",pattern:s,location:`.gitattributes:${e+1}`,source:"gitattributes"}]:o==="linguist-vendored"||o==="linguist-vendored=true"?[{category:"vendored",pattern:s,location:`.gitattributes:${e+1}`,source:"gitattributes"}]:[]):[]}function tb(t){let e=[],n=Ee.join(t,".gitattributes");try{let s=Ye.readFileSync(n,"utf-8").slice(0,1048576).split(/\r?\n/);for(let[i,o]of s.entries())e.push(...eb(o,i))}catch(s){if(s.code!=="ENOENT")throw s}return e}function nb(t){let e=t.toLowerCase();if(!(!e.endsWith(".map")&&!/(?:^|\/)(?:bom|sbom)(?:\.[^/]*)?\.json$/.test(e)&&!e.endsWith(".intoto.jsonl")&&!e.includes("provenance")))return{category:e.includes("bom")||e.endsWith(".intoto.jsonl")||e.includes("provenance")?"sbom-slsa":"build-metadata",pattern:t,location:t,source:"metadata"}}function sb(t,e){let n;try{n=Ye.openSync(Ee.join(t,e),"r");let s=Buffer.alloc(4096),i=Ye.readSync(n,s,0,s.length,0),o=s.subarray(0,i).toString("utf-8").toLowerCase();return!o.includes("@generated")&&!o.includes("code generated")&&!o.includes("auto-generated")?void 0:{category:"generated",pattern:e,location:`${e}:1`,source:"generated-header"}}catch{return}finally{n!==void 0&&Ye.closeSync(n)}}function ib(t){let e=tb(t);for(let n of Fi(t)){let s=nb(n)??sb(t,n);s&&e.push(s)}return e}function ob(t,e){let n=mt(t),s=Sn(n.type,`relationships[${e}].type`);if(!Gy.includes(s))throw new Error(`relationships[${e}].type is unsupported: ${s}`);let i=Sn(n.from,`relationships[${e}].from`),o=Sn(n.to,`relationships[${e}].to`),r=mt(n.evidence),c=typeof r.confidence=="number"&&r.confidence>=0&&r.confidence<=1?r.confidence:1;return{type:s,from:i,to:o,targetIdentity:o,evidence:{location:typeof r.location=="string"&&r.location?r.location:"knodin.yaml",adapter:"knodin-yaml",kind:"declared",confidence:c,freshness:"current",indexGeneration:null}}}function Ak(t,e={}){let n=Ee.resolve(t),s=mt(lu(Ee.join(n,"knodin.yaml")));if(s.schemaVersion!==void 0&&s.schemaVersion!==1)throw new Error("knodin.yaml: schemaVersion must be 1");let i=(Array.isArray(s.repositories)?s.repositories:[]).map((u,f)=>Xy(u,f)),o=(Array.isArray(s.systems)?s.systems:[]).map((u,f)=>Zy(u,f)),r=(Array.isArray(s.relationships)?s.relationships:[]).map((u,f)=>ob(u,f)),c=e.xdgConfigHome??process.env.XDG_CONFIG_HOME??Ee.join(Wy.homedir(),".config");Yy(i,c);let a=Jy(n,i,r);for(let u of i){let f=xr(u,i,n);f&&Ye.existsSync(f)&&(u.policyEvidence=ib(f))}r.push(...Qy(i,n)),i.sort((u,f)=>u.id.localeCompare(f.id)),o.sort((u,f)=>u.id.localeCompare(f.id));let l=[...new Map(r.map(u=>[`${u.from}\0${u.type}\0${u.to}\0${u.evidence.location}`,u])).values()];return l.sort((u,f)=>`${u.from}\0${u.type}\0${u.to}`.localeCompare(`${f.from}\0${f.type}\0${f.to}`)),{schemaVersion:1,repositories:i,systems:o,relationships:l,compatibility:{legacyFederation:a}}}function uu(t){let e=[],n=new Set(t.repositories.map(({id:o})=>o));for(let o of t.systems)for(let r of o.components)r.repository&&!n.has(r.repository)&&e.push({code:"unresolved-repository",identity:r.repository,message:`${o.id}/${r.id} references unknown repository ${r.repository}`});for(let o of t.repositories)o.path&&!Ye.existsSync(o.path)&&e.push({code:"missing-checkout",identity:o.id,message:`${o.id} checkout does not exist at the configured personal path`});let s=new Set(t.systems.flatMap(({components:o})=>o.map(({id:r})=>r))),i=new Set([...n,...s]);for(let o of t.relationships)e.push(...rb(o,i));return{valid:e.length===0,requiresPartial:e.length>0,issues:e}}function rb(t,e){let n=[],s=["pkg:","openapi:","asyncapi:","graphql:","protobuf:","terraform:","terraform-state:","terraform-output:","oci:","config:"],i=t.evidence.kind==="extracted"&&s.some(o=>t.to.startsWith(o));return(!e.has(t.from)||!e.has(t.to)&&!i)&&n.push({code:"invalid-relationship",identity:`${t.from}->${t.to}`,message:`${t.type} references an unknown source or target identity`}),t.evidence.confidence<.8&&n.push({code:"low-confidence-relationship",identity:`${t.from}->${t.to}`,message:`${t.type} confidence ${t.evidence.confidence} is below the system-query threshold`}),t.evidence.freshness==="stale"&&n.push({code:"configuration-drift",identity:`${t.from}->${t.to}`,message:`${t.type} evidence is stale and must be refreshed`}),n}async function ab(t,e,n,s,i){if(!e.repository)return[];let r=t.repositories.find(({id:c})=>c===e.repository)?.path??(t.repositories.length===1?s:void 0);if(!r)return i.some(({identity:c})=>c===e.repository)?[]:[{code:"missing-checkout",identity:e.repository,message:`${e.id} has no personal checkout mapping`}];try{let c=await n(r),a=c.lifecycle?.status;if(c.status==="healthy"&&(!a||a==="healthy"))return[];let l=a&&a!=="healthy"?` and lifecycle is ${a}`:"";return[{code:"unavailable-component",identity:e.id,message:`${e.id} graph is ${c.status}${l}`}]}catch(c){return[{code:"unavailable-component",identity:e.id,message:`${e.id} health is unknown: ${c instanceof Error?c.message:String(c)}`}]}}async function Fk(t,e,n,s){let i=uu(t),o=[...i.issues],r=t.systems.find(({id:c})=>c===e);if(!r)return i;for(let c of r.components)o.push(...await ab(t,c,n,s,o));return{valid:o.length===0,requiresPartial:o.length>0,issues:o}}function Lk(t,e,n=!1,s){let i=t.systems.find(({id:u})=>u===e);if(!i)return{status:"not-found",systemId:e,available:t.systems.map(({id:u})=>u)};let o=s??uu(t);if(!o.valid&&!n)return{status:"unavailable",systemId:e,relationships:[],omissions:o.issues};let r=new Set(o.issues.filter(({code:u})=>u==="unresolved-repository"||u==="missing-checkout").map(({identity:u})=>u)),c=new Set(i.components.filter(({repository:u})=>u!==void 0&&r.has(u)).map(({id:u})=>u)),a=new Set(i.components.map(({id:u})=>u)),l=t.relationships.filter(({from:u,to:f})=>(a.has(u)||a.has(f))&&!c.has(u)&&!c.has(f));return{status:o.valid?"ok":"partial",systemId:e,relationships:l,omissions:o.issues}}function Nk(t,e){let n=Ee.resolve(e),s=new Set(t.repositories.filter(({path:i})=>i!==void 0&&Ee.resolve(i)===n).map(({id:i})=>i));return s.size===0&&t.repositories.length===1&&t.repositories[0]&&s.add(t.repositories[0].id),t.systems.filter(({components:i})=>i.some(({repository:o})=>o!==void 0&&s.has(o))).map(({id:i})=>i).sort((i,o)=>i.localeCompare(o))}function Ck(t,e){let n=Ee.resolve(e),s=t.repositories.find(({path:i})=>i&&Ee.resolve(i)===n);return s?s.indexMode:t.repositories.length===1&&t.repositories[0]?t.repositories[0].indexMode:"full"}async function Ok(t){let e=t.repositories.filter(s=>s.path!==void 0&&Ye.existsSync(s.path)).map(({id:s,path:i})=>({id:s,path:i}));if(e.length<2)return t;let n=await ru(e);return n.length===0?t:{...t,relationships:[...t.relationships,...n].sort((s,i)=>`${s.from}\0${s.type}\0${s.to}\0${s.evidence.location}`.localeCompare(`${i.from}\0${i.type}\0${i.to}\0${i.evidence.location}`))}}function cu(t,e){if(t.repositories.some(({id:n})=>n===e))return e;for(let n of t.systems){let s=n.components.find(({id:i})=>i===e);if(s?.repository)return s.repository}}function cb(t,e){let n=Ee.resolve(e),s=new Set(t.repositories.filter(({path:i})=>i&&Ee.resolve(i)===n).map(({id:i})=>i));return s.size===0&&t.repositories.length===1&&t.repositories[0]&&s.add(t.repositories[0].id),s}function lb(t,e,n){let s=cb(t,e),i=new Set(t.systems.flatMap(({components:o})=>o.filter(({repository:r})=>r&&s.has(r)).map(({id:r})=>r)));return t.relationships.filter(o=>{let r=cu(t,o.from);if(!r||s.has(r))return!1;let c=cu(t,o.to);return c!==void 0&&s.has(c)||i.has(o.to)||n===""&&c===void 0||n!==void 0&&(o.to===n||o.targetIdentity===n)})}function Ik(t,e,n,s,i){if(!i||typeof i!="object")return i;let o=i,r=lb(t,e,s);if(r.length===0)return i;let c=r.map(u=>({type:u.type,from:u.from,to:u.to,targetIdentity:u.targetIdentity,evidence:u.evidence}));if(o.crossRepositoryEvidence={incoming:c,interpretation:"Incoming system evidence is source-scoped; non-exact or low-confidence evidence blocks safe-deletion claims."},n!=="dead_code"||!Array.isArray(o.results))return o;let l=o.results.flatMap(u=>{if(!u||typeof u!="object")return[u];let f=u,m=typeof f.symbol=="string"?f.symbol:"";return r.some(y=>y.evidence.confidence>=.8&&y.evidence.freshness==="current"&&(y.to===m||y.targetIdentity===m))?[]:[{...f,deletionSafe:!1,crossRepositoryEvidence:c}]});return o.results=l,o.count=l.length,o}import ub from"node:child_process";import mu from"node:fs";import pu from"node:path";var db=t=>new Promise(e=>setTimeout(e,t)),fb=500;function mb(t){try{let e=Number(mu.readFileSync(pu.join(t,".knodin","hooks","refresh.lock","pid"),"utf-8"));return!Number.isInteger(e)||e<=0?!1:(process.kill(e,0),!0)}catch{return!1}}function pb(t){let e=pu.join(t,".knodin","hooks","background-index.sh");if(mu.statSync(e).mode&73){let n=ub.spawn(e,[],{cwd:t,stdio:"ignore",detached:process.platform!=="win32",windowsHide:!0});n.once("error",()=>{}),n.unref()}}function hb(t){if(Object.values(t.orphaned).some(n=>n>0))return!0;let e=["indexed file no longer exists: ","indexed file is no longer eligible: ","indexed snapshot differs from disk: "];return t.missing.records.some(n=>!e.some(s=>n.startsWith(s)))}function gb(t,e,n,s,i){if(e>=n||Xt(t).queuedEvents===0||mb(t)||e-s<fb)return s;try{i(t)}catch{}return e}function du(t){return t.status==="healthy"&&t.freshness.state==="fresh"?"fresh":t.status==="repair-needed"&&hb(t)?"repair-needed":t.freshness.state==="unknown"?"unknown":null}async function yb(t,e,n){return(n.status==="stale"||n.status==="repair-needed")&&n.freshness.state!=="queued"?(await t.query("stats","",e),Ki(e,await t.status(e,{audit:"deep"}))):n}function fu(t,e,n,s){return{status:t,waitedMs:Date.now()-e,polls:n,graph:s}}async function Bk(t,e,n=3e4,s=pb){let i=Date.now(),o=0,r=Number.NEGATIVE_INFINITY;for(;;){o++;let c=Date.now()-i;r=gb(e,c,n,r,s);let a=Ki(e,await t.status(e,{audit:"cached"})),l=du(a);if(l||(a=await yb(t,e,a),l=du(a),l))return fu(l,i,o,a);let u=Date.now()-i;if(u>=n)return{status:"timeout",waitedMs:u,polls:o,graph:a};await db(Math.min(100,n-u))}}export{Eb as a,Fr as b,Rb as c,$b as d,_b as e,ku as f,Ab as g,Fb as h,Lb as i,re as j,Ib as k,Hb as l,Ub as m,Wb as n,Jb as o,Yb as p,qi as q,Qb as r,ew as s,tw as t,nw as u,aw as v,cw as w,Ki as x,bw as y,Lw as z,Nw as A,Cw as B,mo as C,Ow as D,Iw as E,Mw as F,Pw as G,Gw as H,Jw as I,Mn as J,KS as K,XS as L,Ze as M,oE as N,aE as O,cE as P,pE as Q,Qh as R,hE as S,ar as T,TE as U,ts as V,RE as W,yg as X,Tl as Y,NE as Z,CE as _,OE as $,mr as aa,IE as ba,ME as ca,PE as da,DE as ea,BE as fa,HE as ga,UE as ha,KE as ia,YE as ja,Jl as ka,ck as la,lk as ma,uk as na,sy as oa,dk as pa,fk as qa,yy as ra,mk as sa,pk as ta,hk as ua,Ak as va,Fk as wa,Lk as xa,Nk as ya,Ck as za,Ok as Aa,Ik as Ba,Bk as Ca};