scip-query 0.10.4 → 0.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{program as ws}from"commander";import{realpathSync as xb}from"fs";import{fileURLToPath as wO}from"url";import{createRequire as g_}from"module";import{fileURLToPath as hf}from"url";import{statSync as vb}from"fs";function Oe(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,...Rb(e.config.dbPath)}}function Rb(e){try{let t=vb(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function j(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",i=t.like?"AND relative_path LIKE ?":"",r=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
2
+ import{program as Is}from"commander";import{realpathSync as Db}from"fs";import{fileURLToPath as FO}from"url";import{createRequire as v_}from"module";import{fileURLToPath as Sf}from"url";import{statSync as Pb}from"fs";function Oe(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,...Nb(e.config.dbPath)}}function Nb(e){try{let t=Pb(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function j(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",i=t.like?"AND relative_path LIKE ?":"",r=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
3
3
  FROM documents
4
4
  WHERE 1 = 1
5
5
  ${e.pathExclusionsFor("documents")}
6
6
  ${n}
7
7
  ${i}
8
- ORDER BY relative_path`,...r).map(a=>a.relative_path),s=t.extensions?o.filter(a=>t.extensions.some(c=>a.toLowerCase().endsWith(c.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}function kb(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Is(e,t){let n=kb(t);return j(e,{like:n,includeIgnored:!1}).map(i=>({relativePath:i}))}import{extname as Dl}from"path";var wb={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb"};function W(e){return wb[Dl(e).toLowerCase()]??null}function yt(e){return Dl(e).toLowerCase()===".vue"}var Il=[];function Et(e){e.groups.length>0&&Il.push(e)}function Ps(e,t){let n=new Set(t.groups);for(let i of Il)i.groups.some(r=>n.has(r))&&(t.file!==void 0&&i.clearFile?i.clearFile(e,t.file):i.clearAll(e))}function Pl(){let e=new WeakMap;return{cache:e,ensure(t){let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}}}function U(e,t){let{cache:n,ensure:i}=Pl(),r={get(o,s,a){let c=i(o);if(c.has(s))return c.get(s);let l=a();return c.set(s,l),l},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)},size(o){return n.get(o)?.size??0}};return Et({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}function Y(e,t){let n=new WeakMap,i={get(r,o){let s=n.get(r);if(s)return s.value;let a=o();return n.set(r,{value:a}),a},invalidate(r){n.delete(r)},has(r){return n.has(r)}};return Et({name:e,groups:t.clearGroups,clearAll:r=>i.invalidate(r)}),i}var Lb={clearGroups:["whole-project","source-file"]};function Lr(e){return Kt(e,Lb)}function Kt(e,t){let{cache:n,ensure:i}=Pl(),r={get(o,s,a,c){let l=i(o),u=l.get(s);if(u&&u.source===a)return u.value;let d=c();return l.set(s,{source:a,value:d}),d},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return Et({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}import{createRequire as Db}from"module";var ke=Db(import.meta.url),Dr=null,Nl=!1;function Ib(){if(Nl)return null;if(Dr)return Dr;try{return Dr=ke("tree-sitter"),Dr}catch{return Nl=!0,null}}var El=new Map,Ns=new Set;function Pb(e){if(Ns.has(e))return null;let t=El.get(e);if(t)return t;let n;try{switch(e){case"rust":n=ke("tree-sitter-rust");break;case"typescript":n=ke("tree-sitter-typescript").typescript;break;case"tsx":n=ke("tree-sitter-typescript").tsx;break;case"javascript":n=ke("tree-sitter-javascript");break;case"python":n=ke("tree-sitter-python");break;case"java":n=ke("tree-sitter-java");break;case"kotlin":n=ke("tree-sitter-kotlin");break;case"scala":n=ke("tree-sitter-scala");break;case"ruby":n=ke("tree-sitter-ruby");break;case"c":n=ke("tree-sitter-c");break;case"cpp":n=ke("tree-sitter-cpp");break;case"csharp":n=ke("tree-sitter-c-sharp");break;case"php":n=ke("tree-sitter-php").php;break;case"vb":{let i=ke("tree-sitter-vb-dotnet");n=i.language??i;break}}}catch{return Ns.add(e),null}return El.set(e,n),n}var Tl=new Map;function Nb(e){let t=Tl.get(e);if(t)return t;let n=Pb(e);if(!n)return null;let i=Ib();if(!i)return null;let r=new i;try{r.setLanguage(n)}catch{return Ns.add(e),null}return Tl.set(e,r),r}function Eb(e,t){return e.parse(i=>i>=t.length?null:t.slice(i,Math.min(t.length,i+16384)))}function wi(e,t){let n=Nb(e);if(!n)return null;try{return Eb(n,t)}catch{return null}}import{existsSync as Tb,readFileSync as _b}from"fs";import{join as Fb}from"path";var $b=U("source-text",{clearGroups:["whole-project","source-file"]}),Ab=U("source-lines",{clearGroups:["whole-project","source-file"]});function M(e,t){let n=t.replace(/\\/g,"/");return $b.get(e,n,()=>{let i=Fb(e.config.projectRoot,n);return Tb(i)?_b(i,"utf-8"):""})}function _e(e,t){let n=t.replace(/\\/g,"/");return Ab.get(e,n,()=>{let i=M(e,n);return i?i.split(`
9
- `):[]})}var Mb=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function Li(e){let t=Mb.exec(e);return t?t[1]??"":null}function Ir(e,t,n){if(n<=0)return!1;let i=_e(e,t);if(i.length===0)return!1;for(let r=n-1;r>=0&&r>=n-5;r-=1){let o=(i[r]??"").trim();if(o!==""){if(Li(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as qb}from"@vue/compiler-sfc";import{posix as Es}from"path";import{parse as Ob}from"@vue/compiler-sfc";var jb=Lr("vue-sfc-units");function Nr(e,t){let n=$l(t),i=M(e,n);return jb.get(e,n,i,()=>Bb(e,n,i))}function $l(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Ts(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Jt(e){return!e||e.body.length===0?0:e.body.split(`
10
- `).length}function Bb(e,t,n){let i={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return i;let r;try{r=Ob(n,{filename:t})}catch(s){return i.errors.push(Fl(s)),i}i.errors.push(...r.errors.map(Fl));let{descriptor:o}=r;return o.template&&(i.template=Pr(e,t,"template",o.template)),o.script&&i.scripts.push(_l(e,t,o.script,!1)),o.scriptSetup&&i.scripts.push(_l(e,t,o.scriptSetup,!0)),i.styles=o.styles.map(s=>Pr(e,t,"style",s)),i.customBlocks=o.customBlocks.map(s=>Pr(e,t,"custom",s)),i.errors.push(...[i.template,...i.scripts,...i.styles,...i.customBlocks].flatMap(s=>s?.errors??[])),i}function _l(e,t,n,i){let r=Pr(e,t,"script",n);return{...r,kind:"script",setup:i,astLanguage:Ts(r.lang)}}function Pr(e,t,n,i){let r=Vb(i.attrs),o=typeof r.lang=="string"?r.lang:null,s=typeof r.src=="string"?r.src:typeof i.src=="string"?i.src:void 0;if(s){let c=Hb(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:r,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=M(e,c),u=l?Math.max(0,l.split(`
11
- `).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:r,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,i.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:r,lang:o,body:i.content,startLine:a,endLine:Math.max(a,i.loc.end.line-1),errors:[]}}function Hb(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let i=$l(Es.normalize(Es.join(Es.dirname(e),n)));return i===".."||i.startsWith("../")?null:i}function Vb(e){return{...e}}function Fl(e){return e instanceof Error?e.message:String(e)}function Er(e){let t=qb(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let i=Ts(n.lang??null);return i?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:i}:null}var Al=Kt("ast-trees",{clearGroups:["whole-project","source-file"]});function me(e,t){if(yt(t))return Ub(e,t);let n=W(t);if(!n)return null;let i=M(e,t);return i?Al.get(e,t,i,()=>wi(n,i)):null}function Ub(e,t){let n=M(e,t);return n?Al.get(e,t,n,()=>{let i=Er(n);if(!i)return null;let r=`
12
- `.repeat(i.startLine)+i.body;return wi(i.language,r)}):null}function An(e,t){let n=Wb(e,t);if(!n)return null;let i=$n(n);return i?{calleeLeaf:i,memberAccess:Gb(n),line:e.startPosition.row}:null}function Wb(e,t){if(t==="rust")return e.type==="call_expression"?e.childForFieldName("function")??e.namedChild(0):e.type==="macro_invocation"?e.childForFieldName("macro")??e.namedChild(0):null;if(t==="python")return e.type!=="call"?null:e.childForFieldName("function")??e.namedChild(0);if(t==="typescript"||t==="tsx"||t==="javascript"){if(e.type==="call_expression")return e.childForFieldName("function")??e.namedChild(0);if(e.type==="new_expression")return e.childForFieldName("constructor")??e.namedChild(0)}return null}function Gb(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function $n(e){switch(e.type){case"identifier":case"type_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?$n(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?$n(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as zb}from"crypto";import{createRequire as Kb}from"module";import{dirname as Jb,join as Qb}from"path";import Xb from"better-sqlite3";var Yb=Kb(import.meta.url),Zb="evidence.db",Tr=new WeakMap,ey=U("evidence-content-hash",{clearGroups:["whole-project","source-file"]});function ty(){for(let e of["../package.json","../../package.json"])try{return Yb(e).version}catch{}return"0.0.0"}var _r=ty();function _s(e){return zb("sha256").update(e).digest("hex")}function Qt(e,t,n){return ey.get(e,t,()=>_s(n))}function Ml(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function Di(e){if(Tr.has(e))return Tr.get(e)??null;let t=null;try{let n=new Xb(Qb(Jb(e.config.dbPath),Zb));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
8
+ ORDER BY relative_path`,...r).map(a=>a.relative_path),s=t.extensions?o.filter(a=>t.extensions.some(c=>a.toLowerCase().endsWith(c.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}function Eb(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Es(e,t){let n=Eb(t);return j(e,{like:n,includeIgnored:!1}).map(i=>({relativePath:i}))}import{extname as Nl}from"path";var Tb={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb"};function W(e){return Tb[Nl(e).toLowerCase()]??null}function yt(e){return Nl(e).toLowerCase()===".vue"}var El=[];function Et(e){e.groups.length>0&&El.push(e)}function Ts(e,t){let n=new Set(t.groups);for(let i of El)i.groups.some(r=>n.has(r))&&(t.file!==void 0&&i.clearFile?i.clearFile(e,t.file):i.clearAll(e))}function Tl(){let e=new WeakMap;return{cache:e,ensure(t){let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}}}function U(e,t){let{cache:n,ensure:i}=Tl(),r={get(o,s,a){let c=i(o);if(c.has(s))return c.get(s);let l=a();return c.set(s,l),l},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)},size(o){return n.get(o)?.size??0}};return Et({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}function Y(e,t){let n=new WeakMap,i={get(r,o){let s=n.get(r);if(s)return s.value;let a=o();return n.set(r,{value:a}),a},invalidate(r){n.delete(r)},has(r){return n.has(r)}};return Et({name:e,groups:t.clearGroups,clearAll:r=>i.invalidate(r)}),i}var _b={clearGroups:["whole-project","source-file"]};function Dr(e){return Kt(e,_b)}function Kt(e,t){let{cache:n,ensure:i}=Tl(),r={get(o,s,a,c){let l=i(o),u=l.get(s);if(u&&u.source===a)return u.value;let d=c();return l.set(s,{source:a,value:d}),d},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return Et({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}import{createRequire as $b}from"module";var ke=$b(import.meta.url),Ir=null,_l=!1;function Fb(){if(_l)return null;if(Ir)return Ir;try{return Ir=ke("tree-sitter"),Ir}catch{return _l=!0,null}}var $l=new Map,_s=new Set;function Ab(e){if(_s.has(e))return null;let t=$l.get(e);if(t)return t;let n;try{switch(e){case"rust":n=ke("tree-sitter-rust");break;case"typescript":n=ke("tree-sitter-typescript").typescript;break;case"tsx":n=ke("tree-sitter-typescript").tsx;break;case"javascript":n=ke("tree-sitter-javascript");break;case"python":n=ke("tree-sitter-python");break;case"java":n=ke("tree-sitter-java");break;case"kotlin":n=ke("tree-sitter-kotlin");break;case"scala":n=ke("tree-sitter-scala");break;case"ruby":n=ke("tree-sitter-ruby");break;case"c":n=ke("tree-sitter-c");break;case"cpp":n=ke("tree-sitter-cpp");break;case"csharp":n=ke("tree-sitter-c-sharp");break;case"php":n=ke("tree-sitter-php").php;break;case"vb":{let i=ke("tree-sitter-vb-dotnet");n=i.language??i;break}}}catch{return _s.add(e),null}return $l.set(e,n),n}var Fl=new Map;function Mb(e){let t=Fl.get(e);if(t)return t;let n=Ab(e);if(!n)return null;let i=Fb();if(!i)return null;let r=new i;try{r.setLanguage(n)}catch{return _s.add(e),null}return Fl.set(e,r),r}function Ob(e,t){return e.parse(i=>i>=t.length?null:t.slice(i,Math.min(t.length,i+16384)))}function wi(e,t){let n=Mb(e);if(!n)return null;try{return Ob(n,t)}catch{return null}}import{existsSync as jb,readFileSync as Bb}from"fs";import{join as Hb}from"path";var Vb=U("source-text",{clearGroups:["whole-project","source-file"]}),qb=U("source-lines",{clearGroups:["whole-project","source-file"]});function M(e,t){let n=t.replace(/\\/g,"/");return Vb.get(e,n,()=>{let i=Hb(e.config.projectRoot,n);return jb(i)?Bb(i,"utf-8"):""})}function _e(e,t){let n=t.replace(/\\/g,"/");return qb.get(e,n,()=>{let i=M(e,n);return i?i.split(`
9
+ `):[]})}var Ub=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function Li(e){let t=Ub.exec(e);return t?t[1]??"":null}function Pr(e,t,n){if(n<=0)return!1;let i=_e(e,t);if(i.length===0)return!1;for(let r=n-1;r>=0&&r>=n-5;r-=1){let o=(i[r]??"").trim();if(o!==""){if(Li(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as Qb}from"@vue/compiler-sfc";import{posix as $s}from"path";import{parse as Wb}from"@vue/compiler-sfc";var Gb=Dr("vue-sfc-units");function Er(e,t){let n=Ol(t),i=M(e,n);return Gb.get(e,n,i,()=>zb(e,n,i))}function Ol(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Fs(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Jt(e){return!e||e.body.length===0?0:e.body.split(`
10
+ `).length}function zb(e,t,n){let i={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return i;let r;try{r=Wb(n,{filename:t})}catch(s){return i.errors.push(Ml(s)),i}i.errors.push(...r.errors.map(Ml));let{descriptor:o}=r;return o.template&&(i.template=Nr(e,t,"template",o.template)),o.script&&i.scripts.push(Al(e,t,o.script,!1)),o.scriptSetup&&i.scripts.push(Al(e,t,o.scriptSetup,!0)),i.styles=o.styles.map(s=>Nr(e,t,"style",s)),i.customBlocks=o.customBlocks.map(s=>Nr(e,t,"custom",s)),i.errors.push(...[i.template,...i.scripts,...i.styles,...i.customBlocks].flatMap(s=>s?.errors??[])),i}function Al(e,t,n,i){let r=Nr(e,t,"script",n);return{...r,kind:"script",setup:i,astLanguage:Fs(r.lang)}}function Nr(e,t,n,i){let r=Jb(i.attrs),o=typeof r.lang=="string"?r.lang:null,s=typeof r.src=="string"?r.src:typeof i.src=="string"?i.src:void 0;if(s){let c=Kb(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:r,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=M(e,c),u=l?Math.max(0,l.split(`
11
+ `).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:r,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,i.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:r,lang:o,body:i.content,startLine:a,endLine:Math.max(a,i.loc.end.line-1),errors:[]}}function Kb(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let i=Ol($s.normalize($s.join($s.dirname(e),n)));return i===".."||i.startsWith("../")?null:i}function Jb(e){return{...e}}function Ml(e){return e instanceof Error?e.message:String(e)}function Tr(e){let t=Qb(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let i=Fs(n.lang??null);return i?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:i}:null}var jl=Kt("ast-trees",{clearGroups:["whole-project","source-file"]});function me(e,t){if(yt(t))return Xb(e,t);let n=W(t);if(!n)return null;let i=M(e,t);return i?jl.get(e,t,i,()=>wi(n,i)):null}function Xb(e,t){let n=M(e,t);return n?jl.get(e,t,n,()=>{let i=Tr(n);if(!i)return null;let r=`
12
+ `.repeat(i.startLine)+i.body;return wi(i.language,r)}):null}function An(e,t){let n=Yb(e,t);if(!n)return null;let i=Fn(n);return i?{calleeLeaf:i,memberAccess:Zb(n),line:e.startPosition.row}:null}function Yb(e,t){if(t==="rust")return e.type==="call_expression"?e.childForFieldName("function")??e.namedChild(0):e.type==="macro_invocation"?e.childForFieldName("macro")??e.namedChild(0):null;if(t==="python")return e.type!=="call"?null:e.childForFieldName("function")??e.namedChild(0);if(t==="typescript"||t==="tsx"||t==="javascript"){if(e.type==="call_expression")return e.childForFieldName("function")??e.namedChild(0);if(e.type==="new_expression")return e.childForFieldName("constructor")??e.namedChild(0)}return null}function Zb(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Fn(e){switch(e.type){case"identifier":case"type_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?Fn(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Fn(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as ey}from"crypto";import{createRequire as ty}from"module";import{dirname as ny,join as iy}from"path";import ry from"better-sqlite3";var oy=ty(import.meta.url),sy="evidence.db",_r=new WeakMap,ay=U("evidence-content-hash",{clearGroups:["whole-project","source-file"]});function cy(){for(let e of["../package.json","../../package.json"])try{return oy(e).version}catch{}return"0.0.0"}var $r=cy();function As(e){return ey("sha256").update(e).digest("hex")}function Qt(e,t,n){return ay.get(e,t,()=>As(n))}function Bl(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function Di(e){if(_r.has(e))return _r.get(e)??null;let t=null;try{let n=new ry(iy(ny(e.config.dbPath),sy));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
13
13
  CREATE TABLE IF NOT EXISTS file_evidence (
14
14
  kind TEXT NOT NULL,
15
15
  relative_path TEXT NOT NULL,
@@ -29,15 +29,15 @@ import{program as ws}from"commander";import{realpathSync as xb}from"fs";import{f
29
29
  );
30
30
  `),t={evidence:n,readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
31
31
  WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
32
- (relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?")}}catch(n){Ml("disabled (open failed)",n)}return Tr.set(e,t),t}function Ii(e,t,n){Ml(`disabled (${t})`,n),Tr.set(e,null)}function Fr(e,t,n,i){let r=Di(e);if(!r)return null;try{return r.readFileEvidence.get(t,n,i,_r)?.payload??null}catch(o){return Ii(e,"file_evidence read",o),null}}function $r(e,t,n,i,r){let o=Di(e);if(o)try{o.writeFileEvidence.run(t,n,i,_r,r)}catch(s){Ii(e,"file_evidence write",s)}}function Ol(e){let t=Di(e);if(!t)return 0;try{return t.evidence.prepare("SELECT COUNT(*) AS count FROM semantic_callees").get()?.count??0}catch(n){return Ii(e,"semantic_callees count",n),0}}function jl(e,t,n,i,r){let o=Di(e);if(!o)return null;try{return o.readCallees.get(t,n,i,r,_r)?.payload??null}catch(s){return Ii(e,"semantic_callees read",s),null}}function Bl(e,t){if(t.length===0)return;let n=Di(e);if(n)try{n.evidence.transaction(()=>{let i=new Set;for(let r of t){let o=`${r.relativePath}\0${r.contentHash}`;i.has(o)||(i.add(o),n.dropStaleCallees.run(r.relativePath,r.contentHash)),n.writeCallees.run(r.relativePath,r.symbol,r.contentHash,r.depsDigest,_r,r.payload)}})()}catch(i){Ii(e,"semantic_callees write",i)}}function Pi(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var ny=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Ar(e,t){let n=ry(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:ql(n.functionNode),params:Hl(n.functionNode),paramsEndLine:Vl(n.functionNode),isLiteralPassthrough:Ul(n.functionNode,t)};if(!iy(e.type,t))return null;let i=e.childForFieldName("name")??e.namedChildren.find(r=>r.type==="identifier"||r.type==="property_identifier");return i?{name:i.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:ql(e),params:Hl(e),paramsEndLine:Vl(e),isLiteralPassthrough:Ul(e,t)}:null}function Wl(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Hl(e){let t=Wl(e);if(!t)return[];let n=[];for(let i of t.namedChildren){if(Pi(i))continue;if(i.type==="identifier"){n.push({name:i.text,simple:!0});continue}let r=i.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(i.text),o=i.childForFieldName("pattern");if(!r&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=i.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function Vl(e){let t=Wl(e);return t?t.endPosition.row:e.startPosition.row}function iy(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?ny.has(e):!1}function ry(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}return null}function ql(e){let t=e.namedChildren.find(i=>i.type==="parameters"||i.type==="formal_parameters");if(!t)return 0;let n=0;for(let i of t.namedChildren)Pi(i)||(n+=1);return n}function Ul(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let i=n.namedChildren.filter(d=>!Pi(d));if(i.length!==1)return!1;let r=i[0],o=null;if(r.type==="return_statement"||r.type==="expression_statement"?o=r.namedChild(0)??null:t==="rust"&&(r.type==="call_expression"||r.type==="macro_invocation")&&(o=r),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!Pi(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let m=d.namedChildren.find(p=>p.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var oy=new Set(["identifier","type_identifier","field_identifier"]),sy=new Set(["identifier"]),ay=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),cy=new Set(["rust","python"]),ly=/\{([^{}]*)\}/g,uy=/\b([A-Za-z_][\w]*)\b/g;function Gl(e,t){return dy(t).has(e.type)}function zl(e,t){return cy.has(t)&&e.type==="string_content"}function Fs(e){let t=0;for(let i of e.values()){let r=i[i.length-1];r!==void 0&&r>t&&(t=r)}let n=new Array(t+1);for(let i=0;i<=t;i+=1)n[i]=new Set;for(let[i,r]of e)for(let o of r)n[o].add(i);return n}function dy(e){return e==="rust"?oy:e==="python"?sy:ay}function Kl(e,t){let n=e.startPosition.row;for(let i of e.text.matchAll(ly)){let r=i[1]??"";for(let o of r.matchAll(uy))o[1]&&t(o[1],n)}}var my=[/\bdefault\s*=\s*"([^"]+)"/g,/\bwith\s*=\s*"([^"]+)"/g,/\bserialize_with\s*=\s*"([^"]+)"/g,/\bdeserialize_with\s*=\s*"([^"]+)"/g,/\bskip_serializing_if\s*=\s*"([^"]+)"/g,/\bgetter\s*=\s*"([^"]+)"/g,/\brename_all_with\s*=\s*"([^"]+)"/g,/\bschema_with\s*=\s*"([^"]+)"/g],py=/^#!?\[\s*serde\s*\(/,fy=/^#!?\[\s*schemars\s*\(/,gy=/^#!?\[\s*validate\s*\(/,hy=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Jl(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let i=e.childForFieldName("function")??e.namedChild(0);if(!i)return;let r=$n(i);if(!r||!hy.has(r))return;let o=e.namedChildren.find(c=>c.type==="arguments");if(!o)return;let s=o.namedChild(0);if(!s||s.type!=="string")return;let a=s.namedChildren.find(c=>c.type==="string_fragment");a&&n.add(a.text)}function Ql(e,t){let n=py.test(e),i=fy.test(e),r=gy.test(e);if(!(!n&&!i&&!r))for(let o of my){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function Xl(e,t){let n=new Map,i=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},r=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{r.has(l.type)&&l.text!==a&&i(l.text,a);for(let u of l.children)c(u)};for(let l of s.children)c(l)};if(t==="rust")for(let s of e.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let a=s.namedChildren.find(l=>l.type==="type_identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="field_declaration_list"||l.type==="enum_variant_list"||l.type==="ordered_field_declaration_list");c&&o(c,a),s.type==="type_item"&&o(s,a)}else if(t==="python")for(let s of e.rootNode.descendantsOfType("class_definition")){let a=s.namedChildren.find(l=>l.type==="identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="block");if(c)for(let l of c.descendantsOfType("type"))for(let u of l.descendantsOfType("identifier"))u.text!==a&&i(u.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var by=Kt("source-facts",{clearGroups:["whole-project","source-file"]});function oe(e,t){let n=M(e,t);if(!n)return null;let i=yy(t,n);return i?by.get(e,t,n,()=>Sy(e,t,i,n)):null}function yy(e,t){return yt(e)?Er(t)?.language??null:W(e)}function Sy(e,t,n,i){let r=Qt(e,t,i),o=Fr(e,"source-facts",t,r);if(o){let c=Cy(o);if(c&&c.language===n)return c}let s=me(e,t);if(!s)return null;let a=Ry(s,n);return $r(e,"source-facts",t,r,xy(a)),a}function xy(e){let t={language:e.language,callables:e.callables,callSites:e.callSites,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,i])=>[n,[...i]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function Cy(e){try{let t=JSON.parse(e),n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,typeContainerMap:new Map(t.typeContainerMap.map(([i,r])=>[i,new Set(r)])),identifierLineMap:n,identifiersByLine:Fs(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function $s(e,t,n,i){let r=oe(e,t);return r?vy(r,n,i)?.isLiteralPassthrough??!0:!0}function vy(e,t,n){return e.callables.find(i=>i.startLine===t&&i.endLine===n)??null}function Ry(e,t){let n=[],i=[],r=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=Ar(l,t);u&&n.push(u);let d=An(l,t);d&&i.push(d),Jl(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Ql(l.text,r),Gl(l,t)&&a(l.text,l.startPosition.row),zl(l,t)&&Kl(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:i,typeContainerMap:Xl(e,t),identifierLineMap:s,identifiersByLine:Fs(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:r,crossLanguageDispatchNames:o}}var Yl=new Set(["rust","typescript","tsx","javascript","python"]);function As(e,t){let n=oe(e,t);return!n||!Yl.has(n.language)?null:n.callables.map(i=>({name:i.name,startLine:i.startLine,endLine:i.endLine}))}function Mn(e,t){let n=oe(e,t);return!n||!Yl.has(n.language)?null:n.callSites}function Ms(e,t){return oe(e,t)?.typeContainerMap??new Map}import{ElementTypes as ky,NodeTypes as eu,parse as wy}from"@vue/compiler-dom";import{parse as Fj}from"@vue/compiler-sfc";function Mr(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var Ly=Lr("vue-template-facts"),Dy=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),Iy=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),Py=new Set(["div","span","template"]),Ny=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function tu(e,t){let n=t.replace(/\\/g,"/"),i=M(e,n);return Ly.get(e,n,i,()=>Ey(n,Nr(e,n).template))}function Ey(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let i;try{i=wy(t.body,{comments:!1})}catch{return n}let r=new Set,o=s=>{s.trim()&&r.add(s)};return nu(i.children,t.startLine,n,o),n.structuralTokens=[...r].sort(),n}function nu(e,t,n,i){for(let r of e)r.type===eu.ELEMENT&&(Ty(r,t,n,i),nu(r.children,t,n,i))}function Ty(e,t,n,i){let r=By(e.tag),o={tag:e.tag,normalized:r,kind:jy(e),startLine:On(t,e.loc.start.line),endLine:On(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),i(`component:${r}`)):o.kind==="builtin"?(n.builtinTags.push(o),i(`builtin:${r}`)):(n.nativeTags.push(o),Py.has(e.tag)||i(`native:${e.tag}`));for(let s of e.props)_y(s,t,n,i)}function _y(e,t,n,i){if(e.type===eu.ATTRIBUTE){let a=e.value?.content??null,c=Zl("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),i(`prop:${e.name}`);return}let r=$y(e),o=iu(e.exp),s=Zl(Fy(e.name),r,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),i(`prop:${r}`);break;case"event":n.events.push(s),i(`event:${r}`);break;case"slot":n.slots.push(s),i(`slot:${r}`);break;case"directive":n.directives.push(s),i(`directive:${r}`);break}o&&Ay(o,t,e.loc.start.line,n,i)}function Zl(e,t,n,i,r,o){return{kind:e,name:t,value:n,startLine:On(i,r),endLine:On(i,o)}}function Fy(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function $y(e){let t=iu(e.arg);return t||e.name}function iu(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function Ay(e,t,n,i,r){for(let o of My(e)){let s={name:o,startLine:On(t,n),endLine:On(t,n)};i.expressionIdentifiers.push(s),r(`id:${o}`)}}function My(e){let t=new Set,n=Oy(e),i=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,r;for(;r=i.exec(n);){let o=r[0];Ny.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function Oy(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function jy(e){let t=e.tag;return e.tagType===ky.COMPONENT?"component":Dy.has(t)?"builtin":Iy.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function By(e){return Mr(e,/[-_:]/)}function On(e,t){return e+Math.max(0,t-1)}import{readdirSync as Hy}from"fs";import{execFileSync as Vy}from"child_process";import{extname as Os,join as qy}from"path";var Uy=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],ru=[".vue"],ou=new Set(Uy.map(e=>e.toLowerCase())),Wy=[...ou].sort().join(","),js=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function De(e,t={}){let n=t.includeIndexed??!0,i=t.includeAuxiliary??!0,r=t.extensions?.map(c=>c.toLowerCase()),o=r?new Set(r):ou,s=r?[...o].sort().join(","):Wy,a=`${n?"1":"0"}|${i?"1":"0"}|${s}`;return Gy.get(e,a,()=>{let c=new Set;if(n)for(let l of j(e,{includeIgnored:!1}))o.has(Os(l).toLowerCase())&&c.add(l);if(i)for(let l of zy(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}var Gy=U("source-files",{clearGroups:[]});function zy(e,t){return Ky(e,t)??Jy(e,t)}function Ky(e,t){try{let n=Vy("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),i=new Set;for(let r of n.split(`
33
- `)){let o=r.trim();o&&t.has(Os(o).toLowerCase())&&i.add(o)}return i}catch{return null}}function Jy(e,t){let n=new Set,i=r=>{let o=r?qy(e,r):e,s;try{s=Hy(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!js.has(a.name)){if(a.isDirectory()){i(r?`${r}/${a.name}`:a.name);continue}t.has(Os(a.name).toLowerCase())&&n.add(r?`${r}/${a.name}`:a.name)}};return i(""),n}var Qy=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),Xy=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),Yy=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),Zy=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),eS=new Set(["catch","for","function","if","return","switch","while"]);function su(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=Jt(n),n.external&&(t.externalLineCount+=Jt(n),t.externalScriptPaths.push(n.sourcePath));for(let r of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:r});if(!n.body||!n.astLanguage){n.astLanguage||t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:`Unsupported Vue script language: ${n.lang??"unknown"}`});continue}t.imports.push(...rS(n));let i=wi(n.astLanguage,n.body);i?nS(n,i.rootNode,t):iS(n,t)}return tS(t),t.externalScriptPaths=cu(t.externalScriptPaths),t}function tS(e){e.composables=jn(e,"composable"),e.stores=jn(e,"store"),e.reactivity=jn(e,"reactivity"),e.lifecycle=jn(e,"lifecycle"),e.requests=jn(e,"request"),e.macros=jn(e,"macro")}function jn(e,t){return cu(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function nS(e,t,n){let i=new Set,r=new Set,o=s=>{let a=Ar(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;r.has(l)||(r.add(l),n.functions.push({name:a.name,sourcePath:e.sourcePath,startLine:e.startLine+a.startLine,endLine:e.startLine+a.endLine,setup:e.setup}))}let c=An(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;i.has(l)||(i.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:au(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function iS(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let i=n[1];!i||eS.has(i)||t.calls.push({name:i,sourcePath:e.sourcePath,line:e.startLine+Or(e.body,n.index??0),categories:au(i),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let i=n[1];if(!i)continue;let r=e.startLine+Or(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}for(let n of e.body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/g)){let i=n[1];if(!i)continue;let r=e.startLine+Or(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}}function rS(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let i=n[1]?.trim(),r=n[2];if(!i||!r)continue;let o=e.startLine+Or(e.body,n.index??0);for(let s of oS(i))t.push({local:s,source:r,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function oS(e){let t=[],i=e.split(",").map(s=>s.trim()).filter(Boolean)[0];i&&!i.startsWith("{")&&!i.startsWith("*")&&t.push(i);let r=/\{([^}]*)\}/.exec(e)?.[1];if(r)for(let s of r.split(",")){let a=s.trim();if(!a)continue;let c=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(a)?.[1];t.push(c??a.replace(/^type\s+/,"").trim())}let o=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1];return o&&t.push(o),t.filter(s=>/^[A-Za-z_$][\w$]*$/.test(s))}function au(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),Qy.has(e)&&t.push("reactivity"),Xy.has(e)&&t.push("lifecycle"),Yy.has(e)&&t.push("request"),Zy.has(e)&&t.push("macro"),t}function Or(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e.charCodeAt(i)===10&&(n+=1);return n}function cu(e){return[...new Set(e)].sort()}var sS=new Set(["in","key","of"]),aS=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]);function Bn(e,t={}){let n=De(e,{extensions:[".vue"]}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(r=>cS(e,r)).filter(r=>(t.minTemplateTokens===void 0||r.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function cS(e,t){let n=t.replace(/\\/g,"/"),i=Nr(e,n),r=tu(e,n),o=su(i),s=uS(r),a=r.expressionIdentifiers.map(h=>h.name).filter(h=>!s.includes(h)).filter((h,g,b)=>b.indexOf(h)===g).sort(),c=r.componentTags.map(h=>h.normalized).filter((h,g,b)=>b.indexOf(h)===g).sort(),l=_e(e,n).length,u=Jt(i.template),d=o.lineCount,m=i.styles.reduce((h,g)=>h+Jt(g),0),p=i.customBlocks.reduce((h,g)=>h+Jt(g),0);return{file:n,sfc:i,templateFacts:r,scriptFacts:o,templateTokens:new Set(r.structuralTokens),behaviorTokens:lS(r,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:p}}function lS(e,t,n){let i=new Set;for(let r of t.composables)i.add(`composable:${r}`);for(let r of t.stores)i.add(`store:${r}`);for(let r of t.reactivity)i.add(`reactivity:${r}`);for(let r of t.lifecycle)i.add(`lifecycle:${r}`);for(let r of t.requests)i.add(`request:${r}`);for(let r of t.macros)i.add(`macro:${r}`);for(let r of t.functions){if(aS.has(r.name))continue;i.add(`function:${r.name}`);let o=/^[a-z]+/.exec(r.name)?.[0]??null;o&&o.length>2&&o!==r.name&&i.add(`function-verb:${o}`)}for(let r of e.events)i.add(`template-event:${r.name}`);for(let r of n)i.add(`template-binding:${r}`);return i}function uS(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let i of dS(n.value))t.add(i);for(let n of e.slots)if(n.value)for(let i of lu(n.value))t.add(i);return[...t].sort()}function dS(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?lu(t[1]??""):[]}function lu(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];sS.has(i)||t.push(i)}return t}import{extname as mS}from"path";var pS=[".tsx",".jsx"],uu=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),fS=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),gS=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),hS=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),bS=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),yS=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),SS=new Set(["children","className","false","key","null","style","true","undefined"]),xS=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]);function Hn(e,t={}){let n=De(e,{extensions:pS}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(r=>CS(e,r)).filter(r=>(t.minJsxTokens===void 0||r.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function CS(e,t){let n=t.replace(/\\/g,"/"),i=vS(n);if(!i)return[];let r=me(e,n);if(!r)return[];let o=_e(e,n).length;return RS(r.rootNode,i).filter(a=>a.kind==="hook"||gu(a.bodyNode)).map(a=>{let c=IS(a.bodyNode),l=_S(a.bodyNode,i);return{file:n,name:a.name,kind:a.kind,startLine:a.node.startPosition.row,endLine:a.node.endPosition.row,loc:Math.max(1,a.node.endPosition.row-a.node.startPosition.row+1),fileLines:o,jsxTokens:c.tokens,behaviorTokens:l.tokens,componentNames:St(c.componentNames),nativeTags:St(c.nativeTags),propNames:St(c.propNames),eventNames:St(c.eventNames),hookNames:St(l.hookNames),requestNames:St(l.requestNames),stateNames:St(l.stateNames),effectNames:St(l.effectNames),handlerNames:St(l.handlerNames)}})}function vS(e){let t=mS(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:W(e)}function RS(e,t){let n=[],i=new Set,r=o=>{let s=kS(o);if(s&&!LS(o)){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;i.has(a)||(i.add(a),n.push(s));return}for(let a of o.namedChildren)r(a)};return(t==="tsx"||t==="javascript")&&r(e),n}function kS(e){if(e.type==="function_declaration"){let o=fu(e);return!o||!du(o)?null:{name:o,kind:mu(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),i=Ni(t);if(!i||!n||!du(i))return null;let r=wS(n);return r?{name:i,kind:mu(i),node:e,bodyNode:r}:null}function du(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function mu(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function wS(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=DS(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(r=>r.type==="arguments")?.namedChildren.find(r=>r.type==="arrow_function"||r.type==="function_expression")??null}function LS(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function fu(e){return Ni(e.childForFieldName("name")??e.namedChild(0))}function DS(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function gu(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(gu)}function IS(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=i=>{i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"?PS(i,t):i.type==="jsx_expression"?NS(i,t):i.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let r of i.namedChildren)n(r)};return n(e),t}function PS(e,t){let n=ES(e),i=!1;if(n){let r=pu(n);i=OS(r),i?(t.componentNames.add(r),t.tokens.add(`component:${r}`)):(t.nativeTags.add(r),t.tokens.add(`native:${r}`))}for(let r of e.namedChildren)if(r.type==="jsx_attribute"){let o=TS(r);if(!o)continue;let s=pu(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else xS.has(s)||(t.propNames.add(s),t.tokens.add(`${i?"prop":"native-prop"}:${s}`))}else r.type==="jsx_spread_attribute"&&t.tokens.add("prop:spread")}function NS(e,t){let n=e.text;(n.includes("&&")||n.includes("?"))&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let i of jS(n))SS.has(i)||t.tokens.add(`binding:${i}`)}function ES(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function TS(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function _S(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},i=r=>{if(r.type==="call_expression"){let o=An(r,t);o&&FS(o.calleeLeaf,n)}else if(r.type==="variable_declarator")AS(r,n);else if(r.type==="function_declaration"){let o=fu(r);o&&hu(o,n)}for(let o of r.namedChildren)i(o)};return i(e),n}function FS(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!uu.has(e)&&!hS.has(e)&&t.tokens.add(`hook:${e}`)),uu.has(e)&&t.tokens.add(`react-hook:${e}`),fS.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),gS.has(e)&&t.tokens.add(`state-hook:${e}`),$S(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function $S(e){if(bS.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function AS(e,t){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&i?.text.includes("useState")){let o=n.namedChildren.find(a=>Ni(a)),s=Ni(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let r=Ni(n);r&&hu(r,t)}function hu(e,t){let n=MS(e);!n||!yS.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function MS(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function OS(e){return/^[A-Z]/.test(e)||e.includes(".")}function pu(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function Ni(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function jS(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];t.includes(i)||t.push(i)}return t}function St(e){return[...e].sort()}function Xt(e,t,n={}){let i=oe(e,t);if(!i)return[];let r=[];if(n.includeCrossLanguageDispatchNames)for(let o of i.crossLanguageDispatchNames)r.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&i.language==="rust")for(let o of i.rustAttrReferencedNames)r.push({name:o,kind:"rust-attribute",occurrences:1});return r}var BS={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function pe(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],i=t[1],r=e.slice(n.length+1+i.length+1),o;if(r.startsWith("`")){let l=r.indexOf("`",1);l===-1?(o=r.slice(1),r=""):(o=r.slice(1,l),r=r.slice(l+2))}else{let l=r.indexOf(" ");l===-1?(o=r,r=""):(o=r.slice(0,l),r=r.slice(l+1))}let s,a=r.indexOf(" ");a===-1?(s=r,r=""):(s=r.slice(0,a),r=r.slice(a+1));let c=HS(r);return{scheme:n,manager:i,packageName:o,version:s,descriptors:c,raw:e}}function rt(e){let t=pe(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let i=t.descriptors[n];if(i?.suffix==="type")return i.name}return null}function HS(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||bu(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let i;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){i=e.slice(n+1),t.push({name:i,suffix:"term"});break}i=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!bu(e[n]);)n++;i=e.slice(o,n)}if(n>=e.length){i&&t.push({name:i,suffix:"term"});break}let r=e[n];if(r==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:i,suffix:"method"}),n=o+2):o!==-1?(t.push({name:i,suffix:"method"}),n=o+1):(t.push({name:i,suffix:"term"}),n++)}else{let o=BS[r];o&&t.push({name:i,suffix:o}),n+=1}}return t}function bu(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function y(e){let t=pe(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let i=[];for(let r of n.descriptors){let o=VS(r);o&&i.push(o)}return i.join(":")}function VS(e){let t=e.suffix==="namespace"?qS(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function qS(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function F(e){let t=pe(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function Z(e){let t=pe(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function xe(e){return e.endsWith("().")||Z(e)==="method"}function se(e){let t=Z(e);return t==="method"||t==="term"}function Tt(e){return Z(e)==="namespace"}var US=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function jr(e){return US.test(e)}var WS=new Set(["test","tests","_tests"]);function Vn(e){let t=pe(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let i=t.descriptors[n];if(i?.suffix==="namespace"&&i.name&&WS.has(i.name))return!0}return!1}function yu(e,t){let n=pe(e),i=pe(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length!==r.length+1)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Su(e,t){let n=pe(e),i=pe(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length<=r.length)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function qn(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
32
+ (relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?")}}catch(n){Bl("disabled (open failed)",n)}return _r.set(e,t),t}function Ii(e,t,n){Bl(`disabled (${t})`,n),_r.set(e,null)}function Fr(e,t,n,i){let r=Di(e);if(!r)return null;try{return r.readFileEvidence.get(t,n,i,$r)?.payload??null}catch(o){return Ii(e,"file_evidence read",o),null}}function Ar(e,t,n,i,r){let o=Di(e);if(o)try{o.writeFileEvidence.run(t,n,i,$r,r)}catch(s){Ii(e,"file_evidence write",s)}}function Hl(e){let t=Di(e);if(!t)return 0;try{return t.evidence.prepare("SELECT COUNT(*) AS count FROM semantic_callees").get()?.count??0}catch(n){return Ii(e,"semantic_callees count",n),0}}function Vl(e,t,n,i,r){let o=Di(e);if(!o)return null;try{return o.readCallees.get(t,n,i,r,$r)?.payload??null}catch(s){return Ii(e,"semantic_callees read",s),null}}function ql(e,t){if(t.length===0)return;let n=Di(e);if(n)try{n.evidence.transaction(()=>{let i=new Set;for(let r of t){let o=`${r.relativePath}\0${r.contentHash}`;i.has(o)||(i.add(o),n.dropStaleCallees.run(r.relativePath,r.contentHash)),n.writeCallees.run(r.relativePath,r.symbol,r.contentHash,r.depsDigest,$r,r.payload)}})()}catch(i){Ii(e,"semantic_callees write",i)}}function Pi(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var ly=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Mr(e,t){let n=dy(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Gl(n.functionNode),params:Ul(n.functionNode),paramsEndLine:Wl(n.functionNode),isLiteralPassthrough:zl(n.functionNode,t)};if(!uy(e.type,t))return null;let i=e.childForFieldName("name")??e.namedChildren.find(r=>r.type==="identifier"||r.type==="property_identifier");return i?{name:i.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:Gl(e),params:Ul(e),paramsEndLine:Wl(e),isLiteralPassthrough:zl(e,t)}:null}function Kl(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Ul(e){let t=Kl(e);if(!t)return[];let n=[];for(let i of t.namedChildren){if(Pi(i))continue;if(i.type==="identifier"){n.push({name:i.text,simple:!0});continue}let r=i.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(i.text),o=i.childForFieldName("pattern");if(!r&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=i.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function Wl(e){let t=Kl(e);return t?t.endPosition.row:e.startPosition.row}function uy(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?ly.has(e):!1}function dy(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}return null}function Gl(e){let t=e.namedChildren.find(i=>i.type==="parameters"||i.type==="formal_parameters");if(!t)return 0;let n=0;for(let i of t.namedChildren)Pi(i)||(n+=1);return n}function zl(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let i=n.namedChildren.filter(d=>!Pi(d));if(i.length!==1)return!1;let r=i[0],o=null;if(r.type==="return_statement"||r.type==="expression_statement"?o=r.namedChild(0)??null:t==="rust"&&(r.type==="call_expression"||r.type==="macro_invocation")&&(o=r),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!Pi(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let m=d.namedChildren.find(p=>p.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var my=new Set(["identifier","type_identifier","field_identifier"]),py=new Set(["identifier"]),fy=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),gy=new Set(["rust","python"]),hy=/\{([^{}]*)\}/g,by=/\b([A-Za-z_][\w]*)\b/g;function Jl(e,t){return yy(t).has(e.type)}function Ql(e,t){return gy.has(t)&&e.type==="string_content"}function Ms(e){let t=0;for(let i of e.values()){let r=i[i.length-1];r!==void 0&&r>t&&(t=r)}let n=new Array(t+1);for(let i=0;i<=t;i+=1)n[i]=new Set;for(let[i,r]of e)for(let o of r)n[o].add(i);return n}function yy(e){return e==="rust"?my:e==="python"?py:fy}function Xl(e,t){let n=e.startPosition.row;for(let i of e.text.matchAll(hy)){let r=i[1]??"";for(let o of r.matchAll(by))o[1]&&t(o[1],n)}}var Sy=[/\bdefault\s*=\s*"([^"]+)"/g,/\bwith\s*=\s*"([^"]+)"/g,/\bserialize_with\s*=\s*"([^"]+)"/g,/\bdeserialize_with\s*=\s*"([^"]+)"/g,/\bskip_serializing_if\s*=\s*"([^"]+)"/g,/\bgetter\s*=\s*"([^"]+)"/g,/\brename_all_with\s*=\s*"([^"]+)"/g,/\bschema_with\s*=\s*"([^"]+)"/g],xy=/^#!?\[\s*serde\s*\(/,Cy=/^#!?\[\s*schemars\s*\(/,vy=/^#!?\[\s*validate\s*\(/,Ry=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Yl(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let i=e.childForFieldName("function")??e.namedChild(0);if(!i)return;let r=Fn(i);if(!r||!Ry.has(r))return;let o=e.namedChildren.find(c=>c.type==="arguments");if(!o)return;let s=o.namedChild(0);if(!s||s.type!=="string")return;let a=s.namedChildren.find(c=>c.type==="string_fragment");a&&n.add(a.text)}function Zl(e,t){let n=xy.test(e),i=Cy.test(e),r=vy.test(e);if(!(!n&&!i&&!r))for(let o of Sy){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function eu(e,t){let n=new Map,i=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},r=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{r.has(l.type)&&l.text!==a&&i(l.text,a);for(let u of l.children)c(u)};for(let l of s.children)c(l)};if(t==="rust")for(let s of e.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let a=s.namedChildren.find(l=>l.type==="type_identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="field_declaration_list"||l.type==="enum_variant_list"||l.type==="ordered_field_declaration_list");c&&o(c,a),s.type==="type_item"&&o(s,a)}else if(t==="python")for(let s of e.rootNode.descendantsOfType("class_definition")){let a=s.namedChildren.find(l=>l.type==="identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="block");if(c)for(let l of c.descendantsOfType("type"))for(let u of l.descendantsOfType("identifier"))u.text!==a&&i(u.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var ky=Kt("source-facts",{clearGroups:["whole-project","source-file"]});function oe(e,t){let n=M(e,t);if(!n)return null;let i=wy(t,n);return i?ky.get(e,t,n,()=>Ly(e,t,i,n)):null}function wy(e,t){return yt(e)?Tr(t)?.language??null:W(e)}function Ly(e,t,n,i){let r=Qt(e,t,i),o=Fr(e,"source-facts",t,r);if(o){let c=Iy(o);if(c&&c.language===n)return c}let s=me(e,t);if(!s)return null;let a=Ny(s,n);return Ar(e,"source-facts",t,r,Dy(a)),a}function Dy(e){let t={language:e.language,callables:e.callables,callSites:e.callSites,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,i])=>[n,[...i]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function Iy(e){try{let t=JSON.parse(e),n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,typeContainerMap:new Map(t.typeContainerMap.map(([i,r])=>[i,new Set(r)])),identifierLineMap:n,identifiersByLine:Ms(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Os(e,t,n,i){let r=oe(e,t);return r?Py(r,n,i)?.isLiteralPassthrough??!0:!0}function Py(e,t,n){return e.callables.find(i=>i.startLine===t&&i.endLine===n)??null}function Ny(e,t){let n=[],i=[],r=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=Mr(l,t);u&&n.push(u);let d=An(l,t);d&&i.push(d),Yl(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Zl(l.text,r),Jl(l,t)&&a(l.text,l.startPosition.row),Ql(l,t)&&Xl(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:i,typeContainerMap:eu(e,t),identifierLineMap:s,identifiersByLine:Ms(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:r,crossLanguageDispatchNames:o}}var tu=new Set(["rust","typescript","tsx","javascript","python"]);function js(e,t){let n=oe(e,t);return!n||!tu.has(n.language)?null:n.callables.map(i=>({name:i.name,startLine:i.startLine,endLine:i.endLine}))}function Mn(e,t){let n=oe(e,t);return!n||!tu.has(n.language)?null:n.callSites}function Bs(e,t){return oe(e,t)?.typeContainerMap??new Map}import{ElementTypes as Ey,NodeTypes as iu,parse as Ty}from"@vue/compiler-dom";import{parse as Uj}from"@vue/compiler-sfc";function Or(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var _y=Dr("vue-template-facts"),$y=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),Fy=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),Ay=new Set(["div","span","template"]),My=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function ru(e,t){let n=t.replace(/\\/g,"/"),i=M(e,n);return _y.get(e,n,i,()=>Oy(n,Er(e,n).template))}function Oy(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let i;try{i=Ty(t.body,{comments:!1})}catch{return n}let r=new Set,o=s=>{s.trim()&&r.add(s)};return ou(i.children,t.startLine,n,o),n.structuralTokens=[...r].sort(),n}function ou(e,t,n,i){for(let r of e)r.type===iu.ELEMENT&&(jy(r,t,n,i),ou(r.children,t,n,i))}function jy(e,t,n,i){let r=zy(e.tag),o={tag:e.tag,normalized:r,kind:Gy(e),startLine:On(t,e.loc.start.line),endLine:On(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),i(`component:${r}`)):o.kind==="builtin"?(n.builtinTags.push(o),i(`builtin:${r}`)):(n.nativeTags.push(o),Ay.has(e.tag)||i(`native:${e.tag}`));for(let s of e.props)By(s,t,n,i)}function By(e,t,n,i){if(e.type===iu.ATTRIBUTE){let a=e.value?.content??null,c=nu("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),i(`prop:${e.name}`);return}let r=Vy(e),o=su(e.exp),s=nu(Hy(e.name),r,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),i(`prop:${r}`);break;case"event":n.events.push(s),i(`event:${r}`);break;case"slot":n.slots.push(s),i(`slot:${r}`);break;case"directive":n.directives.push(s),i(`directive:${r}`);break}o&&qy(o,t,e.loc.start.line,n,i)}function nu(e,t,n,i,r,o){return{kind:e,name:t,value:n,startLine:On(i,r),endLine:On(i,o)}}function Hy(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function Vy(e){let t=su(e.arg);return t||e.name}function su(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function qy(e,t,n,i,r){for(let o of Uy(e)){let s={name:o,startLine:On(t,n),endLine:On(t,n)};i.expressionIdentifiers.push(s),r(`id:${o}`)}}function Uy(e){let t=new Set,n=Wy(e),i=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,r;for(;r=i.exec(n);){let o=r[0];My.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function Wy(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function Gy(e){let t=e.tag;return e.tagType===Ey.COMPONENT?"component":$y.has(t)?"builtin":Fy.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function zy(e){return Or(e,/[-_:]/)}function On(e,t){return e+Math.max(0,t-1)}import{readdirSync as Ky}from"fs";import{execFileSync as Jy}from"child_process";import{extname as Hs,join as Qy}from"path";var Xy=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],au=[".vue"],cu=new Set(Xy.map(e=>e.toLowerCase())),Yy=[...cu].sort().join(","),Vs=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function De(e,t={}){let n=t.includeIndexed??!0,i=t.includeAuxiliary??!0,r=t.extensions?.map(c=>c.toLowerCase()),o=r?new Set(r):cu,s=r?[...o].sort().join(","):Yy,a=`${n?"1":"0"}|${i?"1":"0"}|${s}`;return Zy.get(e,a,()=>{let c=new Set;if(n)for(let l of j(e,{includeIgnored:!1}))o.has(Hs(l).toLowerCase())&&c.add(l);if(i)for(let l of eS(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}var Zy=U("source-files",{clearGroups:[]});function eS(e,t){return tS(e,t)??nS(e,t)}function tS(e,t){try{let n=Jy("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),i=new Set;for(let r of n.split(`
33
+ `)){let o=r.trim();o&&t.has(Hs(o).toLowerCase())&&i.add(o)}return i}catch{return null}}function nS(e,t){let n=new Set,i=r=>{let o=r?Qy(e,r):e,s;try{s=Ky(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Vs.has(a.name)){if(a.isDirectory()){i(r?`${r}/${a.name}`:a.name);continue}t.has(Hs(a.name).toLowerCase())&&n.add(r?`${r}/${a.name}`:a.name)}};return i(""),n}var iS=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),rS=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),oS=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),sS=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),aS=new Set(["catch","for","function","if","return","switch","while"]);function lu(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=Jt(n),n.external&&(t.externalLineCount+=Jt(n),t.externalScriptPaths.push(n.sourcePath));for(let r of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:r});if(!n.body||!n.astLanguage){n.astLanguage||t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:`Unsupported Vue script language: ${n.lang??"unknown"}`});continue}t.imports.push(...dS(n));let i=wi(n.astLanguage,n.body);i?lS(n,i.rootNode,t):uS(n,t)}return cS(t),t.externalScriptPaths=du(t.externalScriptPaths),t}function cS(e){e.composables=jn(e,"composable"),e.stores=jn(e,"store"),e.reactivity=jn(e,"reactivity"),e.lifecycle=jn(e,"lifecycle"),e.requests=jn(e,"request"),e.macros=jn(e,"macro")}function jn(e,t){return du(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function lS(e,t,n){let i=new Set,r=new Set,o=s=>{let a=Mr(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;r.has(l)||(r.add(l),n.functions.push({name:a.name,sourcePath:e.sourcePath,startLine:e.startLine+a.startLine,endLine:e.startLine+a.endLine,setup:e.setup}))}let c=An(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;i.has(l)||(i.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:uu(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function uS(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let i=n[1];!i||aS.has(i)||t.calls.push({name:i,sourcePath:e.sourcePath,line:e.startLine+jr(e.body,n.index??0),categories:uu(i),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let i=n[1];if(!i)continue;let r=e.startLine+jr(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}for(let n of e.body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/g)){let i=n[1];if(!i)continue;let r=e.startLine+jr(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}}function dS(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let i=n[1]?.trim(),r=n[2];if(!i||!r)continue;let o=e.startLine+jr(e.body,n.index??0);for(let s of mS(i))t.push({local:s,source:r,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function mS(e){let t=[],i=e.split(",").map(s=>s.trim()).filter(Boolean)[0];i&&!i.startsWith("{")&&!i.startsWith("*")&&t.push(i);let r=/\{([^}]*)\}/.exec(e)?.[1];if(r)for(let s of r.split(",")){let a=s.trim();if(!a)continue;let c=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(a)?.[1];t.push(c??a.replace(/^type\s+/,"").trim())}let o=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1];return o&&t.push(o),t.filter(s=>/^[A-Za-z_$][\w$]*$/.test(s))}function uu(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),iS.has(e)&&t.push("reactivity"),rS.has(e)&&t.push("lifecycle"),oS.has(e)&&t.push("request"),sS.has(e)&&t.push("macro"),t}function jr(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e.charCodeAt(i)===10&&(n+=1);return n}function du(e){return[...new Set(e)].sort()}var pS=new Set(["in","key","of"]),fS=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]);function Bn(e,t={}){let n=De(e,{extensions:[".vue"]}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(r=>gS(e,r)).filter(r=>(t.minTemplateTokens===void 0||r.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function gS(e,t){let n=t.replace(/\\/g,"/"),i=Er(e,n),r=ru(e,n),o=lu(i),s=bS(r),a=r.expressionIdentifiers.map(h=>h.name).filter(h=>!s.includes(h)).filter((h,g,b)=>b.indexOf(h)===g).sort(),c=r.componentTags.map(h=>h.normalized).filter((h,g,b)=>b.indexOf(h)===g).sort(),l=_e(e,n).length,u=Jt(i.template),d=o.lineCount,m=i.styles.reduce((h,g)=>h+Jt(g),0),p=i.customBlocks.reduce((h,g)=>h+Jt(g),0);return{file:n,sfc:i,templateFacts:r,scriptFacts:o,templateTokens:new Set(r.structuralTokens),behaviorTokens:hS(r,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:p}}function hS(e,t,n){let i=new Set;for(let r of t.composables)i.add(`composable:${r}`);for(let r of t.stores)i.add(`store:${r}`);for(let r of t.reactivity)i.add(`reactivity:${r}`);for(let r of t.lifecycle)i.add(`lifecycle:${r}`);for(let r of t.requests)i.add(`request:${r}`);for(let r of t.macros)i.add(`macro:${r}`);for(let r of t.functions){if(fS.has(r.name))continue;i.add(`function:${r.name}`);let o=/^[a-z]+/.exec(r.name)?.[0]??null;o&&o.length>2&&o!==r.name&&i.add(`function-verb:${o}`)}for(let r of e.events)i.add(`template-event:${r.name}`);for(let r of n)i.add(`template-binding:${r}`);return i}function bS(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let i of yS(n.value))t.add(i);for(let n of e.slots)if(n.value)for(let i of mu(n.value))t.add(i);return[...t].sort()}function yS(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?mu(t[1]??""):[]}function mu(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];pS.has(i)||t.push(i)}return t}import{extname as SS}from"path";var xS=[".tsx",".jsx"],pu=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),CS=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),vS=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),RS=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),kS=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),wS=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),LS=new Set(["children","className","false","key","null","style","true","undefined"]),DS=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]);function Hn(e,t={}){let n=De(e,{extensions:xS}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(r=>IS(e,r)).filter(r=>(t.minJsxTokens===void 0||r.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function IS(e,t){let n=t.replace(/\\/g,"/"),i=PS(n);if(!i)return[];let r=me(e,n);if(!r)return[];let o=_e(e,n).length;return NS(r.rootNode,i).filter(a=>a.kind==="hook"||yu(a.bodyNode)).map(a=>{let c=FS(a.bodyNode),l=BS(a.bodyNode,i);return{file:n,name:a.name,kind:a.kind,startLine:a.node.startPosition.row,endLine:a.node.endPosition.row,loc:Math.max(1,a.node.endPosition.row-a.node.startPosition.row+1),fileLines:o,jsxTokens:c.tokens,behaviorTokens:l.tokens,componentNames:St(c.componentNames),nativeTags:St(c.nativeTags),propNames:St(c.propNames),eventNames:St(c.eventNames),hookNames:St(l.hookNames),requestNames:St(l.requestNames),stateNames:St(l.stateNames),effectNames:St(l.effectNames),handlerNames:St(l.handlerNames)}})}function PS(e){let t=SS(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:W(e)}function NS(e,t){let n=[],i=new Set,r=o=>{let s=ES(o);if(s&&!_S(o)){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;i.has(a)||(i.add(a),n.push(s));return}for(let a of o.namedChildren)r(a)};return(t==="tsx"||t==="javascript")&&r(e),n}function ES(e){if(e.type==="function_declaration"){let o=bu(e);return!o||!fu(o)?null:{name:o,kind:gu(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),i=Ni(t);if(!i||!n||!fu(i))return null;let r=TS(n);return r?{name:i,kind:gu(i),node:e,bodyNode:r}:null}function fu(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function gu(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function TS(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=$S(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(r=>r.type==="arguments")?.namedChildren.find(r=>r.type==="arrow_function"||r.type==="function_expression")??null}function _S(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function bu(e){return Ni(e.childForFieldName("name")??e.namedChild(0))}function $S(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function yu(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(yu)}function FS(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=i=>{i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"?AS(i,t):i.type==="jsx_expression"?MS(i,t):i.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let r of i.namedChildren)n(r)};return n(e),t}function AS(e,t){let n=OS(e),i=!1;if(n){let r=hu(n);i=WS(r),i?(t.componentNames.add(r),t.tokens.add(`component:${r}`)):(t.nativeTags.add(r),t.tokens.add(`native:${r}`))}for(let r of e.namedChildren)if(r.type==="jsx_attribute"){let o=jS(r);if(!o)continue;let s=hu(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else DS.has(s)||(t.propNames.add(s),t.tokens.add(`${i?"prop":"native-prop"}:${s}`))}else r.type==="jsx_spread_attribute"&&t.tokens.add("prop:spread")}function MS(e,t){let n=e.text;(n.includes("&&")||n.includes("?"))&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let i of GS(n))LS.has(i)||t.tokens.add(`binding:${i}`)}function OS(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function jS(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function BS(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},i=r=>{if(r.type==="call_expression"){let o=An(r,t);o&&HS(o.calleeLeaf,n)}else if(r.type==="variable_declarator")qS(r,n);else if(r.type==="function_declaration"){let o=bu(r);o&&Su(o,n)}for(let o of r.namedChildren)i(o)};return i(e),n}function HS(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!pu.has(e)&&!RS.has(e)&&t.tokens.add(`hook:${e}`)),pu.has(e)&&t.tokens.add(`react-hook:${e}`),CS.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),vS.has(e)&&t.tokens.add(`state-hook:${e}`),VS(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function VS(e){if(kS.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function qS(e,t){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&i?.text.includes("useState")){let o=n.namedChildren.find(a=>Ni(a)),s=Ni(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let r=Ni(n);r&&Su(r,t)}function Su(e,t){let n=US(e);!n||!wS.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function US(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function WS(e){return/^[A-Z]/.test(e)||e.includes(".")}function hu(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function Ni(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function GS(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];t.includes(i)||t.push(i)}return t}function St(e){return[...e].sort()}function Xt(e,t,n={}){let i=oe(e,t);if(!i)return[];let r=[];if(n.includeCrossLanguageDispatchNames)for(let o of i.crossLanguageDispatchNames)r.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&i.language==="rust")for(let o of i.rustAttrReferencedNames)r.push({name:o,kind:"rust-attribute",occurrences:1});return r}var zS={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function pe(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],i=t[1],r=e.slice(n.length+1+i.length+1),o;if(r.startsWith("`")){let l=r.indexOf("`",1);l===-1?(o=r.slice(1),r=""):(o=r.slice(1,l),r=r.slice(l+2))}else{let l=r.indexOf(" ");l===-1?(o=r,r=""):(o=r.slice(0,l),r=r.slice(l+1))}let s,a=r.indexOf(" ");a===-1?(s=r,r=""):(s=r.slice(0,a),r=r.slice(a+1));let c=KS(r);return{scheme:n,manager:i,packageName:o,version:s,descriptors:c,raw:e}}function it(e){let t=pe(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let i=t.descriptors[n];if(i?.suffix==="type")return i.name}return null}function KS(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||xu(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let i;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){i=e.slice(n+1),t.push({name:i,suffix:"term"});break}i=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!xu(e[n]);)n++;i=e.slice(o,n)}if(n>=e.length){i&&t.push({name:i,suffix:"term"});break}let r=e[n];if(r==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:i,suffix:"method"}),n=o+2):o!==-1?(t.push({name:i,suffix:"method"}),n=o+1):(t.push({name:i,suffix:"term"}),n++)}else{let o=zS[r];o&&t.push({name:i,suffix:o}),n+=1}}return t}function xu(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function y(e){let t=pe(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let i=[];for(let r of n.descriptors){let o=JS(r);o&&i.push(o)}return i.join(":")}function JS(e){let t=e.suffix==="namespace"?QS(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function QS(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function $(e){let t=pe(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function Z(e){let t=pe(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function xe(e){return e.endsWith("().")||Z(e)==="method"}function se(e){let t=Z(e);return t==="method"||t==="term"}function Tt(e){return Z(e)==="namespace"}var XS=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function Br(e){return XS.test(e)}var YS=new Set(["test","tests","_tests"]);function Vn(e){let t=pe(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let i=t.descriptors[n];if(i?.suffix==="namespace"&&i.name&&YS.has(i.name))return!0}return!1}function Cu(e,t){let n=pe(e),i=pe(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length!==r.length+1)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function vu(e,t){let n=pe(e),i=pe(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length<=r.length)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function qn(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
34
34
  FROM global_symbols gs
35
35
  JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
36
36
  JOIN documents d ON der.document_id = d.id
37
37
  WHERE ${t.where}
38
38
  ${e.pathExclusionsFor("d")}
39
- ${Cu(t.orderBy)}
40
- ${vu(t.limit)}`,...t.params??[])}function Un(e,t){return e.all(`SELECT
39
+ ${ku(t.orderBy)}
40
+ ${wu(t.limit)}`,...t.params??[])}function Un(e,t){return e.all(`SELECT
41
41
  gs.id,
42
42
  gs.symbol,
43
43
  c.document_id,
@@ -54,8 +54,8 @@ import{program as ws}from"commander";import{realpathSync as xb}from"fs";import{f
54
54
  AND ${t.where}
55
55
  ${e.pathExclusionsFor("d")}
56
56
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
57
- ${Cu(t.orderBy)}
58
- ${vu(t.limit)}`,...t.params??[])}function Cu(e){return e?`ORDER BY ${e}`:""}function vu(e){return typeof e=="number"?`LIMIT ${e}`:""}function Yt(e){return!e||!e.trim()?null:e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim()||null}function Zt(e){if(!e)return null;let t=xu(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let i=e.slice(n+1);return(xu(i)??i).replace(/\n/g," ")}function xu(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function GS(e){if(rt(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function Wn(e,t,n={}){let i=new Map;for(let o of t)e.length>0&&!GS(o)||i.set(o.id,o);for(let o of e)i.set(o.id,o);let r=[...i.values()];return n.sort?r.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):r}var zS=U("file-definitions",{clearGroups:["definition-catalog"]}),Ru=new WeakMap;function G(e,t){return zS.get(e,t,()=>{let n=Wn(KS(e,t),JS(e,t),{sort:!0});return XS(e,t,n.map(QS))})}function KS(e,t){return e.all(`SELECT
57
+ ${ku(t.orderBy)}
58
+ ${wu(t.limit)}`,...t.params??[])}function ku(e){return e?`ORDER BY ${e}`:""}function wu(e){return typeof e=="number"?`LIMIT ${e}`:""}function Yt(e){return!e||!e.trim()?null:e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim()||null}function Zt(e){if(!e)return null;let t=Ru(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let i=e.slice(n+1);return(Ru(i)??i).replace(/\n/g," ")}function Ru(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function ZS(e){if(it(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function Wn(e,t,n={}){let i=new Map;for(let o of t)e.length>0&&!ZS(o)||i.set(o.id,o);for(let o of e)i.set(o.id,o);let r=[...i.values()];return n.sort?r.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):r}var ex=U("file-definitions",{clearGroups:["definition-catalog"]}),Lu=new WeakMap;function G(e,t){return ex.get(e,t,()=>{let n=Wn(tx(e,t),nx(e,t),{sort:!0});return rx(e,t,n.map(ix))})}function tx(e,t){return e.all(`SELECT
59
59
  gs.id,
60
60
  gs.symbol,
61
61
  der.document_id,
@@ -71,7 +71,7 @@ import{program as ws}from"commander";import{realpathSync as xb}from"fs";import{f
71
71
  JOIN documents d ON der.document_id = d.id
72
72
  WHERE d.relative_path = ?
73
73
  ${e.symbolNoiseFor("gs")}
74
- ORDER BY der.start_line, der.end_line`,t)}function JS(e,t){return e.all(`SELECT
74
+ ORDER BY der.start_line, der.end_line`,t)}function nx(e,t){return e.all(`SELECT
75
75
  gs.id,
76
76
  gs.symbol,
77
77
  c.document_id,
@@ -90,10 +90,10 @@ import{program as ws}from"commander";import{realpathSync as xb}from"fs";import{f
90
90
  AND m.role = 1
91
91
  ${e.symbolNoiseFor("gs")}
92
92
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
93
- ORDER BY start_line, end_line`,t)}function QS(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:F(e.symbol),parentTypeName:rt(e.symbol),isFunctionLike:se(e.symbol),isTypeLike:Z(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function ot(e,t={}){return Ei(e,t.scope)}function Ei(e,t){return j(e,{scope:t,includeIgnored:!1}).flatMap(n=>G(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Br(e,t,n={}){if(t.length===0)return[];let i=t.flatMap(r=>G(e,r)).filter(r=>!e.isIgnored(r.relativePath));return n.onlyDocumented&&(i=i.filter(r=>r.documentation!==null&&r.documentation!=="")),n.sort&&(i=i.sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.startLine-o.startLine||r.endLine-o.endLine)),i.map(r=>({startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,shortName:y(r.symbol),signature:Yt(Zt(r.documentation)),relativePath:r.relativePath,enclosingSymbol:r.enclosingSymbol}))}function Bs(e){let t=new Map,n=e.map((i,r)=>({definition:i,index:r,span:i.endLine-i.startLine})).sort((i,r)=>i.span-r.span||i.index-r.index);for(let{definition:i}of n)for(let r=i.startLine;r<=i.endLine;r+=1)t.has(r)||t.set(r,i);return t}function je(e,t){let n=Ru.get(e);return n||(n=Bs(e),Ru.set(e,n)),n.get(t)??null}function en(e,t){let n=G(e,t.relative_path).find(i=>i.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function XS(e,t,n){let i=M(e,t),r=As(e,t);return r?ix(n,r,i):i?YS(n,i):n}function YS(e,t){let n=t.split(/\r?\n/),i=ZS(e,n),r=ex(e,i),o=tx(r,n);return nx(e,o)}function ZS(e,t){let n=e.some(r=>Hr(r.symbol))?sx(t):null,i=new Map;for(let r of e)i.set(r.symbolId,ox(t,n,r));return i}function ex(e,t){return e.filter(n=>Hr(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,i)=>n.startLine-i.startLine||n.definition.startLine-i.definition.startLine||n.definition.symbol.localeCompare(i.definition.symbol))}function tx(e,t){let n=new Map;for(let i=0;i<e.length;i+=1){let r=e[i],o=e[i+1],s=o?Math.max(r.startLine,o.startLine-1):t.length-1;n.set(r.definition.symbolId,{startLine:r.startLine,endLine:ax(t,r.definition,r.startLine,s)})}return n}function nx(e,t){return e.map(n=>{let i=t.get(n.symbolId);return i?{...n,startLine:i.startLine,endLine:i.endLine}:n})}function ix(e,t,n=null){let i=new Map;for(let r of t){let o=i.get(r.name);o?o.push(r):i.set(r.name,[r])}return e.map(r=>{if(!rx(r)||!r.leaf)return ku(r,n);let o=i.get(r.leaf);if(!o||o.length===0)return ku(r,n);let s=o[0],a=Math.abs(s.startLine-r.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-r.startLine);u<a&&(s=l,a=u)}return{...r,startLine:s.startLine,endLine:s.endLine}})}function rx(e){return Hr(e.symbol)?!0:Z(e.symbol)==="term"&&rt(e.symbol)===null}function ku(e,t){if(!t||!e.leaf||Z(e.symbol)!=="term"||rt(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>i.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function ox(e,t,n){if(!Hr(n.symbol))return n.startLine;let i=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return i;let r=t.get(n.leaf);if(!r||r.length===0)return i;let o=null;for(let s of r){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??i}function sx(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,i=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,r=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<e.length;a+=1){let c=e[a]??"";for(let u of c.matchAll(t))u[1]&&s(u[1],a);for(let u of c.matchAll(n))u[1]&&s(u[1],a);let l=c.match(i);l?.[1]&&s(l[1],a);for(let u of c.matchAll(r))u[1]&&s(u[1],a)}return o}function ax(e,t,n,i){let r=Math.max(n,Math.min(e.length-1,i)),o=Math.max(n,Math.min(r,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=r;l+=1){let u=cx(e[l]??"");for(let d of u)d==="{"?(s+=1,c=!0):d==="}"?s=Math.max(0,s-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function cx(e){let t="",n=null,i=!1;for(let r=0;r<e.length;r+=1){let o=e[r],s=e[r+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-r);break}if(n){if(i){i=!1,t+=" ";continue}if(o==="\\"){i=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function Hr(e){return e.includes("().")}function Vr(e){let t=pe(e);if("kind"in t)return[];let n=[];for(let i=t.descriptors.length-2;i>=0;i-=1){let r=t.descriptors[i];r?.suffix==="type"&&r.name&&n.push(r.name)}return n}import{existsSync as vx}from"fs";import{basename as wu,isAbsolute as Rx,join as kx}from"path";function B(e,t){let n=zn(e,t.trim());if(n)return n;let i=fx(e,t);if(i)return i;let r=lx(e,t);return r||px(e,t)}function lx(e,t){let n=Vs(t),i=Hs(n);if(!i)return null;let r=`%${i.path}%`,o=i.leaf,a=ux(e,r,o,n)[0];return a?en(e,a):null}function ux(e,t,n,i){let r=Wn([],[...dx(e,t,n),...mx(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Gn(o,i)>1);return r.sort((o,s)=>Gn(s,i)-Gn(o,i)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),r}function dx(e,t,n){return qn(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function mx(e,t,n){return Un(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function px(e,t){let n=Vs(t),i=xx(t),r=yx(e,i),o=Cx(r,t,n);if(o&&!e.isIgnored(o.relative_path))return en(e,o);let s=null;for(let a of r){if(e.isIgnored(a.relative_path))continue;let c=Sx(a,t,n,i);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?en(e,s.row):null}function fx(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,i,r,o]=n,s=Math.max(0,parseInt(r,10)-1),a=Math.max(s,parseInt(o,10)-1),c=gx(e,i,s,a)??hx(e,i,s,a);return c&&!e.isIgnored(c.relative_path)?en(e,c):null}function gx(e,t,n,i){return qn(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function hx(e,t,n,i){return Un(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function zn(e,t){let i=qn(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??Un(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!i||e.isIgnored(i.relative_path)?null:en(e,i)}function qr(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=bx(e,t.symbolId)[0];return n?en(e,n):null}function bx(e,t){let n=qn(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),i=Un(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Wn(n,i)}function yx(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),i=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),r=n.join(`
94
- AND `),o=qn(e,{where:r,params:i,limit:200}),s=Un(e,{where:r,params:i,limit:200});return Wn(o,s)}function Sx(e,t,n,i){let r=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,d=y(e.symbol),m=F(e.symbol),p=e.display_name??"",h=e.symbol.toLowerCase(),g=d.toLowerCase(),b=m.toLowerCase(),S=p.toLowerCase(),x=e.relative_path.toLowerCase(),I=/[/:.]/.test(n),L=Hs(n),C=L?.leaf.toLowerCase(),D=0;return(u===r||u===o)&&(D+=1150),(d===r||d===o)&&(D+=1100),p===s&&(D+=1180),m===s&&(D+=1160),(`${m}()`===r||`${m}()`===o)&&(D+=955),(h===a||h===c)&&(D+=1e3),(g===a||g===c)&&(D+=950),(x===a||x===c)&&(D+=925),(x.endsWith(`/${c}`)||x.endsWith(`/${a}`))&&(D+=875),S===l&&(D+=850),b===l&&(D+=825),(`${b}()`===a||`${b}()`===c)&&(D+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(D+=800),h.includes(c)&&(D+=120),g.includes(c)&&(D+=140),x.includes(c)&&(D+=140),S.includes(c)&&(D+=110),i.every(k=>{let A=k.toLowerCase();return h.includes(A)||g.includes(A)||x.includes(A)||S.includes(A)})&&(D+=100+i.length*15),L&&x.includes(L.path.toLowerCase())&&(D+=360,C&&(b===C||`${b}()`===C||`${b}()`==`${C}()`)&&(D+=700),xe(e.symbol)&&(D+=180)),se(e.symbol)&&b===l&&(D+=60),!I&&Tt(e.symbol)&&(D-=160),D-=Math.min(50,Math.max(0,e.end_line-e.start_line)),D}function Hs(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let i=t.slice(n+1).replace(/\(\)$/,"");return!i||i.includes(".")?null:{path:t.slice(0,n),leaf:i}}function Vs(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function xx(e){let t=Vs(e),n=t.split(/[^A-Za-z0-9_]+/).map(i=>i.trim()).filter(i=>i.length>0);return n.length>0?[...new Set(n)]:[t]}function Cx(e,t,n){let i=t.trim(),r=e.filter(o=>{let s=y(o.symbol),a=(o.display_name??"").trim();return o.symbol===i||s===i||s===n||a===i||a===n||`${a}()`===i||Gn(o,n)>1||o.relative_path===i});return r.length===0?null:(r.sort((o,s)=>Gn(s,n)-Gn(o,n)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.relative_path.localeCompare(s.relative_path)||o.symbol.localeCompare(s.symbol)),r[0]??null)}function Gn(e,t){let n=Hs(t);if(!n)return 0;let i=e.relative_path.toLowerCase(),r=F(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return i.includes(o)?r!==s?1:xe(e.symbol)?rt(e.symbol)===null?5:4:rt(e.symbol)===null?3:2:0}function Ie(e,t){let n=Lu(e,t,{allowMultiple:!1})[0]?.relativePath;return n||wx(e,t)}function Kn(e,t){return Lu(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function wx(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=Rx(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=kx(e.config.projectRoot,i);return vx(r)?i:null}function Lu(e,t,n){let i=Du(t);if(!i)return[];let r=j(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:Lx(a,i)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(r.length===0){let a=B(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=r.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=r.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?r:[r[0]]}function Lx(e,t){let n=Du(e),i=wu(n),r=wu(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),i===r&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function Du(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as qR}from"path";import{existsSync as Ur}from"fs";import{basename as Dx,dirname as _t,extname as xt,join as Je,relative as Ti,resolve as Be}from"path";var Ix=Y("indexed-paths",{clearGroups:[]}),tn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Wr=[".py",".pyi"],Fe=[".java",".scala",".kt",".kts"],Gr=[".rs"],zr=[".rb"],Kr=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Ft=[".cs",".vb"],Jr=[".dart"],nn=[".php"],Px=new Set(tn),qs=new Set(Wr),Iu=new Set(Fe),Us=new Set(Gr),Ws=new Set(zr),Pu=new Set(Kr),Nu=new Set(Ft),Gs=new Set(Jr),Eu=new Set(nn),Nx=[{extensions:tn,lookup:Px},{extensions:Wr,lookup:qs},{extensions:Fe,lookup:Iu},{extensions:Gr,lookup:Us},{extensions:zr,lookup:Ws},{extensions:Kr,lookup:Pu},{extensions:Ft,lookup:Nu},{extensions:Jr,lookup:Gs},{extensions:nn,lookup:Eu}];function $t(e,t){return t.has(xt(e).toLowerCase())}function Ex(e){return $t(e,qs)}function Tx(e){return $t(e,Iu)}function _x(e){return $t(e,Us)}function Fx(e){return $t(e,Ws)}function $x(e){return $t(e,Pu)}function Ax(e){return $t(e,Nu)}function Tu(e){return xt(e).toLowerCase()===".vb"}function Mx(e){return $t(e,Gs)}function Ox(e){return $t(e,Eu)}function zs(e){let t=xt(e).toLowerCase();for(let n of Nx)if(n.lookup.has(t))return n.extensions;return tn}function jx(e){return Tx(e)||Ax(e)||Ox(e)}function Xe(e,t,n){return Ex(t)?Jn(e,t,n):_x(t)?Ct(e,t,n):Fx(t)?Qr(e,t,n):$x(t)?Xr(e,t,n):jx(t)?ee(e,n.replace(/\\/g,"."),zs(t)):Mx(t)?Yr(e,t,n):Bx(e,t,n)}function Bx(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let i=_t(Je(e.config.projectRoot,t)),r=Be(i,n),o=_i(e);for(let s of Wx(r)){let a=Qe(Ti(e.config.projectRoot,s));if(o.has(a)||Ur(s))return a}return Qe(Ti(e.config.projectRoot,r))}function Jn(e,t,n){let i=_i(e),r;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=_t(Je(e.config.projectRoot,t));for(let l=1;l<s;l++)c=_t(c);r=a?Be(c,a.replace(/\./g,"/")):c}else r=Be(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Hx(r)){let s=Qe(Ti(e.config.projectRoot,o));if(i.has(s)||Ur(o))return s}return null}function Ct(e,t,n){if(!n)return null;let i=n.replace(/\s+as\s+.+$/,"").trim();if(!i.startsWith("crate::")&&!i.startsWith("self::")&&!i.startsWith("super::"))return null;let r=_t(Je(e.config.projectRoot,t)),o;return i.startsWith("crate::")?o=Be(e.config.projectRoot,"src",i.slice(7).replace(/::/g,"/")):i.startsWith("self::")?o=Be(r,i.slice(6).replace(/::/g,"/")):o=Be(_t(r),i.slice(7).replace(/::/g,"/")),Ks(e,Vx(o))}function Qr(e,t,n){let i=_t(Je(e.config.projectRoot,t)),r=Be(i,n);return Ks(e,qx(r))}function Xr(e,t,n){let i=_t(Je(e.config.projectRoot,t)),r=[Be(i,n),Be(e.config.projectRoot,n),Be(e.config.projectRoot,"include",n),Be(e.config.projectRoot,"src",n)];return Ks(e,r)}function ee(e,t,n){let i=_i(e),r=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=r.replace(/\./g,"/"),s=r.split(".").pop()??r;for(let c of n){let l=`${o}${c}`,u=[...i].find(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...i].find(u=>Dx(u)===`${s}${c}`);if(l)return l}let a=[...i].filter(c=>n.includes(xt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Yr(e,t,n){let i=_i(e);if(n.startsWith("package:")){let s=n.slice(8),a=s.indexOf("/");if(a<0)return null;let c=s.slice(a+1),l=Qe(c.startsWith("lib/")?c:`lib/${c}`);return i.has(l)?l:null}let r=_t(Je(e.config.projectRoot,t)),o=Be(r,n);for(let s of Ux(o)){let a=Qe(Ti(e.config.projectRoot,s));if(i.has(a)||Ur(s))return a}return null}function Hx(e){let t=xt(e);return qs.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Je(e,"__init__.py"),Je(e,"__init__.pyi")]}function Ks(e,t){let n=_i(e);for(let i of t){let r=Qe(Ti(e.config.projectRoot,i));if(n.has(r)||Ur(i))return r}return null}function Vx(e){let t=xt(e);return Us.has(t)?[e]:[`${e}.rs`,Je(e,"mod.rs")]}function qx(e){let t=xt(e);return Ws.has(t)?[e]:[`${e}.rb`,Je(e,"index.rb")]}function Ux(e){let t=xt(e);return Gs.has(t)?[e]:[`${e}.dart`,e]}function Wx(e){let t=xt(e),n=new Set;if(t){n.add(e);for(let i of tn)n.add(e.slice(0,-t.length)+i)}else for(let i of tn)n.add(`${e}${i}`),n.add(Je(e,`index${i}`));return[...n]}function _i(e){return Ix.get(e,()=>new Set(j(e,{includeIgnored:!1}).map(Qe)))}function Qe(e){return e.replace(/\\/g,"/")}import{basename as Fu}from"path";function rn(e){return e.replace(/'''[\s\S]*?'''/g,At).replace(/"""[\s\S]*?"""/g,At).replace(/#.*$/gm,At).replace(/\/\/.*$/gm,At).replace(/\/\*[\s\S]*?\*\//g,At).replace(/`(?:\\[\s\S]|[^`])*`/g,At).replace(/'(?:\\.|[^'\\\r\n])*'/g,At).replace(/"(?:\\.|[^"\\\r\n])*"/g,At)}function At(e){return e.replace(/[^\r\n]/g," ")}var X1=Kt("stripped-lines",{clearGroups:["whole-project","source-file"]});Et({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Zr=null,Fi=""},clearFile:()=>{Zr=null,Fi=""}});var Zr=null,Fi="";function Gx(e){return Zr===e||(Zr=e,Fi=rn(e)),Fi}function Mt(e,t,n){let i=Gx(e);return`${i.slice(0,t)}${" ".repeat(n-t)}${i.slice(n)}`}function Pe(e,t){return new RegExp(`\\b${_u(t)}\\b`,"m").test(e)}function Qn(e,t){let n=new Set,i=new RegExp(`\\b${_u(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let r of e.matchAll(i)){let o=r[1];o&&n.add(o)}return[...n]}function _u(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $i(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var zx=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Ne(e){let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let o=e[r];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(i,r)),i=r+1)}return t.push(e.slice(i)),t}function $e(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function te(e,t){let n=new Set,i=(r,o)=>{let s=o||t.has(r.type);!s&&zx.has(r.type)&&n.add(r.text);for(let a of r.children)i(a,s)};return i(e.rootNode,!1),n}function st(e,t,n,i,r,o,s){return{importedName:r,localName:o,sourcePath:s??ee(e,i,zs(t)),kind:"named",used:Pe(n,o),usedMembers:[]}}function J(e,t,n,i,r="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function Xn(e,t,n,i,r="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i,usedMembers:o,isTypeOnly:s.isTypeOnly}}function on(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function sn(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function He(e,t,n){let i=[];for(let r of e.matchAll(t)){let o=r[0];if(!o||typeof r.index!="number")continue;let s=Mt(e,r.index,r.index+o.length);for(let a of n(r,s))i.push(a)}return i}function Ve(e,t,n,i){let r=me(e,t);if(r){let o=n(r);if(o)return o}return i()}function eo(e,t,n,i){let r=me(e,t),o=W(t),s=o?n[o]:void 0;return r&&s?s(r):i()}function $u(e,t,n){return Ve(e,t,i=>Jx(e,t,i),()=>Kx(e,t,n))}function Kx(e,t,n){return He(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,r)=>{let o=i[1]?.trim();if(!o)return[];let s=Fu(o).replace(/\.[^.]+$/,"");return[Xn(o,s,Xr(e,t,o),Pe(r,s))]})}function Jx(e,t,n){let i=te(n,new Set(["preproc_include"])),r=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=Fu(s).replace(/\.[^.]+$/,"");r.push(J(s,a,Xr(e,t,s),i))}return r}function Au(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=r[1]?.trim(),s=r[2]?.trim()??null,a=r[0];if(!o||!a||typeof r.index!="number")continue;let c=Mt(n,r.index,r.index+a.length);i.push({importedName:o,localName:s,sourcePath:Yr(e,t,o),kind:s?"namespace":"side-effect",used:s?Pe(c,s):!0,usedMembers:s?Qn(c,s):[]})}return i}function Mu(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=r[1]?.trim();o&&i.push({specifier:o,sourcePath:Yr(e,t,o)})}return i}function Ou(e,t,n){return eo(e,t,{csharp:i=>Xx(e,t,i),vb:i=>Qx(e,t,i)},()=>{let i=Tu(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return He(n,i,(r,o)=>{let s=r[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,d=u.split(".").pop()??u,m=l?a?.trim()??d:d;return[st(e,t,o,u,d,m,ee(e,u,Ft))]})})}function Qx(e,t,n){let i=te(n,new Set(["imports_statement"])),r=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(m=>m.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;r.push(J(u,d,ee(e,l,Ft),i,c?"namespace":"named"))}return r}function Xx(e,t,n){let i=te(n,new Set(["using_directive"])),r=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,d=a?.text??u;r.push(J(u,d,ee(e,l,Ft),i,a?"namespace":"named"))}return r}var Yx=U("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function ju(e,t){return Yx.get(e,t,()=>{let n=new Set,i=M(e,t);if(!i)return n;let o=i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function Js(e,t,n){return Ve(e,t,i=>eC(e,t,i),()=>Zx(e,t,n))}function Zx(e,t,n){return dC(n).flatMap(i=>mC(e,t,i.clause,i.specifier,i.start,i.end,n))}function eC(e,t,n){let i=tC(e,t,n),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))r.push(...nC(e,t,n,o,i));return r}function tC(e,t,n){let i=te(n,new Set(["import_statement"]));if(yt(t))for(let r of ju(e,t))i.add(r);return i}function nC(e,t,n,i,r){let o=aC(i);if(!o)return[];let s=Xe(e,t,o),a=$e(i,"import_clause");return a?iC(n,a,s,r,cC(i.text)):[on("*",s)]}function iC(e,t,n,i,r){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(rC(s.text,n,i,r));else if(s.type==="namespace_import"){let a=oC(e,s,n,i,r);a&&o.push(a)}else s.type==="named_imports"&&o.push(...sC(s,n,i,r));return o}function rC(e,t,n,i){return J("default",e,t,n,"default",{isTypeOnly:i})}function oC(e,t,n,i,r){let s=$e(t,"identifier")?.text??"";if(!s)return null;let a=uC(e,s);return sn("*",n,{localName:s,usedMembers:a,isTypeOnly:r,used:a.length>0||i.has(s)})}function sC(e,t,n,i){let r=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;r.push(J(c,l,t,n,"named",{isTypeOnly:i||lC(o.text)}))}return r}function aC(e){let t=$e(e,"string");if(!t)return null;let n=$e(t,"string_fragment");return n?n.text:null}function cC(e){return/^\s*import\s+type\b/.test(e)}function lC(e){return/^\s*type\b/.test(e.trim())}function uC(e,t){let n=new Set;for(let i of e.rootNode.descendantsOfType("member_expression")){let r=i.namedChild(0),o=i.namedChild(1);!r||!o||r.type!=="identifier"||r.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function dC(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(n)){let o=r[0],s=r[1],a=r[2];!o||!a||typeof r.index!="number"||t.push({clause:s,specifier:a,start:r.index,end:r.index+o.length})}let i=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(i)){let o=r[0],s=r[1];!o||!s||typeof r.index!="number"||t.push({clause:null,specifier:s,start:r.index,end:r.index+o.length})}return t.sort((r,o)=>r.start-o.start)}function mC(e,t,n,i,r,o,s){let a=Xe(e,t,i),c=Mt(s,r,o);return n?pC(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=Qn(c,u.localName);return sn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||Pe(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?on(u.importedName,u.sourcePath):Xn(u.importedName,u.localName??"",u.sourcePath,u.localName?Pe(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[on("*",a)]}function pC(e){let t=e.trim(),n=/^type\b/.test(t),i=t.replace(/^type\s+/,""),[r,o]=fC(i),s=[];return r&&s.push(...Bu(r,n)),o&&s.push(...Bu(o,n)),s}function Bu(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let i=n.slice(1,-1).trim();return i?Ne(i).map(r=>{let o=r.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function fC(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i==="{"&&t++,i==="}"&&t--,i===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Qs(e,t,n){let i=me(e,t);return i?xC(e,t,i):gC(e,t,n)}function gC(e,t,n){return[...hC(e,t,n),...bC(e,t,n),...yC(e,t,n)]}function hC(e,t,n){let i=[],r=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=Ne(s).map(d=>SC(d.trim())).filter(d=>!!d),l=Yn(n,o.index),u=Yn(n,o.index+o[0].length-1);i.push({kind:"named",sourcePath:Xe(e,t,a),names:c,startLine:l,endLine:u})}return i}function bC(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[2]??"",a=Yn(n,o.index),c=Yn(n,o.index+o[0].length-1);i.push({kind:"star-as",sourcePath:Xe(e,t,s),names:[],startLine:a,endLine:c})}return i}function yC(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=Yn(n,o.index),c=Yn(n,o.index+o[0].length-1);i.push({kind:"star",sourcePath:Xe(e,t,s),names:[],startLine:a,endLine:c})}return i}function SC(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let i=t.match(/^(\w+)$/);return i?i[1]??null:null}function Yn(e,t){let n=0;for(let i=0;i<t&&i<e.length;i++)e.charCodeAt(i)===10&&n++;return n}function xC(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("export_statement")){let o=CC(e,t,r);if(o===void 0)continue;let s=r.startPosition.row,a=r.endPosition.row,c=vC(r,o,s,a);i.push(c)}return i}function CC(e,t,n){let i=$e(n,"string");if(!i)return;let r=$e(i,"string_fragment");if(r)return Xe(e,t,r.text)}function vC(e,t,n,i){let r=$e(e,"export_clause");if(r){let s=[];for(let a of r.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:i}}return $e(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:i}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:i}}function Hu(e,t,n){return eo(e,t,{java:i=>RC(e,t,i),kotlin:i=>kC(e,t,i),scala:i=>wC(e,t,i)},()=>He(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(i,r)=>{let o=i[1]?.trim();return o?LC(e,t,o,r):[]}))}function RC(e,t,n){let i=te(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){r.push(sn("*",ee(e,l,Fe)));continue}let u=l.split(".").pop()??l;r.push(J(u,u,ee(e,l,Fe),i))}return r}function kC(e,t,n){let i=te(n,new Set(["import_header","import_list"])),r=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(p=>p.type==="identifier");if(!s)continue;let a=o.namedChildren.some(p=>p.type==="wildcard_import"),c=o.namedChildren.find(p=>p.type==="import_alias");if(a){r.push(sn("*",ee(e,s.text,Fe)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;r.push(J(u,m,ee(e,l,Fe),i))}return r}function wC(e,t,n){let i=te(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){r.push(sn("*",ee(e,c,Fe)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,p]=d.namedChildren;if(!m)continue;let h=m.text,g=p?.text??h;if(h==="_")continue;r.push(J(h,g,ee(e,`${c}.${h}`,Fe),i))}else if(d.type==="identifier"){let m=d.text;r.push(J(m,m,ee(e,`${c}.${m}`,Fe),i))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;r.push(J(l,l,ee(e,u&&a.length>1?`${u}.${l}`:c,Fe),i))}return r}function LC(e,t,n,i){if(n.includes("{")&&n.includes("}")){let r=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return Ne(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),m=u==="_"?r:`${r}.${u}`.replace(/\.\./g,".");return[st(e,t,i,m,u,d)]})}return[st(e,t,i,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function qu(e,t,n){return Ve(e,t,i=>DC(e,t,i),()=>He(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?Ne(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,m=(l??d).trim();return[st(e,t,r,u,d,m,ee(e,u.replace(/\\/g,"."),nn))]}):[]}))}function DC(e,t,n){let i=te(n,new Set(["namespace_use_declaration"])),r=[],o=(s,a,c)=>{r.push(J(a,c,ee(e,s.replace(/\\/g,"."),nn),i))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=Vu(l,c);u&&o(m,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=Vu(c,"");l&&o(d,l,u)}}return r}function Vu(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),i=e.namedChildren.filter(l=>l.type==="name"),r="";n?r=n.text:i.length>=1&&(r=i[0].text);let o=n&&i.length>0?i[i.length-1]:null,s=r.split("\\").pop()??r,a=o?.text??s,c=t?`${t}\\${r}`:r;return{importedName:s,localName:a,qualified:c}}function Wu(e,t,n){return Ve(e,t,i=>IC(e,t,i),()=>NC(n).flatMap(i=>TC(e,t,i,n)))}function IC(e,t,n){let i=te(n,new Set(["import_statement","import_from_statement"])),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Uu(s);if(!a)continue;let c=Jn(e,t,a.qualifiedName);r.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:i.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=PC(s);if(a===null)continue;let c=Jn(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){r.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=Uu(u);d&&r.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:i.has(d.localName),usedMembers:[]})}}return r}function Uu(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function PC(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=$e(e,"import_prefix")?.text??"",n=$e(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function NC(e){let t=e.split(`
95
- `),n=[],i=0;for(let r=0;r<t.length;r++){let o=t[r],s=o.trimStart(),a=i;if(i+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=$i(o);for(;r+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){r++;let m=t[r];c+=`
96
- ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,end:l})}return n}function EC(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let i=n[2].trim();return i.startsWith("(")&&i.endsWith(")")&&(i=i.slice(1,-1).trim()),{kind:"from",module:n[1],clause:i}}function TC(e,t,n,i){let r=Mt(i,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Ne(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),p=(d??m.split(".")[0]??m).trim(),h=Jn(e,t,m),g=Qn(r,p);return[{importedName:m,localName:p,sourcePath:h,kind:"namespace",used:Pe(r,p)||g.length>0,usedMembers:g}]});let s=n.module?Jn(e,t,n.module):null,a=[];for(let c of Ne(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:s,kind:"named",used:Pe(r,m),usedMembers:[]})}return a}import{basename as _C}from"path";function Gu(e,t,n){return Ve(e,t,i=>$C(e,t,i),()=>FC(e,t,n))}function FC(e,t,n){return He(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(i,r)=>{let o=i[1],s=i[2];if(!o||!s)return[];let a=o==="require_relative"?Qr(e,t,s):null;if(a){let c=zu(s);return[Xn(c,c,a,Pe(r,c))]}return[on(s,a)]})}function $C(e,t,n){let i=te(n,new Set([])),r=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(p=>p.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?Qr(e,t,d):null;if(m){let p=zu(d);r.push(J(p,p,m,i))}else r.push(on(d,m))}return r}function zu(e){return Mr(_C(e).replace(/\.[^.]+$/,""),/_/)}function Ku(e,t,n){return Ve(e,t,i=>AC(e,t,i),()=>He(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?MC(e,t,o,r):[]}))}function AC(e,t,n){let i=te(n,new Set(["use_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of Ai(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Ct(e,t,a.qualifiedName)??Ct(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));r.push(J(a.importedName,a.localName,c,i))}}return r}function Ai(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:to(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,i=n.split("::").pop()??n;return[{qualifiedName:to(t,n),importedName:i,localName:i}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=to(t,n.text),o=[];for(let s of i.namedChildren)o.push(...Ai(s,r));return o}case"use_list":{let n=[];for(let i of e.namedChildren)n.push(...Ai(i,t));return n}case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=Ai(n,t),o=i.text;return r.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),i=n?n.text:"";return[{qualifiedName:to(t,`${i}::*`),importedName:"*",localName:"*"}]}default:return[]}}function to(e,t){return e?t?`${e}::${t}`:e:t}function MC(e,t,n,i){let r=n.trim();if(r.includes("{")&&r.includes("}")){let u=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),d=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return Ne(d).flatMap(m=>{let p=m.trim();if(!p||p==="self")return[];let[h,g]=p.split(/\s+as\s+/),b=h?.trim();if(!b)return[];let S=(g??b.split("::").pop()??b).trim(),x=`${u}::${b}`.replace(/::::/g,"::");return[st(e,t,i,x,b.split("::").pop()??b,S,Ct(e,t,u))]})}let[o,s]=r.split(/\s+as\s+/),a=o?.trim()??r,c=(s??a.split("::").pop()??a).trim(),l=Ct(e,t,a)??Ct(e,t,a.split("::").slice(0,-1).join("::"));return[st(e,t,i,a,a.split("::").pop()??a,c,l)]}function Ju(e,t,n){let i=me(e,t);if(i)return OC(e,t,i);let r=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&r.push(...BC(e,t,s))}return r}function OC(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("use_declaration")){if(!jC(r))continue;let o=r.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of Ai(o,""))s.importedName&&i.push(Xs(e,t,s.qualifiedName))}return i}function jC(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function BC(e,t,n){let i=n.trim();if(i.includes("{")&&i.includes("}")){let r=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),o=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return Ne(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${r}::${c?.trim()??a}`.replace(/::::/g,"::");return[Xs(e,t,l)]})}return[Xs(e,t,i)]}function Xs(e,t,n){return{specifier:n,sourcePath:Ct(e,t,n)??Ct(e,t,n.split("::").slice(0,-1).join("::"))}}function an({language:e,extensions:t,imports:n,parseImports:i}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:i}}function Qu(e,t){let n=t.toLowerCase();for(let i of e)for(let r of i.extensions)if(n.endsWith(r))return i;return null}var HC={language:"javascript",extensions:tn,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Js,parseReExports:Qs},VC=an({language:"python",extensions:Wr,imports:"ast-with-regex-fallback",parseImports:Wu}),qC=an({language:"jvm",extensions:Fe,imports:"ast-dispatch-with-regex-fallback",parseImports:Hu}),UC={language:"rust",extensions:Gr,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Ku,parseExports:Ju},WC=an({language:"ruby",extensions:zr,imports:"ast-with-regex-fallback",parseImports:Gu}),GC=an({language:"c/cpp",extensions:Kr,imports:"ast-with-regex-fallback",parseImports:$u}),zC=an({language:"dotnet",extensions:Ft,imports:"ast-dispatch-with-regex-fallback",parseImports:Ou}),KC={language:"dart",extensions:Jr,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Au,parseExports:Mu},JC=an({language:"php",extensions:nn,imports:"ast-with-regex-fallback",parseImports:qu}),QC=[HC,VC,qC,UC,WC,GC,zC,KC,JC];function no(e){return Qu(QC,e)}var Ys={clearGroups:["whole-project","source-file"]},XC=U("source-imports",Ys),YC=U("source-exports",Ys),ZC=U("source-reexports",Ys);function Mi(e,t){let n=Qe(t);return ZC.get(e,n,()=>{let i=no(n);if(!i?.parseReExports)return[];let r=M(e,n);return r?i.parseReExports(e,n,r):[]})}function fe(e,t){let n=Qe(t);return XC.get(e,n,()=>{let i=no(n);if(!i)return[];let r=M(e,n);return r?i.parseImports(e,n,r):[]})}function io(e,t){let n=Qe(t);return YC.get(e,n,()=>{let i=no(n);if(!i?.parseExports)return[];let r=M(e,n);return r?i.parseExports(e,n,r):[]})}var ev=U("file-dep-graph",{clearGroups:["whole-project"]});function ne(e,t){return ev.get(e,t??"",()=>{let n=new Map,i=new Set(j(e,{includeIgnored:!1})),r=(o,s)=>nv(e,n,i,o,s);for(let o of tv(e,t))r(o.from_file,o.to_file);for(let o of i)if(!(t&&!o.includes(t)))for(let s of fe(e,o))s.sourcePath&&r(o,s.sourcePath);return n})}function tv(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
93
+ ORDER BY start_line, end_line`,t)}function ix(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:$(e.symbol),parentTypeName:it(e.symbol),isFunctionLike:se(e.symbol),isTypeLike:Z(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function rt(e,t={}){return Ei(e,t.scope)}function Ei(e,t){return j(e,{scope:t,includeIgnored:!1}).flatMap(n=>G(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Hr(e,t,n={}){if(t.length===0)return[];let i=t.flatMap(r=>G(e,r)).filter(r=>!e.isIgnored(r.relativePath));return n.onlyDocumented&&(i=i.filter(r=>r.documentation!==null&&r.documentation!=="")),n.sort&&(i=i.sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.startLine-o.startLine||r.endLine-o.endLine)),i.map(r=>({startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,shortName:y(r.symbol),signature:Yt(Zt(r.documentation)),relativePath:r.relativePath,enclosingSymbol:r.enclosingSymbol}))}function qs(e){let t=new Map,n=e.map((i,r)=>({definition:i,index:r,span:i.endLine-i.startLine})).sort((i,r)=>i.span-r.span||i.index-r.index);for(let{definition:i}of n)for(let r=i.startLine;r<=i.endLine;r+=1)t.has(r)||t.set(r,i);return t}function je(e,t){let n=Lu.get(e);return n||(n=qs(e),Lu.set(e,n)),n.get(t)??null}function en(e,t){let n=G(e,t.relative_path).find(i=>i.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function rx(e,t,n){let i=M(e,t),r=js(e,t);return r?ux(n,r,i):i?ox(n,i):n}function ox(e,t){let n=t.split(/\r?\n/),i=sx(e,n),r=ax(e,i),o=cx(r,n);return lx(e,o)}function sx(e,t){let n=e.some(r=>Vr(r.symbol))?px(t):null,i=new Map;for(let r of e)i.set(r.symbolId,mx(t,n,r));return i}function ax(e,t){return e.filter(n=>Vr(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,i)=>n.startLine-i.startLine||n.definition.startLine-i.definition.startLine||n.definition.symbol.localeCompare(i.definition.symbol))}function cx(e,t){let n=new Map;for(let i=0;i<e.length;i+=1){let r=e[i],o=e[i+1],s=o?Math.max(r.startLine,o.startLine-1):t.length-1;n.set(r.definition.symbolId,{startLine:r.startLine,endLine:fx(t,r.definition,r.startLine,s)})}return n}function lx(e,t){return e.map(n=>{let i=t.get(n.symbolId);return i?{...n,startLine:i.startLine,endLine:i.endLine}:n})}function ux(e,t,n=null){let i=new Map;for(let r of t){let o=i.get(r.name);o?o.push(r):i.set(r.name,[r])}return e.map(r=>{if(!dx(r)||!r.leaf)return Du(r,n);let o=i.get(r.leaf);if(!o||o.length===0)return Du(r,n);let s=o[0],a=Math.abs(s.startLine-r.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-r.startLine);u<a&&(s=l,a=u)}return{...r,startLine:s.startLine,endLine:s.endLine}})}function dx(e){return Vr(e.symbol)?!0:Z(e.symbol)==="term"&&it(e.symbol)===null}function Du(e,t){if(!t||!e.leaf||Z(e.symbol)!=="term"||it(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>i.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function mx(e,t,n){if(!Vr(n.symbol))return n.startLine;let i=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return i;let r=t.get(n.leaf);if(!r||r.length===0)return i;let o=null;for(let s of r){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??i}function px(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,i=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,r=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<e.length;a+=1){let c=e[a]??"";for(let u of c.matchAll(t))u[1]&&s(u[1],a);for(let u of c.matchAll(n))u[1]&&s(u[1],a);let l=c.match(i);l?.[1]&&s(l[1],a);for(let u of c.matchAll(r))u[1]&&s(u[1],a)}return o}function fx(e,t,n,i){let r=Math.max(n,Math.min(e.length-1,i)),o=Math.max(n,Math.min(r,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=r;l+=1){let u=gx(e[l]??"");for(let d of u)d==="{"?(s+=1,c=!0):d==="}"?s=Math.max(0,s-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function gx(e){let t="",n=null,i=!1;for(let r=0;r<e.length;r+=1){let o=e[r],s=e[r+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-r);break}if(n){if(i){i=!1,t+=" ";continue}if(o==="\\"){i=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function Vr(e){return e.includes("().")}function qr(e){let t=pe(e);if("kind"in t)return[];let n=[];for(let i=t.descriptors.length-2;i>=0;i-=1){let r=t.descriptors[i];r?.suffix==="type"&&r.name&&n.push(r.name)}return n}import{existsSync as Px}from"fs";import{basename as Iu,isAbsolute as Nx,join as Ex}from"path";function B(e,t){let n=zn(e,t.trim());if(n)return n;let i=Cx(e,t);if(i)return i;let r=hx(e,t);return r||xx(e,t)}function hx(e,t){let n=Ws(t),i=Us(n);if(!i)return null;let r=`%${i.path}%`,o=i.leaf,a=bx(e,r,o,n)[0];return a?en(e,a):null}function bx(e,t,n,i){let r=Wn([],[...yx(e,t,n),...Sx(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Gn(o,i)>1);return r.sort((o,s)=>Gn(s,i)-Gn(o,i)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),r}function yx(e,t,n){return qn(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function Sx(e,t,n){return Un(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function xx(e,t){let n=Ws(t),i=Dx(t),r=wx(e,i),o=Ix(r,t,n);if(o&&!e.isIgnored(o.relative_path))return en(e,o);let s=null;for(let a of r){if(e.isIgnored(a.relative_path))continue;let c=Lx(a,t,n,i);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?en(e,s.row):null}function Cx(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,i,r,o]=n,s=Math.max(0,parseInt(r,10)-1),a=Math.max(s,parseInt(o,10)-1),c=vx(e,i,s,a)??Rx(e,i,s,a);return c&&!e.isIgnored(c.relative_path)?en(e,c):null}function vx(e,t,n,i){return qn(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function Rx(e,t,n,i){return Un(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function zn(e,t){let i=qn(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??Un(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!i||e.isIgnored(i.relative_path)?null:en(e,i)}function Ur(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=kx(e,t.symbolId)[0];return n?en(e,n):null}function kx(e,t){let n=qn(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),i=Un(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Wn(n,i)}function wx(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),i=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),r=n.join(`
94
+ AND `),o=qn(e,{where:r,params:i,limit:200}),s=Un(e,{where:r,params:i,limit:200});return Wn(o,s)}function Lx(e,t,n,i){let r=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,d=y(e.symbol),m=$(e.symbol),p=e.display_name??"",h=e.symbol.toLowerCase(),g=d.toLowerCase(),b=m.toLowerCase(),S=p.toLowerCase(),x=e.relative_path.toLowerCase(),I=/[/:.]/.test(n),L=Us(n),C=L?.leaf.toLowerCase(),D=0;return(u===r||u===o)&&(D+=1150),(d===r||d===o)&&(D+=1100),p===s&&(D+=1180),m===s&&(D+=1160),(`${m}()`===r||`${m}()`===o)&&(D+=955),(h===a||h===c)&&(D+=1e3),(g===a||g===c)&&(D+=950),(x===a||x===c)&&(D+=925),(x.endsWith(`/${c}`)||x.endsWith(`/${a}`))&&(D+=875),S===l&&(D+=850),b===l&&(D+=825),(`${b}()`===a||`${b}()`===c)&&(D+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(D+=800),h.includes(c)&&(D+=120),g.includes(c)&&(D+=140),x.includes(c)&&(D+=140),S.includes(c)&&(D+=110),i.every(k=>{let A=k.toLowerCase();return h.includes(A)||g.includes(A)||x.includes(A)||S.includes(A)})&&(D+=100+i.length*15),L&&x.includes(L.path.toLowerCase())&&(D+=360,C&&(b===C||`${b}()`===C||`${b}()`==`${C}()`)&&(D+=700),xe(e.symbol)&&(D+=180)),se(e.symbol)&&b===l&&(D+=60),!I&&Tt(e.symbol)&&(D-=160),D-=Math.min(50,Math.max(0,e.end_line-e.start_line)),D}function Us(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let i=t.slice(n+1).replace(/\(\)$/,"");return!i||i.includes(".")?null:{path:t.slice(0,n),leaf:i}}function Ws(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function Dx(e){let t=Ws(e),n=t.split(/[^A-Za-z0-9_]+/).map(i=>i.trim()).filter(i=>i.length>0);return n.length>0?[...new Set(n)]:[t]}function Ix(e,t,n){let i=t.trim(),r=e.filter(o=>{let s=y(o.symbol),a=(o.display_name??"").trim();return o.symbol===i||s===i||s===n||a===i||a===n||`${a}()`===i||Gn(o,n)>1||o.relative_path===i});return r.length===0?null:(r.sort((o,s)=>Gn(s,n)-Gn(o,n)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.relative_path.localeCompare(s.relative_path)||o.symbol.localeCompare(s.symbol)),r[0]??null)}function Gn(e,t){let n=Us(t);if(!n)return 0;let i=e.relative_path.toLowerCase(),r=$(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return i.includes(o)?r!==s?1:xe(e.symbol)?it(e.symbol)===null?5:4:it(e.symbol)===null?3:2:0}function Ie(e,t){let n=Pu(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Tx(e,t)}function Kn(e,t){return Pu(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Tx(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=Nx(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=Ex(e.config.projectRoot,i);return Px(r)?i:null}function Pu(e,t,n){let i=Nu(t);if(!i)return[];let r=j(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:_x(a,i)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(r.length===0){let a=B(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=r.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=r.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?r:[r[0]]}function _x(e,t){let n=Nu(e),i=Iu(n),r=Iu(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),i===r&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function Nu(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as QR}from"path";import{existsSync as Wr}from"fs";import{basename as $x,dirname as _t,extname as xt,join as Ke,relative as Ti,resolve as Be}from"path";var Fx=Y("indexed-paths",{clearGroups:[]}),tn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Gr=[".py",".pyi"],$e=[".java",".scala",".kt",".kts"],zr=[".rs"],Kr=[".rb"],Jr=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],$t=[".cs",".vb"],Qr=[".dart"],nn=[".php"],Ax=new Set(tn),Gs=new Set(Gr),Eu=new Set($e),zs=new Set(zr),Ks=new Set(Kr),Tu=new Set(Jr),_u=new Set($t),Js=new Set(Qr),$u=new Set(nn),Mx=[{extensions:tn,lookup:Ax},{extensions:Gr,lookup:Gs},{extensions:$e,lookup:Eu},{extensions:zr,lookup:zs},{extensions:Kr,lookup:Ks},{extensions:Jr,lookup:Tu},{extensions:$t,lookup:_u},{extensions:Qr,lookup:Js},{extensions:nn,lookup:$u}];function Ft(e,t){return t.has(xt(e).toLowerCase())}function Ox(e){return Ft(e,Gs)}function jx(e){return Ft(e,Eu)}function Bx(e){return Ft(e,zs)}function Hx(e){return Ft(e,Ks)}function Vx(e){return Ft(e,Tu)}function qx(e){return Ft(e,_u)}function Fu(e){return xt(e).toLowerCase()===".vb"}function Ux(e){return Ft(e,Js)}function Wx(e){return Ft(e,$u)}function Qs(e){let t=xt(e).toLowerCase();for(let n of Mx)if(n.lookup.has(t))return n.extensions;return tn}function Gx(e){return jx(e)||qx(e)||Wx(e)}function Qe(e,t,n){return Ox(t)?Jn(e,t,n):Bx(t)?Ct(e,t,n):Hx(t)?Xr(e,t,n):Vx(t)?Yr(e,t,n):Gx(t)?ee(e,n.replace(/\\/g,"."),Qs(t)):Ux(t)?Zr(e,t,n):zx(e,t,n)}function zx(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let i=_t(Ke(e.config.projectRoot,t)),r=Be(i,n),o=_i(e);for(let s of Yx(r)){let a=Je(Ti(e.config.projectRoot,s));if(o.has(a)||Wr(s))return a}return Je(Ti(e.config.projectRoot,r))}function Jn(e,t,n){let i=_i(e),r;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=_t(Ke(e.config.projectRoot,t));for(let l=1;l<s;l++)c=_t(c);r=a?Be(c,a.replace(/\./g,"/")):c}else r=Be(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Kx(r)){let s=Je(Ti(e.config.projectRoot,o));if(i.has(s)||Wr(o))return s}return null}function Ct(e,t,n){if(!n)return null;let i=n.replace(/\s+as\s+.+$/,"").trim();if(!i.startsWith("crate::")&&!i.startsWith("self::")&&!i.startsWith("super::"))return null;let r=_t(Ke(e.config.projectRoot,t)),o;return i.startsWith("crate::")?o=Be(e.config.projectRoot,"src",i.slice(7).replace(/::/g,"/")):i.startsWith("self::")?o=Be(r,i.slice(6).replace(/::/g,"/")):o=Be(_t(r),i.slice(7).replace(/::/g,"/")),Xs(e,Jx(o))}function Xr(e,t,n){let i=_t(Ke(e.config.projectRoot,t)),r=Be(i,n);return Xs(e,Qx(r))}function Yr(e,t,n){let i=_t(Ke(e.config.projectRoot,t)),r=[Be(i,n),Be(e.config.projectRoot,n),Be(e.config.projectRoot,"include",n),Be(e.config.projectRoot,"src",n)];return Xs(e,r)}function ee(e,t,n){let i=_i(e),r=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=r.replace(/\./g,"/"),s=r.split(".").pop()??r;for(let c of n){let l=`${o}${c}`,u=[...i].find(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...i].find(u=>$x(u)===`${s}${c}`);if(l)return l}let a=[...i].filter(c=>n.includes(xt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Zr(e,t,n){let i=_i(e);if(n.startsWith("package:")){let s=n.slice(8),a=s.indexOf("/");if(a<0)return null;let c=s.slice(a+1),l=Je(c.startsWith("lib/")?c:`lib/${c}`);return i.has(l)?l:null}let r=_t(Ke(e.config.projectRoot,t)),o=Be(r,n);for(let s of Xx(o)){let a=Je(Ti(e.config.projectRoot,s));if(i.has(a)||Wr(s))return a}return null}function Kx(e){let t=xt(e);return Gs.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Ke(e,"__init__.py"),Ke(e,"__init__.pyi")]}function Xs(e,t){let n=_i(e);for(let i of t){let r=Je(Ti(e.config.projectRoot,i));if(n.has(r)||Wr(i))return r}return null}function Jx(e){let t=xt(e);return zs.has(t)?[e]:[`${e}.rs`,Ke(e,"mod.rs")]}function Qx(e){let t=xt(e);return Ks.has(t)?[e]:[`${e}.rb`,Ke(e,"index.rb")]}function Xx(e){let t=xt(e);return Js.has(t)?[e]:[`${e}.dart`,e]}function Yx(e){let t=xt(e),n=new Set;if(t){n.add(e);for(let i of tn)n.add(e.slice(0,-t.length)+i)}else for(let i of tn)n.add(`${e}${i}`),n.add(Ke(e,`index${i}`));return[...n]}function _i(e){return Fx.get(e,()=>new Set(j(e,{includeIgnored:!1}).map(Je)))}function Je(e){return e.replace(/\\/g,"/")}import{basename as Mu}from"path";function rn(e){return e.replace(/'''[\s\S]*?'''/g,At).replace(/"""[\s\S]*?"""/g,At).replace(/#.*$/gm,At).replace(/\/\/.*$/gm,At).replace(/\/\*[\s\S]*?\*\//g,At).replace(/`(?:\\[\s\S]|[^`])*`/g,At).replace(/'(?:\\.|[^'\\\r\n])*'/g,At).replace(/"(?:\\.|[^"\\\r\n])*"/g,At)}function At(e){return e.replace(/[^\r\n]/g," ")}var aB=Kt("stripped-lines",{clearGroups:["whole-project","source-file"]});Et({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{eo=null,$i=""},clearFile:()=>{eo=null,$i=""}});var eo=null,$i="";function Zx(e){return eo===e||(eo=e,$i=rn(e)),$i}function Mt(e,t,n){let i=Zx(e);return`${i.slice(0,t)}${" ".repeat(n-t)}${i.slice(n)}`}function Pe(e,t){return new RegExp(`\\b${Au(t)}\\b`,"m").test(e)}function Qn(e,t){let n=new Set,i=new RegExp(`\\b${Au(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let r of e.matchAll(i)){let o=r[1];o&&n.add(o)}return[...n]}function Au(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fi(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var eC=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Ne(e){let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let o=e[r];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(i,r)),i=r+1)}return t.push(e.slice(i)),t}function Fe(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function te(e,t){let n=new Set,i=(r,o)=>{let s=o||t.has(r.type);!s&&eC.has(r.type)&&n.add(r.text);for(let a of r.children)i(a,s)};return i(e.rootNode,!1),n}function ot(e,t,n,i,r,o,s){return{importedName:r,localName:o,sourcePath:s??ee(e,i,Qs(t)),kind:"named",used:Pe(n,o),usedMembers:[]}}function J(e,t,n,i,r="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function Xn(e,t,n,i,r="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i,usedMembers:o,isTypeOnly:s.isTypeOnly}}function on(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function sn(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function He(e,t,n){let i=[];for(let r of e.matchAll(t)){let o=r[0];if(!o||typeof r.index!="number")continue;let s=Mt(e,r.index,r.index+o.length);for(let a of n(r,s))i.push(a)}return i}function Ve(e,t,n,i){let r=me(e,t);if(r){let o=n(r);if(o)return o}return i()}function to(e,t,n,i){let r=me(e,t),o=W(t),s=o?n[o]:void 0;return r&&s?s(r):i()}function Ou(e,t,n){return Ve(e,t,i=>nC(e,t,i),()=>tC(e,t,n))}function tC(e,t,n){return He(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,r)=>{let o=i[1]?.trim();if(!o)return[];let s=Mu(o).replace(/\.[^.]+$/,"");return[Xn(o,s,Yr(e,t,o),Pe(r,s))]})}function nC(e,t,n){let i=te(n,new Set(["preproc_include"])),r=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=Mu(s).replace(/\.[^.]+$/,"");r.push(J(s,a,Yr(e,t,s),i))}return r}function ju(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=r[1]?.trim(),s=r[2]?.trim()??null,a=r[0];if(!o||!a||typeof r.index!="number")continue;let c=Mt(n,r.index,r.index+a.length);i.push({importedName:o,localName:s,sourcePath:Zr(e,t,o),kind:s?"namespace":"side-effect",used:s?Pe(c,s):!0,usedMembers:s?Qn(c,s):[]})}return i}function Bu(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=r[1]?.trim();o&&i.push({specifier:o,sourcePath:Zr(e,t,o)})}return i}function Hu(e,t,n){return to(e,t,{csharp:i=>rC(e,t,i),vb:i=>iC(e,t,i)},()=>{let i=Fu(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return He(n,i,(r,o)=>{let s=r[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,d=u.split(".").pop()??u,m=l?a?.trim()??d:d;return[ot(e,t,o,u,d,m,ee(e,u,$t))]})})}function iC(e,t,n){let i=te(n,new Set(["imports_statement"])),r=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(m=>m.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;r.push(J(u,d,ee(e,l,$t),i,c?"namespace":"named"))}return r}function rC(e,t,n){let i=te(n,new Set(["using_directive"])),r=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,d=a?.text??u;r.push(J(u,d,ee(e,l,$t),i,a?"namespace":"named"))}return r}var oC=U("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Vu(e,t){return oC.get(e,t,()=>{let n=new Set,i=M(e,t);if(!i)return n;let o=i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function Ys(e,t,n){return Ve(e,t,i=>aC(e,t,i),()=>sC(e,t,n))}function sC(e,t,n){return yC(n).flatMap(i=>SC(e,t,i.clause,i.specifier,i.start,i.end,n))}function aC(e,t,n){let i=cC(e,t,n),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))r.push(...lC(e,t,n,o,i));return r}function cC(e,t,n){let i=te(n,new Set(["import_statement"]));if(yt(t))for(let r of Vu(e,t))i.add(r);return i}function lC(e,t,n,i,r){let o=fC(i);if(!o)return[];let s=Qe(e,t,o),a=Fe(i,"import_clause");return a?uC(n,a,s,r,gC(i.text)):[on("*",s)]}function uC(e,t,n,i,r){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(dC(s.text,n,i,r));else if(s.type==="namespace_import"){let a=mC(e,s,n,i,r);a&&o.push(a)}else s.type==="named_imports"&&o.push(...pC(s,n,i,r));return o}function dC(e,t,n,i){return J("default",e,t,n,"default",{isTypeOnly:i})}function mC(e,t,n,i,r){let s=Fe(t,"identifier")?.text??"";if(!s)return null;let a=bC(e,s);return sn("*",n,{localName:s,usedMembers:a,isTypeOnly:r,used:a.length>0||i.has(s)})}function pC(e,t,n,i){let r=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;r.push(J(c,l,t,n,"named",{isTypeOnly:i||hC(o.text)}))}return r}function fC(e){let t=Fe(e,"string");if(!t)return null;let n=Fe(t,"string_fragment");return n?n.text:null}function gC(e){return/^\s*import\s+type\b/.test(e)}function hC(e){return/^\s*type\b/.test(e.trim())}function bC(e,t){let n=new Set;for(let i of e.rootNode.descendantsOfType("member_expression")){let r=i.namedChild(0),o=i.namedChild(1);!r||!o||r.type!=="identifier"||r.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function yC(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(n)){let o=r[0],s=r[1],a=r[2];!o||!a||typeof r.index!="number"||t.push({clause:s,specifier:a,start:r.index,end:r.index+o.length})}let i=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(i)){let o=r[0],s=r[1];!o||!s||typeof r.index!="number"||t.push({clause:null,specifier:s,start:r.index,end:r.index+o.length})}return t.sort((r,o)=>r.start-o.start)}function SC(e,t,n,i,r,o,s){let a=Qe(e,t,i),c=Mt(s,r,o);return n?xC(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=Qn(c,u.localName);return sn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||Pe(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?on(u.importedName,u.sourcePath):Xn(u.importedName,u.localName??"",u.sourcePath,u.localName?Pe(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[on("*",a)]}function xC(e){let t=e.trim(),n=/^type\b/.test(t),i=t.replace(/^type\s+/,""),[r,o]=CC(i),s=[];return r&&s.push(...qu(r,n)),o&&s.push(...qu(o,n)),s}function qu(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let i=n.slice(1,-1).trim();return i?Ne(i).map(r=>{let o=r.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function CC(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i==="{"&&t++,i==="}"&&t--,i===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Zs(e,t,n){let i=me(e,t);return i?DC(e,t,i):vC(e,t,n)}function vC(e,t,n){return[...RC(e,t,n),...kC(e,t,n),...wC(e,t,n)]}function RC(e,t,n){let i=[],r=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=Ne(s).map(d=>LC(d.trim())).filter(d=>!!d),l=Yn(n,o.index),u=Yn(n,o.index+o[0].length-1);i.push({kind:"named",sourcePath:Qe(e,t,a),names:c,startLine:l,endLine:u})}return i}function kC(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[2]??"",a=Yn(n,o.index),c=Yn(n,o.index+o[0].length-1);i.push({kind:"star-as",sourcePath:Qe(e,t,s),names:[],startLine:a,endLine:c})}return i}function wC(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=Yn(n,o.index),c=Yn(n,o.index+o[0].length-1);i.push({kind:"star",sourcePath:Qe(e,t,s),names:[],startLine:a,endLine:c})}return i}function LC(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let i=t.match(/^(\w+)$/);return i?i[1]??null:null}function Yn(e,t){let n=0;for(let i=0;i<t&&i<e.length;i++)e.charCodeAt(i)===10&&n++;return n}function DC(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("export_statement")){let o=IC(e,t,r);if(o===void 0)continue;let s=r.startPosition.row,a=r.endPosition.row,c=PC(r,o,s,a);i.push(c)}return i}function IC(e,t,n){let i=Fe(n,"string");if(!i)return;let r=Fe(i,"string_fragment");if(r)return Qe(e,t,r.text)}function PC(e,t,n,i){let r=Fe(e,"export_clause");if(r){let s=[];for(let a of r.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:i}}return Fe(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:i}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:i}}function Uu(e,t,n){return to(e,t,{java:i=>NC(e,t,i),kotlin:i=>EC(e,t,i),scala:i=>TC(e,t,i)},()=>He(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(i,r)=>{let o=i[1]?.trim();return o?_C(e,t,o,r):[]}))}function NC(e,t,n){let i=te(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){r.push(sn("*",ee(e,l,$e)));continue}let u=l.split(".").pop()??l;r.push(J(u,u,ee(e,l,$e),i))}return r}function EC(e,t,n){let i=te(n,new Set(["import_header","import_list"])),r=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(p=>p.type==="identifier");if(!s)continue;let a=o.namedChildren.some(p=>p.type==="wildcard_import"),c=o.namedChildren.find(p=>p.type==="import_alias");if(a){r.push(sn("*",ee(e,s.text,$e)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;r.push(J(u,m,ee(e,l,$e),i))}return r}function TC(e,t,n){let i=te(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){r.push(sn("*",ee(e,c,$e)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,p]=d.namedChildren;if(!m)continue;let h=m.text,g=p?.text??h;if(h==="_")continue;r.push(J(h,g,ee(e,`${c}.${h}`,$e),i))}else if(d.type==="identifier"){let m=d.text;r.push(J(m,m,ee(e,`${c}.${m}`,$e),i))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;r.push(J(l,l,ee(e,u&&a.length>1?`${u}.${l}`:c,$e),i))}return r}function _C(e,t,n,i){if(n.includes("{")&&n.includes("}")){let r=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return Ne(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),m=u==="_"?r:`${r}.${u}`.replace(/\.\./g,".");return[ot(e,t,i,m,u,d)]})}return[ot(e,t,i,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Gu(e,t,n){return Ve(e,t,i=>$C(e,t,i),()=>He(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?Ne(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,m=(l??d).trim();return[ot(e,t,r,u,d,m,ee(e,u.replace(/\\/g,"."),nn))]}):[]}))}function $C(e,t,n){let i=te(n,new Set(["namespace_use_declaration"])),r=[],o=(s,a,c)=>{r.push(J(a,c,ee(e,s.replace(/\\/g,"."),nn),i))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=Wu(l,c);u&&o(m,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=Wu(c,"");l&&o(d,l,u)}}return r}function Wu(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),i=e.namedChildren.filter(l=>l.type==="name"),r="";n?r=n.text:i.length>=1&&(r=i[0].text);let o=n&&i.length>0?i[i.length-1]:null,s=r.split("\\").pop()??r,a=o?.text??s,c=t?`${t}\\${r}`:r;return{importedName:s,localName:a,qualified:c}}function Ku(e,t,n){return Ve(e,t,i=>FC(e,t,i),()=>MC(n).flatMap(i=>jC(e,t,i,n)))}function FC(e,t,n){let i=te(n,new Set(["import_statement","import_from_statement"])),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=zu(s);if(!a)continue;let c=Jn(e,t,a.qualifiedName);r.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:i.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=AC(s);if(a===null)continue;let c=Jn(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){r.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=zu(u);d&&r.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:i.has(d.localName),usedMembers:[]})}}return r}function zu(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function AC(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Fe(e,"import_prefix")?.text??"",n=Fe(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function MC(e){let t=e.split(`
95
+ `),n=[],i=0;for(let r=0;r<t.length;r++){let o=t[r],s=o.trimStart(),a=i;if(i+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=Fi(o);for(;r+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){r++;let m=t[r];c+=`
96
+ ${m}`,l+=1+m.length,u+=Fi(m),i+=m.length+1}let d=OC(c);d&&n.push({...d,start:a,end:l})}return n}function OC(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let i=n[2].trim();return i.startsWith("(")&&i.endsWith(")")&&(i=i.slice(1,-1).trim()),{kind:"from",module:n[1],clause:i}}function jC(e,t,n,i){let r=Mt(i,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Ne(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),p=(d??m.split(".")[0]??m).trim(),h=Jn(e,t,m),g=Qn(r,p);return[{importedName:m,localName:p,sourcePath:h,kind:"namespace",used:Pe(r,p)||g.length>0,usedMembers:g}]});let s=n.module?Jn(e,t,n.module):null,a=[];for(let c of Ne(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:s,kind:"named",used:Pe(r,m),usedMembers:[]})}return a}import{basename as BC}from"path";function Ju(e,t,n){return Ve(e,t,i=>VC(e,t,i),()=>HC(e,t,n))}function HC(e,t,n){return He(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(i,r)=>{let o=i[1],s=i[2];if(!o||!s)return[];let a=o==="require_relative"?Xr(e,t,s):null;if(a){let c=Qu(s);return[Xn(c,c,a,Pe(r,c))]}return[on(s,a)]})}function VC(e,t,n){let i=te(n,new Set([])),r=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(p=>p.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?Xr(e,t,d):null;if(m){let p=Qu(d);r.push(J(p,p,m,i))}else r.push(on(d,m))}return r}function Qu(e){return Or(BC(e).replace(/\.[^.]+$/,""),/_/)}function Xu(e,t,n){return Ve(e,t,i=>qC(e,t,i),()=>He(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?UC(e,t,o,r):[]}))}function qC(e,t,n){let i=te(n,new Set(["use_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of Ai(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Ct(e,t,a.qualifiedName)??Ct(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));r.push(J(a.importedName,a.localName,c,i))}}return r}function Ai(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:no(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,i=n.split("::").pop()??n;return[{qualifiedName:no(t,n),importedName:i,localName:i}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=no(t,n.text),o=[];for(let s of i.namedChildren)o.push(...Ai(s,r));return o}case"use_list":{let n=[];for(let i of e.namedChildren)n.push(...Ai(i,t));return n}case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=Ai(n,t),o=i.text;return r.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),i=n?n.text:"";return[{qualifiedName:no(t,`${i}::*`),importedName:"*",localName:"*"}]}default:return[]}}function no(e,t){return e?t?`${e}::${t}`:e:t}function UC(e,t,n,i){let r=n.trim();if(r.includes("{")&&r.includes("}")){let u=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),d=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return Ne(d).flatMap(m=>{let p=m.trim();if(!p||p==="self")return[];let[h,g]=p.split(/\s+as\s+/),b=h?.trim();if(!b)return[];let S=(g??b.split("::").pop()??b).trim(),x=`${u}::${b}`.replace(/::::/g,"::");return[ot(e,t,i,x,b.split("::").pop()??b,S,Ct(e,t,u))]})}let[o,s]=r.split(/\s+as\s+/),a=o?.trim()??r,c=(s??a.split("::").pop()??a).trim(),l=Ct(e,t,a)??Ct(e,t,a.split("::").slice(0,-1).join("::"));return[ot(e,t,i,a,a.split("::").pop()??a,c,l)]}function Yu(e,t,n){let i=me(e,t);if(i)return WC(e,t,i);let r=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&r.push(...zC(e,t,s))}return r}function WC(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("use_declaration")){if(!GC(r))continue;let o=r.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of Ai(o,""))s.importedName&&i.push(ea(e,t,s.qualifiedName))}return i}function GC(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function zC(e,t,n){let i=n.trim();if(i.includes("{")&&i.includes("}")){let r=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),o=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return Ne(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${r}::${c?.trim()??a}`.replace(/::::/g,"::");return[ea(e,t,l)]})}return[ea(e,t,i)]}function ea(e,t,n){return{specifier:n,sourcePath:Ct(e,t,n)??Ct(e,t,n.split("::").slice(0,-1).join("::"))}}function an({language:e,extensions:t,imports:n,parseImports:i}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:i}}function Zu(e,t){let n=t.toLowerCase();for(let i of e)for(let r of i.extensions)if(n.endsWith(r))return i;return null}var KC={language:"javascript",extensions:tn,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Ys,parseReExports:Zs},JC=an({language:"python",extensions:Gr,imports:"ast-with-regex-fallback",parseImports:Ku}),QC=an({language:"jvm",extensions:$e,imports:"ast-dispatch-with-regex-fallback",parseImports:Uu}),XC={language:"rust",extensions:zr,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Xu,parseExports:Yu},YC=an({language:"ruby",extensions:Kr,imports:"ast-with-regex-fallback",parseImports:Ju}),ZC=an({language:"c/cpp",extensions:Jr,imports:"ast-with-regex-fallback",parseImports:Ou}),ev=an({language:"dotnet",extensions:$t,imports:"ast-dispatch-with-regex-fallback",parseImports:Hu}),tv={language:"dart",extensions:Qr,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:ju,parseExports:Bu},nv=an({language:"php",extensions:nn,imports:"ast-with-regex-fallback",parseImports:Gu}),iv=[KC,JC,QC,XC,YC,ZC,ev,tv,nv];function io(e){return Zu(iv,e)}var ta={clearGroups:["whole-project","source-file"]},rv=U("source-imports",ta),ov=U("source-exports",ta),sv=U("source-reexports",ta);function Mi(e,t){let n=Je(t);return sv.get(e,n,()=>{let i=io(n);if(!i?.parseReExports)return[];let r=M(e,n);return r?i.parseReExports(e,n,r):[]})}function fe(e,t){let n=Je(t);return rv.get(e,n,()=>{let i=io(n);if(!i)return[];let r=M(e,n);return r?i.parseImports(e,n,r):[]})}function ro(e,t){let n=Je(t);return ov.get(e,n,()=>{let i=io(n);if(!i?.parseExports)return[];let r=M(e,n);return r?i.parseExports(e,n,r):[]})}var av=U("file-dep-graph",{clearGroups:["whole-project"]});function ne(e,t){return av.get(e,t??"",()=>{let n=new Map,i=new Set(j(e,{includeIgnored:!1})),r=(o,s)=>lv(e,n,i,o,s);for(let o of cv(e,t))r(o.from_file,o.to_file);for(let o of i)if(!(t&&!o.includes(t)))for(let s of fe(e,o))s.sourcePath&&r(o,s.sourcePath);return n})}function cv(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
97
97
  d1.relative_path AS from_file,
98
98
  d2.relative_path AS to_file
99
99
  FROM mentions m
@@ -111,11 +111,11 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
111
111
  WHERE d1.id != d2.id
112
112
  AND m.role != 1
113
113
  ${e.pathExclusionsFor("d1","d2")}
114
- ${n}`)}function nv(e,t,n,i,r){if(i===r||e.isIgnored(i)||e.isIgnored(r)||!n.has(r))return;let o=t.get(i);o||(o=new Set,t.set(i,o)),o.add(r)}import{existsSync as ro,readFileSync as iv,readdirSync as Yu}from"fs";import{join as Oi}from"path";var rv={files:new Set,pathPrefixes:[]},Zs=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,ov=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,Zu=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],sv=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),av=4,cv=Y("package-surface",{clearGroups:["whole-project"]});function lv(e){return cv.get(e,()=>uv(e.config.projectRoot))}function ei(e,t){let n=lv(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function uv(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of dv(e))for(let o of mv(i))pv(e,r,o,t,n);return t.size===0&&n.length===0?rv:{files:t,pathPrefixes:n}}function dv(e){let t=[],n=td(e,"");return n&&t.push({manifest:n,packageRoot:""}),ed(e,"",t,0),t}function ed(e,t,n,i){if(i>=av)return;let r=Oi(e,t);if(ro(r))for(let o of Yu(r,{withFileTypes:!0})){if(!o.isDirectory()||sv.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=td(e,s);a&&n.push({manifest:a,packageRoot:s}),ed(e,s,n,i+1)}}function td(e,t){try{let n=iv(Oi(e,t,"package.json"),"utf-8"),i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function mv(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return nd(e.exports,t),t}function nd(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))nd(n,t)}function pv(e,t,n,i,r){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of Xu(c))l!==""&&r.push(Zn(t,l));return}let a=o.replace(ov,"");for(let c of Xu(a)){c===a&&c===o&&i.add(Zn(t,o));for(let l of Zu)fv(e,i,t,c+l)}i.add(Zn(t,o))}function Xu(e){let t=[e];return Zs.test(e)&&(t.push(e.replace(Zs,"src/")),t.push(e.replace(Zs,""))),t}function fv(e,t,n,i){let r=Zn(n,i);if(t.add(r),!i.startsWith("src/")||ro(Oi(e,r)))return;let o=Zu.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);gv(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of id(e,n,c,`${l}${o}`))t.add(u)}function gv(e,t,n,i,r){let o=Zn(n,`${i}/index${r}`);ro(Oi(e,o))&&t.add(o)}function id(e,t,n,i){let r=Oi(e,t,n);if(!ro(r))return[];let o=[];for(let s of Yu(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...id(e,t,a,i)):s.isFile()&&s.name===i&&o.push(Zn(t,a))}return o}function Zn(e,t){return e?`${e}/${t}`:t}function K(e){let t=ti(e);return Nv(t)?"test":Ev(t)?"worker":Tv(t)?"entry":_v(t)?"barrel":"source"}function oo(e){return K(e)==="barrel"}function od(e){return hv.get(e,()=>{let t=ne(e),n=De(e).filter(o=>{let s=K(o);return s==="entry"||s==="worker"}),i=new Set,r=new Set;for(;n.length>0;){let o=n.shift();if(!i.has(o)){i.add(o),K(o)==="barrel"&&r.add(o);for(let s of t.get(o)??[])i.has(s)||n.push(s)}}return r})}var hv=Y("live-barrels",{clearGroups:["whole-project"]});function ea(e,t){return od(e).has(ti(t))}function sd(e){let t=od(e);return De(e).filter(n=>oo(n)&&!t.has(n)&&!bv(e,n))}function bv(e,t){let n=ti(t),i=oe(e,n)?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
114
+ ${n}`)}function lv(e,t,n,i,r){if(i===r||e.isIgnored(i)||e.isIgnored(r)||!n.has(r))return;let o=t.get(i);o||(o=new Set,t.set(i,o)),o.add(r)}import{existsSync as oo,readFileSync as uv,readdirSync as td}from"fs";import{join as Oi}from"path";var dv={files:new Set,pathPrefixes:[]},na=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,mv=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,nd=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],pv=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),fv=4,gv=Y("package-surface",{clearGroups:["whole-project"]});function hv(e){return gv.get(e,()=>bv(e.config.projectRoot))}function ei(e,t){let n=hv(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function bv(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of yv(e))for(let o of Sv(i))xv(e,r,o,t,n);return t.size===0&&n.length===0?dv:{files:t,pathPrefixes:n}}function yv(e){let t=[],n=rd(e,"");return n&&t.push({manifest:n,packageRoot:""}),id(e,"",t,0),t}function id(e,t,n,i){if(i>=fv)return;let r=Oi(e,t);if(oo(r))for(let o of td(r,{withFileTypes:!0})){if(!o.isDirectory()||pv.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=rd(e,s);a&&n.push({manifest:a,packageRoot:s}),id(e,s,n,i+1)}}function rd(e,t){try{let n=uv(Oi(e,t,"package.json"),"utf-8"),i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function Sv(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return od(e.exports,t),t}function od(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))od(n,t)}function xv(e,t,n,i,r){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of ed(c))l!==""&&r.push(Zn(t,l));return}let a=o.replace(mv,"");for(let c of ed(a)){c===a&&c===o&&i.add(Zn(t,o));for(let l of nd)Cv(e,i,t,c+l)}i.add(Zn(t,o))}function ed(e){let t=[e];return na.test(e)&&(t.push(e.replace(na,"src/")),t.push(e.replace(na,""))),t}function Cv(e,t,n,i){let r=Zn(n,i);if(t.add(r),!i.startsWith("src/")||oo(Oi(e,r)))return;let o=nd.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);vv(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of sd(e,n,c,`${l}${o}`))t.add(u)}function vv(e,t,n,i,r){let o=Zn(n,`${i}/index${r}`);oo(Oi(e,o))&&t.add(o)}function sd(e,t,n,i){let r=Oi(e,t,n);if(!oo(r))return[];let o=[];for(let s of td(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...sd(e,t,a,i)):s.isFile()&&s.name===i&&o.push(Zn(t,a))}return o}function Zn(e,t){return e?`${e}/${t}`:t}function K(e){let t=ti(e);return Mv(t)?"test":Ov(t)?"worker":jv(t)?"entry":Bv(t)?"barrel":"source"}function so(e){return K(e)==="barrel"}function cd(e){return Rv.get(e,()=>{let t=ne(e),n=De(e).filter(o=>{let s=K(o);return s==="entry"||s==="worker"}),i=new Set,r=new Set;for(;n.length>0;){let o=n.shift();if(!i.has(o)){i.add(o),K(o)==="barrel"&&r.add(o);for(let s of t.get(o)??[])i.has(s)||n.push(s)}}return r})}var Rv=Y("live-barrels",{clearGroups:["whole-project"]});function ia(e,t){return cd(e).has(ti(t))}function ld(e){let t=cd(e);return De(e).filter(n=>so(n)&&!t.has(n)&&!kv(e,n))}function kv(e,t){let n=ti(t),i=oe(e,n)?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
115
115
  FROM defn_enclosing_ranges der
116
116
  JOIN documents d ON d.id = der.document_id
117
117
  WHERE d.relative_path = ?
118
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function we(e,t){let n=K(t);return n==="entry"||n==="worker"||ea(e,t)}function ie(e,t,n){let i=ti(n);if(ei(e,i)||Rv(t,i))return!0;let r=e.config.entryRoots;return r?!!(r.files?.some(o=>ti(o)===i)||r.pathPrefixes?.some(o=>i.startsWith(ti(o)))||r.qualifiedVars?.some(o=>Fv(t,o))||r.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var ad=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),yv=new Set(["default","generateMetadata","generateStaticParams"]),Sv=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),xv=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),Cv=new Set(["load","actions","entries",...ad]),vv=new Set(["default"]);function Rv(e,t){let n=F(e);return n===""?!1:kv(t)?ad.has(n):wv(t)?yv.has(n):Lv(t)?Sv.has(n):Dv(t)?xv.has(n):Iv(t)?Cv.has(n):Pv(t)?vv.has(n):!1}function kv(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function wv(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Lv(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Dv(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Iv(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function Pv(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function Nv(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function Ev(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function Tv(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function _v(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function ti(e){return e.replace(/\\/g,"/")}function Fv(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(rd(i)+"/")&&e.includes(rd(r)+".")}function rd(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function so(e,t,n,i={}){if(!n)return[];let r=M(e,t);return r?r.indexOf(n)===-1?[]:(vt(e,t).get(n)??[]).filter(s=>!$v(s,i)):[]}function $v(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var Av=U("file-identifiers",{clearGroups:["whole-project","source-file"]});function cd(e,t){let n=oe(e,t);return n?n.fileIdentifiers:Av.get(e,t,()=>new Set(vt(e,t).keys()))}var Mv=U("file-ident-lines",{clearGroups:["whole-project","source-file"]});function vt(e,t){let n=oe(e,t);return n?n.identifierLineMap:Mv.get(e,t,()=>jv(e,t))}var Ov=U("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function ld(e,t){let n=oe(e,t);return n?n.identifiersByLine:Ov.get(e,t,()=>{let i=vt(e,t),r=0;for(let s of i.values()){let a=s[s.length-1];a!==void 0&&a>r&&(r=a)}let o=new Array(r+1);for(let s=0;s<=r;s+=1)o[s]=new Set;for(let[s,a]of i)for(let c of a)o[c].add(s);return o})}function jv(e,t){let n=new Map,i=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},r=M(e,t);if(!r)return n;let o=rn(r).split(/\r?\n/),s=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<o.length;a+=1){let c=o[a]??"";for(let l of c.matchAll(s))l[1]&&i(l[1],a)}return n}function ud(e,t){return ta(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
118
+ AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function we(e,t){let n=K(t);return n==="entry"||n==="worker"||ia(e,t)}function ie(e,t,n){let i=ti(n);if(ei(e,i)||Nv(t,i))return!0;let r=e.config.entryRoots;return r?!!(r.files?.some(o=>ti(o)===i)||r.pathPrefixes?.some(o=>i.startsWith(ti(o)))||r.qualifiedVars?.some(o=>Hv(t,o))||r.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var ud=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),wv=new Set(["default","generateMetadata","generateStaticParams"]),Lv=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),Dv=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),Iv=new Set(["load","actions","entries",...ud]),Pv=new Set(["default"]);function Nv(e,t){let n=$(e);return n===""?!1:Ev(t)?ud.has(n):Tv(t)?wv.has(n):_v(t)?Lv.has(n):$v(t)?Dv.has(n):Fv(t)?Iv.has(n):Av(t)?Pv.has(n):!1}function Ev(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Tv(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function _v(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function $v(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Fv(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function Av(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function Mv(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function Ov(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function jv(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function Bv(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function ti(e){return e.replace(/\\/g,"/")}function Hv(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(ad(i)+"/")&&e.includes(ad(r)+".")}function ad(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function ao(e,t,n,i={}){if(!n)return[];let r=M(e,t);return r?r.indexOf(n)===-1?[]:(vt(e,t).get(n)??[]).filter(s=>!Vv(s,i)):[]}function Vv(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var qv=U("file-identifiers",{clearGroups:["whole-project","source-file"]});function dd(e,t){let n=oe(e,t);return n?n.fileIdentifiers:qv.get(e,t,()=>new Set(vt(e,t).keys()))}var Uv=U("file-ident-lines",{clearGroups:["whole-project","source-file"]});function vt(e,t){let n=oe(e,t);return n?n.identifierLineMap:Uv.get(e,t,()=>Gv(e,t))}var Wv=U("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function md(e,t){let n=oe(e,t);return n?n.identifiersByLine:Wv.get(e,t,()=>{let i=vt(e,t),r=0;for(let s of i.values()){let a=s[s.length-1];a!==void 0&&a>r&&(r=a)}let o=new Array(r+1);for(let s=0;s<=r;s+=1)o[s]=new Set;for(let[s,a]of i)for(let c of a)o[c].add(s);return o})}function Gv(e,t){let n=new Map,i=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},r=M(e,t);if(!r)return n;let o=rn(r).split(/\r?\n/),s=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<o.length;a+=1){let c=o[a]??"";for(let l of c.matchAll(s))l[1]&&i(l[1],a)}return n}function pd(e,t){return ra(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
119
119
  m.symbol_id,
120
120
  d.relative_path,
121
121
  COUNT(*) AS ref_count
@@ -125,13 +125,13 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
125
125
  WHERE m.role != 1
126
126
  ${i}
127
127
  ${e.pathExclusionsFor("d")}
128
- GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function dd(e,t){return ta(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
128
+ GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function fd(e,t){return ra(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
129
129
  FROM mentions m
130
130
  JOIN chunks c ON m.chunk_id = c.id
131
131
  JOIN documents d ON c.document_id = d.id
132
132
  WHERE m.role != 1
133
133
  ${i}
134
- ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function ao(e,t){return ta(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
134
+ ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function co(e,t){return ra(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
135
135
  c.start_line AS chunk_start, c.end_line AS chunk_end
136
136
  FROM mentions m
137
137
  JOIN chunks c ON m.chunk_id = c.id
@@ -139,7 +139,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
139
139
  WHERE m.role != 1
140
140
  ${i}
141
141
  ${e.pathExclusionsFor("d")}
142
- ORDER BY d.relative_path, c.start_line`,...n??[])})}function ta(e,t,n){if(!t)return n();if(t.length===0)return[];let i=[];for(let r=0;r<t.length;r+=750)i.push(...n(t.slice(r,r+750)));return i}function md(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Ot(e,t){return md(e)===md(t)}function co(e,t){let n=pd(e);return n?t.filter(i=>pd(i.file)===n):t}function lo(e,t,n,i){let r=n.find(o=>o.file===t);if(r)return r;if(i){let o=new Set(fe(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Ot(a,s.file))return s;return null}return n.length===1?n[0]:null}function pd(e){let t=W(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Bv=Y("global-leaf-index",{clearGroups:["whole-project"]});function cn(e){return Bv.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
142
+ ORDER BY d.relative_path, c.start_line`,...n??[])})}function ra(e,t,n){if(!t)return n();if(t.length===0)return[];let i=[];for(let r=0;r<t.length;r+=750)i.push(...n(t.slice(r,r+750)));return i}function gd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Ot(e,t){return gd(e)===gd(t)}function lo(e,t){let n=hd(e);return n?t.filter(i=>hd(i.file)===n):t}function uo(e,t,n,i){let r=n.find(o=>o.file===t);if(r)return r;if(i){let o=new Set(fe(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Ot(a,s.file))return s;return null}return n.length===1?n[0]:null}function hd(e){let t=W(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var zv=Y("global-leaf-index",{clearGroups:["whole-project"]});function cn(e){return zv.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
143
143
  COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
144
144
  FROM global_symbols gs
145
145
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -153,8 +153,8 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
153
153
  GROUP BY m.symbol_id
154
154
  ) mention_doc ON mention_doc.symbol_id = gs.id
155
155
  WHERE 1 = 1
156
- ${e.symbolNoiseFor("gs")}`),n=new Map;for(let i of t){if(!i.relative_path||e.isIgnored(i.relative_path))continue;let r=F(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.some(s=>s.symbolId===i.id)||o.push({symbol:i.symbol,symbolId:i.id,file:i.relative_path})}return n})}function Ye(e,t,n){if(e.has(t))return e.get(t);let i=n();return e.set(t,i),i}import fd from"path";function Hv(e,t){return e.getReferences().map(n=>{let i=n.getNode();return bd(i,t)})}function Vv(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function gd(e,t,n,i){let r=[];for(let o of Vv(e))for(let s of Hv(o,i))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||r.push(s);for(let o of n)r.push(o);return uo(r)}function hd(e,t,n,i){let r=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();ji(i,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||r.push({location:bd(a,i),node:a}))}return r}function bd(e,t){let n=e.getSourceFile(),i=n.getLineAndColumnAtPos(e.getStart());return{file:ji(t,n.getFilePath())??n.getBaseName(),line:i.line-1,column:i.column-1}}function yd(e,t,n){let i=e.getSourceFile(),r=ni(i,e),o=e.getText(),s=new RegExp(`\\b${qv(o)}\\b`,"g"),a=i.getFullText().split(`
157
- `),c=[];for(let l=0;l<a.length;l++){if(l===r)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return uo(c.filter(l=>ji(n,fd.join(n,l.file))===t))}function na(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function ni(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function uo(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.line}:${i.column}`;t.has(r)||(t.add(r),n.push(i))}return n}function ji(e,t){let n=fd.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function qv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sd(e,t,n,i){let r=Uv(t,i);return r.size===0?new Map:Wv(e,n,r)}function Uv(e,t){let n=new Map;for(let i of G(e,t)){let r=F(i.symbol)??i.leaf;if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return n}function Wv(e,t,n){let i=new Map,r=new Map;return t.forEachDescendant(o=>{for(let s of Gv(e,o)){let a=n.get(s);if(!a)continue;let c=ni(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=r.get(l.symbolId);d!==void 0&&d<=u||(r.set(l.symbolId,u),i.set(l.symbolId,o))}}}),i}function Gv(e,t){let n=[],i=r=>{r&&!n.includes(r)&&n.push(r)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let r=t.getNameNode();i(r?.getText())}if("getName"in t&&typeof t.getName=="function"){let r=t.getName();i(r)}return e.Node.isIdentifier(t)&&i(t.getText()),n}var zv=U("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Cd(e,t,n,i){let r=Rd(e,t),o=xd(r.get(i)??[],n);if(o)return o;let s=[];for(let a of r.values())for(let c of a)((c.leaf||F(c.symbol)||"").includes(i)||c.symbol.includes(i))&&s.push(c);return xd(s,n)}function vd(e,t){let n=new Map;for(let[i,r]of Rd(e,t)){let o=r[0];o&&n.set(i,o)}return n}function Rd(e,t){return zv.get(e,t,()=>{let n=new Map;for(let i of G(e,t)){let r=i.leaf||F(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push({...i,leaf:r})}for(let i of n.values())i.sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine||r.symbolId-o.symbolId);return n})}function xd(e,t){let n=null,i=Number.POSITIVE_INFINITY;for(let r of e){let o=Math.abs(r.startLine-t);(o<i||o===i&&n&&r.startLine<n.startLine)&&(n=r,i=o)}return n}import Kv from"path";var Bi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function ii(e){let t=e.toLowerCase();return Bi.some(n=>t.endsWith(n))}function kd(e,t){let n=new Map,i=r=>ii(r)?Ye(n,r,()=>{let o=Kv.join(e.config.projectRoot,r);for(let{project:s}of t){let a=s.getSourceFile(o)??s.addSourceFileAtPathIfExists(o)??null;if(a)return{project:s,sourceFile:a}}return null}):null;return{sourceFile:r=>i(r)?.sourceFile??null,sourceFileMatch:i,indexedTypeScriptLikeDocuments:()=>j(e,{extensions:Bi})}}import jt from"path";import{existsSync as mo,readdirSync as Jv,readFileSync as wd}from"fs";function Ld(e){let t=jt.join(e,"package.json");if(!mo(t))return[];let n;try{n=JSON.parse(wd(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>Qv(e,r)).flatMap(r=>Xv(e,r))}function Qv(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=jt.join(e,t);return mo(jt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=jt.join(e,i||".");if(!mo(o))return[];try{return Jv(o).map(s=>jt.join(o,s,r)).filter(s=>mo(jt.join(s,"package.json")))}catch{return[]}}function Xv(e,t){try{let n=JSON.parse(wd(jt.join(t,"package.json"),"utf8"));if(!n.name)return[];let i=jt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:i,sourceRootRelative:`${i}/src`}]}catch{return[]}}function Dd(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Id(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as Hi,readFileSync as Yv,readdirSync as Zv,statSync as eR}from"fs";import re from"path";var ra=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function oa(e,t){let i=t?re.dirname(re.join(e,t)):e,r=re.resolve(e);for(;i.startsWith(r);){for(let s of ra){let a=re.join(i,s);if(Hi(a))return a}let o=re.dirname(i);if(o===i)break;i=o}for(let o of ra){let s=re.join(e,o);if(Hi(s))return s}return null}function Pd(e){let t=e.config.projectRoot,n=new Set(sa(t,e.config.semantic?.typescript?.tsconfigs)),i=j(e,{includeIgnored:!1,extensions:Bi});for(let r of i){let o=oa(t,r);o&&n.add(re.resolve(o))}if(n.size===0){let r=oa(t);r&&n.add(re.resolve(r))}return[...n].filter(r=>!Nd(t,r)).sort((r,o)=>r.localeCompare(o))}function sa(e,t=[]){let n=new Set;for(let i of t){let r=re.isAbsolute(i)?i:re.join(e,i);Hi(r)&&n.add(re.resolve(r))}for(let i of tR(e))for(let r of ra){let o=re.join(i,r);Hi(o)&&n.add(re.resolve(o))}if(n.size===0){let i=oa(e);i&&n.add(re.resolve(i))}return[...n].filter(i=>!Nd(e,i)).sort((i,r)=>i.localeCompare(r))}function tR(e){let t=re.join(e,"package.json");if(!Hi(t))return[];let n;try{n=JSON.parse(Yv(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>nR(e,r))}function nR(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=re.join(e,t);return ia(s)?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=re.join(e,i||".");return ia(o)?Zv(o).map(s=>re.join(o,s,r)).filter(ia):[]}function ia(e){try{return eR(e).isDirectory()}catch{return!1}}function Nd(e,t){let n=re.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}import{createRequire as iR}from"module";var rR=iR(import.meta.url),Vi;function Ed(){if(Vi!==void 0)return Vi;try{Vi=rR("ts-morph")}catch{Vi=null}return Vi}function Td(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function po(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function $d(e,t){let n=Ed();if(!n)return po("ts-morph is not installed");let i=Pd(e);if(i.length===0)return po("no tsconfig found");try{let r=Td(n,i);return new aa(e,n,r)}catch(r){return po(r instanceof Error?r.message:String(r),i[0],i)}}var aa=class{constructor(t,n,i){this.db=t;this.tsMorph=n;this.projects=i;this.workspacePackages=Ld(t.config.projectRoot),this.sourceFiles=kd(t,i)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Ye(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let i=[];for(let r of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,r))i.push(o);return i})}referencesFor(t){return Ye(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),i=this.packageImportReferencesForDefinition(t);return n?gd(n,t,i,this.db.config.projectRoot):i})}calleesFor(t){return Ye(this.calleesCache,t.symbolId,()=>Ye(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Ye(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let i=n.getType().getCallSignatures()[0];if(!i)return null;let r=i.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Fd(c)}),o=i.getReturnType().getText(n);return`(${r.join(",")})=>${Fd(o)}`})}importUsageForDeclaration(t,n){let i=Xe(this.db,t,n.getModuleSpecifierValue()),r=_d(n);return n.getImportClause()?.isTypeOnly()?r.map(o=>oR(t,i,o)):r.map(o=>this.valueImportUsageForEntry(t,i,o))}valueImportUsageForEntry(t,n,i){let r=i.identifier?i.identifier.findReferences():[],o=[];for(let l of r)for(let u of hd(l,t,i.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!na(l.node)),a=o.some(l=>na(l.node)),c=i.isTypeOnly;return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:c,isUsed:c||o.length>0,isTypeUsed:c||a,isValueUsed:s,references:o.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let i of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,i);for(let[i,r]of t)t.set(i,uo(r));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,i){if(this.db.isIgnored(i))return;let r=this.sourceFiles.sourceFileMatch(i);if(r)for(let o of r.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,i,o)}addPackageImportReferencesForDeclaration(t,n,i,r){let o=Dd(this.workspacePackages,r.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of _d(r)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=yd(a.identifier,i,this.db.config.projectRoot);l.length>0&&cR(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let i=new Map;for(let r of Id(n))this.collectPackageExports(n,r,i,new Set);i.size>0&&t.set(n.name,i)}return this.packageExportIndex=t,t}collectPackageExports(t,n,i,r){if(r.has(n))return;r.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?Xe(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,i,r);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let h=i.get(m);h||(h=new Set,i.set(m,h)),h.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Ye(this.indexedDefinitionLeafCache,t,()=>vd(this.db,t)).get(n)??null}nodeForDefinition(t){return Ye(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Ye(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Sd(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let i of n){let r=i.getSourceFile(),o=ji(this.db.config.projectRoot,r.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=ni(r,i),a=Cd(this.db,o,s,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFiles.sourceFile(t);if(!n)return new Map;let i=G(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(i.length===0)return new Map;let r=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,i,o);s&&sR(r,s.callerId,s.target)});for(let[o,s]of r)r.set(o,lR(s));return r}semanticCalleeForCallNode(t,n,i){let r=aR(n,ni(t,i));if(!r)return null;let o=i.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:r.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function _d(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let i=e.getNamespaceImport();i&&t.push({identifier:i,importedName:"*",localName:i.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let r of e.getNamedImports()){let o=r.getNameNode(),a=r.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:r.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function oR(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function sR(e,t,n){let i=e.get(t);i||(i=[],e.set(t,i)),i.push(n)}function aR(e,t){let n=null;for(let i of e)t<i.startLine||t>i.endLine||(!n||i.startLine>=n.startLine)&&(n=i);return n}function cR(e,t,n){for(let i of t){let r=e.get(i)??[];r.push(...n),e.set(i,r)}}function lR(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}|${i.line}`;t.has(r)||(t.add(r),n.push(i))}return n}function Fd(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var ca=new WeakMap;Et({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>ca.delete(e)});function ln(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,i=ca.get(e);i||(i=new Map,ca.set(e,i));let r=i.get(n);if(r)return r;let o=$d(e,t);return i.set(n,o),o}function qi(e,t){let n=go(e,t);return n?n.importUsage(t):[]}function un(e,t){let n=go(e,t.relativePath);return n?n.referencesFor(t):[]}function ri(e,t){let n=new Map;for(let i of t)for(let r of un(e,i)){if(r.file===i.relativePath||e.isIgnored(r.file))continue;let o=n.get(i.symbolId);o||(o=new Set,n.set(i.symbolId,o)),o.add(r.file)}return n}function fo(e,t){let n=new Map;for(let i of t){let r=go(e,i.relativePath);if(!r)continue;let o=r.calleesFor(i);o.length>0&&n.set(i.symbolId,o)}return n}function Ad(e,t){let n=go(e,t.relativePath);return n?n.signatureFor(t):null}function go(e,t){if(!ii(t))return null;let n=ln(e,t);return n.availability().available?n:null}function ho(e,t){let n=new Map;for(let i of fe(e,t)){if(!i.sourcePath)continue;let r=i.localName??i.importedName;if(r&&Md(n,r,i.sourcePath),i.kind==="namespace")for(let o of i.usedMembers)Md(n,o,i.sourcePath)}return n}function Md(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function oi(e,t,n){let i=cn(e).get(n);if(!i||i.length===0)return[];if(i.length===1)return[Ui(i[0])];let r=i.filter(c=>c.file===t);if(r.length>0)return r.map(Ui);let o=ho(e,t),s=o.get(n);if(s)for(let c of s){let l=i.filter(u=>Ot(c,u.file));if(l.length>0)return l.map(Ui)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=i.filter(u=>Ot(c,u.file));if(l.length>0&&l.length===i.length)return l.map(Ui)}return[]}function jd(e,t,n){let i=oi(e,t,n);if(i.length>0)return i;let r=cn(e).get(n);return!r||r.length===0?[]:r.map(Ui)}function Bd(e,t,n={}){let i=qr(e,t);if(!i)return[];let r=F(i.symbol);if(!r)return[];if(n.semantic!==!1){let s=un(e,{...i,leaf:r,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return Od(e,a)}}let o=new Map;for(let s of De(e)){let a=M(e,s);if(!a||a.indexOf(r)===-1||s!==i.relativePath&&!oi(e,s,r).some(u=>u.symbolId===i.symbolId))continue;let c=so(e,s,r,s===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{});c.length>0&&o.set(s,c)}return Od(e,o)}function Hd(e,t){let n=new Map;for(let o of t){if(!o.leaf)continue;let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}if(n.size===0)return new Map;let i=new Set(t.map(o=>o.symbolId)),r=new Map;for(let o of De(e)){let s=cd(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of oi(e,o,a)){if(!i.has(c.symbolId)||o===c.relativePath)continue;let l=r.get(c.symbolId);l||(l=new Set,r.set(c.symbolId,l)),l.add(o)}}}return r}function Ui(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Od(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=G(e,r);for(let a of o){let c=je(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function dn(e,t){let n=gR(e,t);return n?hR(e,dR(e,n.match,n.identifier)):[]}function Bt(e,t,n={}){return uR(e,t,n).map(i=>({file:i.file,line:i.line,enclosingSymbol:i.enclosingSymbol}))}function uR(e,t,n={}){let i=Bd(e,t,{semantic:n.semantic}),r=i.length>0?Vd(i,"source-attribution"):Vd(dn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?r:r.filter(o=>!e.isIgnored(o.file))}function Vd(e,t){return e.map(n=>({...n,provenance:t}))}function dR(e,t,n){let i=new Map;for(let[r,o]of mR(e,t.symbolId))i.set(r,pR(e,r,o,t,n));return i}function mR(e,t){let n=new Map;for(let i of ao(e,[t])){if(e.isIgnored(i.relative_path))continue;let r=n.get(i.relative_path);r||(r=[],n.set(i.relative_path,r)),r.push({start_line:i.chunk_start,end_line:i.chunk_end})}return n}function pR(e,t,n,i,r){let o=t===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{},s=r?so(e,t,r,o):[];return n.flatMap(a=>fR(s,a))}function fR(e,t){let n=e.filter(i=>i>=t.start_line&&i<=t.end_line);return n.length>0?n:[t.start_line]}function gR(e,t){let n=qr(e,t);return n?{match:n,identifier:F(n.symbol)||null}:null}function hR(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=G(e,r);for(let a of o){let c=je(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Ae(e,t,n={}){let i=bo(e,[t],{additive:n.additive,semantic:n.semantic}),r=n.callableOnly?(i.get(t.symbolId)??[]).filter(o=>xe(o.symbol)):i.get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}function Ud(e,t,n={}){let i=SR(e)?CR(e,t,{semantic:n.semantic!==!1}):xR(e).get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}var bR=Y("caller-rows",{clearGroups:["whole-project"]}),yR=2e4;function SR(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>yR}function xR(e){return bR.get(e,()=>{let t=ot(e),n=bo(e,t),i=new Map;for(let s of t)i.set(s.symbol,s.symbolId);let r=new Map,o=new Map;for(let s of t){let a=n.get(s.symbolId);if(!(!a||a.length===0))for(let c of a){let l=i.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=r.get(l);u||(u=[],r.set(l,u),o.set(l,new Set));let d=`${s.symbol}|${s.relativePath}`;o.get(l).has(d)||(o.get(l).add(d),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return r})}function CR(e,t,n){let i=[],r=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;r.has(c)||(r.add(c),i.push(a))};for(let a of dn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?vR(e,t):null;if(s)for(let a of un(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=je(G(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return i}function vR(e,t){return e.get(`SELECT
156
+ ${e.symbolNoiseFor("gs")}`),n=new Map;for(let i of t){if(!i.relative_path||e.isIgnored(i.relative_path))continue;let r=$(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.some(s=>s.symbolId===i.id)||o.push({symbol:i.symbol,symbolId:i.id,file:i.relative_path})}return n})}function Xe(e,t,n){if(e.has(t))return e.get(t);let i=n();return e.set(t,i),i}import bd from"path";function Kv(e,t){return e.getReferences().map(n=>{let i=n.getNode();return xd(i,t)})}function Jv(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function yd(e,t,n,i){let r=[];for(let o of Jv(e))for(let s of Kv(o,i))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||r.push(s);for(let o of n)r.push(o);return mo(r)}function Sd(e,t,n,i){let r=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();ji(i,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||r.push({location:xd(a,i),node:a}))}return r}function xd(e,t){let n=e.getSourceFile(),i=n.getLineAndColumnAtPos(e.getStart());return{file:ji(t,n.getFilePath())??n.getBaseName(),line:i.line-1,column:i.column-1}}function Cd(e,t,n){let i=e.getSourceFile(),r=ni(i,e),o=e.getText(),s=new RegExp(`\\b${Qv(o)}\\b`,"g"),a=i.getFullText().split(`
157
+ `),c=[];for(let l=0;l<a.length;l++){if(l===r)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return mo(c.filter(l=>ji(n,bd.join(n,l.file))===t))}function oa(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function ni(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function mo(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.line}:${i.column}`;t.has(r)||(t.add(r),n.push(i))}return n}function ji(e,t){let n=bd.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Qv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vd(e,t,n,i){let r=Xv(t,i);return r.size===0?new Map:Yv(e,n,r)}function Xv(e,t){let n=new Map;for(let i of G(e,t)){let r=$(i.symbol)??i.leaf;if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return n}function Yv(e,t,n){let i=new Map,r=new Map;return t.forEachDescendant(o=>{for(let s of Zv(e,o)){let a=n.get(s);if(!a)continue;let c=ni(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=r.get(l.symbolId);d!==void 0&&d<=u||(r.set(l.symbolId,u),i.set(l.symbolId,o))}}}),i}function Zv(e,t){let n=[],i=r=>{r&&!n.includes(r)&&n.push(r)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let r=t.getNameNode();i(r?.getText())}if("getName"in t&&typeof t.getName=="function"){let r=t.getName();i(r)}return e.Node.isIdentifier(t)&&i(t.getText()),n}var eR=U("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function kd(e,t,n,i){let r=Ld(e,t),o=Rd(r.get(i)??[],n);if(o)return o;let s=[];for(let a of r.values())for(let c of a)((c.leaf||$(c.symbol)||"").includes(i)||c.symbol.includes(i))&&s.push(c);return Rd(s,n)}function wd(e,t){let n=new Map;for(let[i,r]of Ld(e,t)){let o=r[0];o&&n.set(i,o)}return n}function Ld(e,t){return eR.get(e,t,()=>{let n=new Map;for(let i of G(e,t)){let r=i.leaf||$(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push({...i,leaf:r})}for(let i of n.values())i.sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine||r.symbolId-o.symbolId);return n})}function Rd(e,t){let n=null,i=Number.POSITIVE_INFINITY;for(let r of e){let o=Math.abs(r.startLine-t);(o<i||o===i&&n&&r.startLine<n.startLine)&&(n=r,i=o)}return n}import tR from"path";var Bi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function ii(e){let t=e.toLowerCase();return Bi.some(n=>t.endsWith(n))}function Dd(e,t){let n=new Map,i=r=>ii(r)?Xe(n,r,()=>{let o=tR.join(e.config.projectRoot,r);for(let{project:s}of t){let a=s.getSourceFile(o)??s.addSourceFileAtPathIfExists(o)??null;if(a)return{project:s,sourceFile:a}}return null}):null;return{sourceFile:r=>i(r)?.sourceFile??null,sourceFileMatch:i,indexedTypeScriptLikeDocuments:()=>j(e,{extensions:Bi})}}import jt from"path";import{existsSync as po,readdirSync as nR,readFileSync as Id}from"fs";function Pd(e){let t=jt.join(e,"package.json");if(!po(t))return[];let n;try{n=JSON.parse(Id(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>iR(e,r)).flatMap(r=>rR(e,r))}function iR(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=jt.join(e,t);return po(jt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=jt.join(e,i||".");if(!po(o))return[];try{return nR(o).map(s=>jt.join(o,s,r)).filter(s=>po(jt.join(s,"package.json")))}catch{return[]}}function rR(e,t){try{let n=JSON.parse(Id(jt.join(t,"package.json"),"utf8"));if(!n.name)return[];let i=jt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:i,sourceRootRelative:`${i}/src`}]}catch{return[]}}function Nd(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Ed(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as Hi,readFileSync as oR,readdirSync as sR,statSync as aR}from"fs";import re from"path";var aa=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function ca(e,t){let i=t?re.dirname(re.join(e,t)):e,r=re.resolve(e);for(;i.startsWith(r);){for(let s of aa){let a=re.join(i,s);if(Hi(a))return a}let o=re.dirname(i);if(o===i)break;i=o}for(let o of aa){let s=re.join(e,o);if(Hi(s))return s}return null}function Td(e){let t=e.config.projectRoot,n=new Set(la(t,e.config.semantic?.typescript?.tsconfigs)),i=j(e,{includeIgnored:!1,extensions:Bi});for(let r of i){let o=ca(t,r);o&&n.add(re.resolve(o))}if(n.size===0){let r=ca(t);r&&n.add(re.resolve(r))}return[...n].filter(r=>!_d(t,r)).sort((r,o)=>r.localeCompare(o))}function la(e,t=[]){let n=new Set;for(let i of t){let r=re.isAbsolute(i)?i:re.join(e,i);Hi(r)&&n.add(re.resolve(r))}for(let i of cR(e))for(let r of aa){let o=re.join(i,r);Hi(o)&&n.add(re.resolve(o))}if(n.size===0){let i=ca(e);i&&n.add(re.resolve(i))}return[...n].filter(i=>!_d(e,i)).sort((i,r)=>i.localeCompare(r))}function cR(e){let t=re.join(e,"package.json");if(!Hi(t))return[];let n;try{n=JSON.parse(oR(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>lR(e,r))}function lR(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=re.join(e,t);return sa(s)?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=re.join(e,i||".");return sa(o)?sR(o).map(s=>re.join(o,s,r)).filter(sa):[]}function sa(e){try{return aR(e).isDirectory()}catch{return!1}}function _d(e,t){let n=re.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}import{createRequire as uR}from"module";var dR=uR(import.meta.url),Vi;function $d(){if(Vi!==void 0)return Vi;try{Vi=dR("ts-morph")}catch{Vi=null}return Vi}function Fd(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function fo(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Od(e,t){let n=$d();if(!n)return fo("ts-morph is not installed");let i=Td(e);if(i.length===0)return fo("no tsconfig found");try{let r=Fd(n,i);return new ua(e,n,r)}catch(r){return fo(r instanceof Error?r.message:String(r),i[0],i)}}var ua=class{constructor(t,n,i){this.db=t;this.tsMorph=n;this.projects=i;this.workspacePackages=Pd(t.config.projectRoot),this.sourceFiles=Dd(t,i)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Xe(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let i=[];for(let r of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,r))i.push(o);return i})}referencesFor(t){return Xe(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),i=this.packageImportReferencesForDefinition(t);return n?yd(n,t,i,this.db.config.projectRoot):i})}calleesFor(t){return Xe(this.calleesCache,t.symbolId,()=>Xe(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Xe(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let i=n.getType().getCallSignatures()[0];if(!i)return null;let r=i.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Md(c)}),o=i.getReturnType().getText(n);return`(${r.join(",")})=>${Md(o)}`})}importUsageForDeclaration(t,n){let i=Qe(this.db,t,n.getModuleSpecifierValue()),r=Ad(n);return n.getImportClause()?.isTypeOnly()?r.map(o=>mR(t,i,o)):r.map(o=>this.valueImportUsageForEntry(t,i,o))}valueImportUsageForEntry(t,n,i){let r=i.identifier?i.identifier.findReferences():[],o=[];for(let l of r)for(let u of Sd(l,t,i.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!oa(l.node)),a=o.some(l=>oa(l.node)),c=i.isTypeOnly;return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:c,isUsed:c||o.length>0,isTypeUsed:c||a,isValueUsed:s,references:o.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let i of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,i);for(let[i,r]of t)t.set(i,mo(r));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,i){if(this.db.isIgnored(i))return;let r=this.sourceFiles.sourceFileMatch(i);if(r)for(let o of r.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,i,o)}addPackageImportReferencesForDeclaration(t,n,i,r){let o=Nd(this.workspacePackages,r.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Ad(r)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Cd(a.identifier,i,this.db.config.projectRoot);l.length>0&&gR(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let i=new Map;for(let r of Ed(n))this.collectPackageExports(n,r,i,new Set);i.size>0&&t.set(n.name,i)}return this.packageExportIndex=t,t}collectPackageExports(t,n,i,r){if(r.has(n))return;r.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?Qe(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,i,r);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let h=i.get(m);h||(h=new Set,i.set(m,h)),h.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Xe(this.indexedDefinitionLeafCache,t,()=>wd(this.db,t)).get(n)??null}nodeForDefinition(t){return Xe(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Xe(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?vd(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let i of n){let r=i.getSourceFile(),o=ji(this.db.config.projectRoot,r.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=ni(r,i),a=kd(this.db,o,s,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFiles.sourceFile(t);if(!n)return new Map;let i=G(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(i.length===0)return new Map;let r=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,i,o);s&&pR(r,s.callerId,s.target)});for(let[o,s]of r)r.set(o,hR(s));return r}semanticCalleeForCallNode(t,n,i){let r=fR(n,ni(t,i));if(!r)return null;let o=i.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:r.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function Ad(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let i=e.getNamespaceImport();i&&t.push({identifier:i,importedName:"*",localName:i.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let r of e.getNamedImports()){let o=r.getNameNode(),a=r.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:r.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function mR(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function pR(e,t,n){let i=e.get(t);i||(i=[],e.set(t,i)),i.push(n)}function fR(e,t){let n=null;for(let i of e)t<i.startLine||t>i.endLine||(!n||i.startLine>=n.startLine)&&(n=i);return n}function gR(e,t,n){for(let i of t){let r=e.get(i)??[];r.push(...n),e.set(i,r)}}function hR(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}|${i.line}`;t.has(r)||(t.add(r),n.push(i))}return n}function Md(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var da=new WeakMap;Et({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>da.delete(e)});function ln(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,i=da.get(e);i||(i=new Map,da.set(e,i));let r=i.get(n);if(r)return r;let o=Od(e,t);return i.set(n,o),o}function qi(e,t){let n=ho(e,t);return n?n.importUsage(t):[]}function un(e,t){let n=ho(e,t.relativePath);return n?n.referencesFor(t):[]}function ri(e,t){let n=new Map;for(let i of t)for(let r of un(e,i)){if(r.file===i.relativePath||e.isIgnored(r.file))continue;let o=n.get(i.symbolId);o||(o=new Set,n.set(i.symbolId,o)),o.add(r.file)}return n}function go(e,t){let n=new Map;for(let i of t){let r=ho(e,i.relativePath);if(!r)continue;let o=r.calleesFor(i);o.length>0&&n.set(i.symbolId,o)}return n}function jd(e,t){let n=ho(e,t.relativePath);return n?n.signatureFor(t):null}function ho(e,t){if(!ii(t))return null;let n=ln(e,t);return n.availability().available?n:null}function bo(e,t){let n=new Map;for(let i of fe(e,t)){if(!i.sourcePath)continue;let r=i.localName??i.importedName;if(r&&Bd(n,r,i.sourcePath),i.kind==="namespace")for(let o of i.usedMembers)Bd(n,o,i.sourcePath)}return n}function Bd(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function oi(e,t,n){let i=cn(e).get(n);if(!i||i.length===0)return[];if(i.length===1)return[Ui(i[0])];let r=i.filter(c=>c.file===t);if(r.length>0)return r.map(Ui);let o=bo(e,t),s=o.get(n);if(s)for(let c of s){let l=i.filter(u=>Ot(c,u.file));if(l.length>0)return l.map(Ui)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=i.filter(u=>Ot(c,u.file));if(l.length>0&&l.length===i.length)return l.map(Ui)}return[]}function Vd(e,t,n){let i=oi(e,t,n);if(i.length>0)return i;let r=cn(e).get(n);return!r||r.length===0?[]:r.map(Ui)}function qd(e,t,n={}){let i=Ur(e,t);if(!i)return[];let r=$(i.symbol);if(!r)return[];if(n.semantic!==!1){let s=un(e,{...i,leaf:r,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return Hd(e,a)}}let o=new Map;for(let s of De(e)){let a=M(e,s);if(!a||a.indexOf(r)===-1||s!==i.relativePath&&!oi(e,s,r).some(u=>u.symbolId===i.symbolId))continue;let c=ao(e,s,r,s===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{});c.length>0&&o.set(s,c)}return Hd(e,o)}function Ud(e,t){let n=new Map;for(let o of t){if(!o.leaf)continue;let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}if(n.size===0)return new Map;let i=new Set(t.map(o=>o.symbolId)),r=new Map;for(let o of De(e)){let s=dd(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of oi(e,o,a)){if(!i.has(c.symbolId)||o===c.relativePath)continue;let l=r.get(c.symbolId);l||(l=new Set,r.set(c.symbolId,l)),l.add(o)}}}return r}function Ui(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Hd(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=G(e,r);for(let a of o){let c=je(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function dn(e,t){let n=vR(e,t);return n?RR(e,yR(e,n.match,n.identifier)):[]}function Bt(e,t,n={}){return bR(e,t,n).map(i=>({file:i.file,line:i.line,enclosingSymbol:i.enclosingSymbol}))}function bR(e,t,n={}){let i=qd(e,t,{semantic:n.semantic}),r=i.length>0?Wd(i,"source-attribution"):Wd(dn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?r:r.filter(o=>!e.isIgnored(o.file))}function Wd(e,t){return e.map(n=>({...n,provenance:t}))}function yR(e,t,n){let i=new Map;for(let[r,o]of SR(e,t.symbolId))i.set(r,xR(e,r,o,t,n));return i}function SR(e,t){let n=new Map;for(let i of co(e,[t])){if(e.isIgnored(i.relative_path))continue;let r=n.get(i.relative_path);r||(r=[],n.set(i.relative_path,r)),r.push({start_line:i.chunk_start,end_line:i.chunk_end})}return n}function xR(e,t,n,i,r){let o=t===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{},s=r?ao(e,t,r,o):[];return n.flatMap(a=>CR(s,a))}function CR(e,t){let n=e.filter(i=>i>=t.start_line&&i<=t.end_line);return n.length>0?n:[t.start_line]}function vR(e,t){let n=Ur(e,t);return n?{match:n,identifier:$(n.symbol)||null}:null}function RR(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=G(e,r);for(let a of o){let c=je(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Ae(e,t,n={}){let i=yo(e,[t],{additive:n.additive,semantic:n.semantic}),r=n.callableOnly?(i.get(t.symbolId)??[]).filter(o=>xe(o.symbol)):i.get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}function zd(e,t,n={}){let i=LR(e)?IR(e,t,{semantic:n.semantic!==!1}):DR(e).get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}var kR=Y("caller-rows",{clearGroups:["whole-project"]}),wR=2e4;function LR(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>wR}function DR(e){return kR.get(e,()=>{let t=rt(e),n=yo(e,t),i=new Map;for(let s of t)i.set(s.symbol,s.symbolId);let r=new Map,o=new Map;for(let s of t){let a=n.get(s.symbolId);if(!(!a||a.length===0))for(let c of a){let l=i.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=r.get(l);u||(u=[],r.set(l,u),o.set(l,new Set));let d=`${s.symbol}|${s.relativePath}`;o.get(l).has(d)||(o.get(l).add(d),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return r})}function IR(e,t,n){let i=[],r=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;r.has(c)||(r.add(c),i.push(a))};for(let a of dn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?PR(e,t):null;if(s)for(let a of un(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=je(G(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return i}function PR(e,t){return e.get(`SELECT
158
158
  d.id AS documentId,
159
159
  gs.id AS symbolId,
160
160
  gs.symbol,
@@ -173,11 +173,11 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
173
173
  LEFT JOIN chunks c ON c.document_id = der.document_id
174
174
  JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
175
175
  WHERE gs.id = ?
176
- LIMIT 1`,t.symbolId)??null}function bo(e,t,n={}){if(t.length===0)return new Map;let i=n.additive??!1,r=[],o=[];for(let u of t)W(u.relativePath)&&Mn(e,u.relativePath)!==null?r.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let p=s.get(d);p||(p=[],s.set(d,p));let h=a.get(d);h||(h=new Set,a.set(d,h));for(let g of m){let b=`${g.symbol}|${g.chunkId}`;h.has(b)||(h.add(b),p.push(g))}}};r.length>0&&c(DR(e,r)),n.semantic!==!1&&c(ER(RR(e,t)));let l=i?t:o;return l.length>0&&c(NR(e,l)),s}function RR(e,t){let n=new Map,i=[],r=[];for(let s of t){if(!ii(s.relativePath))continue;let a=M(e,s.relativePath);if(!a){r.push(s);continue}let c=Qt(e,s.relativePath,a),l=LR(e,s.relativePath),u=jl(e,s.relativePath,s.symbol,c,l);if(u!==null){let d=kR(u);if(d){d.length>0&&n.set(s.symbolId,d);continue}}i.push({def:s,contentHash:c,depsDigest:l})}if(i.length===0&&r.length===0)return n;let o=fo(e,[...r,...i.map(s=>s.def)]);for(let[s,a]of o)n.set(s,a);return ln(e).availability().available&&Bl(e,i.map(s=>({relativePath:s.def.relativePath,symbol:s.def.symbol,contentHash:s.contentHash,depsDigest:s.depsDigest,payload:JSON.stringify(o.get(s.def.symbolId)??[])}))),n}function kR(e){try{return JSON.parse(e)}catch{return null}}var wR=U("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function LR(e,t){return wR.get(e,t,()=>{let i=[...ne(e).get(t)??[]].sort().map(r=>`${r}:${Qt(e,r,M(e,r))}`);return _s(i.join("|"))})}function DR(e,t){let n=new Map,i=IR(t,n),r=cn(e);for(let[o,s]of i){let a=Mn(e,o);if(!a)continue;let c=Bs(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=PR(e,o,r,l.calleeLeaf,l.memberAccess);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite"})}}return n}function IR(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function PR(e,t,n,i,r){let o=co(t,n.get(i)??[]);return o.length===0?null:lo(e,t,o,r)}function NR(e,t){if(t.length===0)return new Map;let i=la(t.map(m=>m.documentId)).flatMap(m=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
176
+ LIMIT 1`,t.symbolId)??null}function yo(e,t,n={}){if(t.length===0)return new Map;let i=n.additive??!1,r=[],o=[];for(let u of t)W(u.relativePath)&&Mn(e,u.relativePath)!==null?r.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let p=s.get(d);p||(p=[],s.set(d,p));let h=a.get(d);h||(h=new Set,a.set(d,h));for(let g of m){let b=`${g.symbol}|${g.chunkId}`;h.has(b)||(h.add(b),p.push(g))}}};r.length>0&&c($R(e,r)),n.semantic!==!1&&c(OR(NR(e,t)));let l=i?t:o;return l.length>0&&c(MR(e,l)),s}function NR(e,t){let n=new Map,i=[],r=[];for(let s of t){if(!ii(s.relativePath))continue;let a=M(e,s.relativePath);if(!a){r.push(s);continue}let c=Qt(e,s.relativePath,a),l=_R(e,s.relativePath),u=Vl(e,s.relativePath,s.symbol,c,l);if(u!==null){let d=ER(u);if(d){d.length>0&&n.set(s.symbolId,d);continue}}i.push({def:s,contentHash:c,depsDigest:l})}if(i.length===0&&r.length===0)return n;let o=go(e,[...r,...i.map(s=>s.def)]);for(let[s,a]of o)n.set(s,a);return ln(e).availability().available&&ql(e,i.map(s=>({relativePath:s.def.relativePath,symbol:s.def.symbol,contentHash:s.contentHash,depsDigest:s.depsDigest,payload:JSON.stringify(o.get(s.def.symbolId)??[])}))),n}function ER(e){try{return JSON.parse(e)}catch{return null}}var TR=U("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function _R(e,t){return TR.get(e,t,()=>{let i=[...ne(e).get(t)??[]].sort().map(r=>`${r}:${Qt(e,r,M(e,r))}`);return As(i.join("|"))})}function $R(e,t){let n=new Map,i=FR(t,n),r=cn(e);for(let[o,s]of i){let a=Mn(e,o);if(!a)continue;let c=qs(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=AR(e,o,r,l.calleeLeaf,l.memberAccess);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite"})}}return n}function FR(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function AR(e,t,n,i,r){let o=lo(t,n.get(i)??[]);return o.length===0?null:uo(e,t,o,r)}function MR(e,t){if(t.length===0)return new Map;let i=ma(t.map(m=>m.documentId)).flatMap(m=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
177
177
  FROM mentions m
178
178
  JOIN chunks c ON m.chunk_id = c.id
179
179
  WHERE m.role != 1
180
- AND c.document_id IN (${m.map(()=>"?").join(",")})`,...m)),r=new Map;for(let m of i)r.has(m.document_id)||r.set(m.document_id,[]),r.get(m.document_id).push(m);let s=la(i.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
180
+ AND c.document_id IN (${m.map(()=>"?").join(",")})`,...m)),r=new Map;for(let m of i)r.has(m.document_id)||r.set(m.document_id,[]),r.get(m.document_id).push(m);let s=ma(i.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
181
181
  COALESCE(der.document_id, def_chunk.document_id) AS document_id
182
182
  FROM global_symbols gs
183
183
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -189,11 +189,11 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
189
189
  AND m.symbol_id IN (${m.map(()=>"?").join(",")})
190
190
  GROUP BY m.symbol_id
191
191
  ) def_chunk ON def_chunk.symbol_id = gs.id
192
- WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=la([...t.map(m=>m.documentId),...s.flatMap(m=>m.document_id===null?[]:[m.document_id])]),c=new Map(a.flatMap(m=>e.all(`SELECT id, relative_path FROM documents
193
- WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(p=>[p.id,p.relative_path]))),l=new Map;for(let m of s)l.has(m.symbol_id)||l.set(m.symbol_id,{symbol:m.symbol,file:m.document_id!==null?c.get(m.document_id)??"":""});let u=new Map,d=c;for(let m of t){let p=r.get(m.documentId)??[],h=new Set,g=[],b=null,S=()=>{if(b)return b;let x=d.get(m.documentId)??"",I=new Set;if(x){let L=ld(e,x),C=Math.max(0,m.startLine),D=Math.min(L.length-1,m.endLine);for(let k=C;k<=D;k+=1)for(let A of L[k])I.add(A)}return b=I,I};for(let x of p){if(x.symbol_id===m.symbolId)continue;let I=l.get(x.symbol_id);if(!I)continue;if(!(x.start_line>=m.startLine&&x.end_line<=m.endLine)){if(!(x.start_line<=m.endLine&&x.end_line>=m.startLine))continue;let k=F(I.symbol);if(!k||!S().has(k))continue}let C=`${I.symbol}|${x.chunk_id}`;h.has(C)||(h.add(C),g.push({...I,chunkId:x.chunk_id,source:"scip-chunk"}))}u.set(m.symbolId,g)}return u}var qd=500;function la(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=qd)n.push(t.slice(i,i+qd));return n}function ER(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,r)}return t}function Wd(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=j(e,{includeIgnored:!1}),o=cn(e),s=t??ot(e),a=new Set(s.map(c=>c.symbolId));return TR(e,i,r,o,a),_R(e,i,s,a),MR(e,i,r,o,a),n.semantic!==!1&&jR(i,ri(e,OR(s))),i}function TR(e,t,n,i,r){for(let o of n){if(!W(o))continue;let s=Mn(e,o);if(s)for(let a of s){let c=co(o,i.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=lo(e,o,c,a.memberAccess);l&&r.has(l.symbolId)&&l.file!==o&&ua(t,l.symbolId,o)}}}function _R(e,t,n,i){let r=$R(n);for(let o of FR(e,i))e.isIgnored(o.relative_path)||AR(o,r.get(o.symbol_id))||ua(t,o.symbol_id,o.relative_path)}function FR(e,t){return ao(e,t?[...t]:void 0)}function $R(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function AR(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function MR(e,t,n,i,r){for(let o of n){if(W(o)!=="rust")continue;let s=Xt(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=i.get(a);if(c)for(let l of c)r.has(l.symbolId)&&l.file!==o&&ua(t,l.symbolId,o)}}}function ua(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function OR(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function jR(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function qe(e,t,n={}){return Ud(e,t,n)}function da(e,t,n={}){return Wd(e,t,n)}function ma(e,t){return Hd(e,t)}function Gd(e,t,n={}){let i=da(e,t,{semantic:n.semantic});return n.sourceFallback===!1?i:BR(i,ma(e,t))}function BR(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function zd(e,t,n){let i=t.identifierResolution==="strict"?oi:jd;for(let r of t.paths)if(!(!W(r)&&!(t.includeVueSfc&&yt(r)))&&!e.isIgnored(r)&&!t.skipPath?.(r))try{let s=(c,l,u,d)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let m=t.resolveTargets?t.resolveTargets({sourceFile:r,name:c,kind:l,defaultTargets:d}):d();for(let p of m)n({sourceFile:r,name:c,target:p,occurrences:u,kind:l})},a=vt(e,r);for(let[c,l]of a)s(c,"identifier",l.length,()=>i(e,r,c));for(let c of Xt(e,r,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>oi(e,r,c.name):()=>i(e,r,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(r)}}function q(e){return e.endLine-e.startLine+1}function Kd(e,t={}){let{scope:n,minLoc:i=1,maxLoc:r=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:d=!1,includeSuppressed:m=!1,sortByLocDesc:p=!1}=t,h=[];for(let g of Ei(e,n)){let b=g.relativePath;if(e.isIgnored(b)||s&&we(e,b)||!HR(g,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&g.symbol===o)continue;let S=q(g);S<i||S>r||a&&VR(b)||c&&ie(e,g.symbol,b)||d&&jr(g.symbol)||K(b)!=="test"&&(Vn(g.symbol)||!m&&Ir(e,b,g.startLine)||h.push(g))}return p?h.sort((g,b)=>q(b)-q(g)):h}function HR(e,t){return t.requireCallableSymbol?xe(e.symbol):t.requireFunctionLikeSymbol?se(e.symbol):e.isFunctionLike}function VR(e){return(e.split("/").pop()??"").includes("types")}var T=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Ei(this.db,t)}definitionsForFile(t){return G(this.db,t)}productionCallableDefinitions(t={}){return Kd(this.db,t)}calleeMap(t,n={}){return bo(this.db,t,n)}crossFileCallerMap(t,n={}){return da(this.db,t,n)}sourceFallbackCallerFiles(t){return ma(this.db,t)}callerFileMap(t,n={}){return Gd(this.db,t,n)}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of j(this.db,{includeIgnored:!1}))if(W(r)==="rust")for(let{name:o}of Xt(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(o=>[o.symbolId,o.symbol])),r=this.calleeMap(t,n);return new Set([...r.entries()].filter(([o,s])=>{let a=i.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ne(this.db,t)}fileKind(t){return K(t)}hasSuppressionComment(t){return Ir(this.db,t.relativePath,t.startLine)}sourceFiles(){return De(this.db)}scanSourceReferences(t,n){zd(this.db,t,n)}callableSignature(t){let n=oe(this.db,t.relativePath)?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function pa(e,t){let n=B(e,t);if(!n)return[];let i=F(n.symbol),o=new T(e).definitionsForFile(n.relativePath).filter(c=>xe(c.symbol)),s=o.filter(c=>c.parentTypeName===i||c.symbol.includes(i));return(s.length>0?s:UR(qR(n.relativePath))===i?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:F(c.symbol)}))}function UR(e){return e.replace(/\.[^.]+$/,"")}function fa(e,t,n={}){let i=B(e,t);if(!i)return[];let o=!se(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=Bt(e,i,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=WR(e,i),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function WR(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=GR(t.symbol);if(n.length===0)return[];let i=[];for(let r of j(e,{extensions:[".rb"],includeIgnored:!1})){let o=M(e,r);if(!o)continue;let s=o.split(`
194
- `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&i.push({relativePath:r,line:a})}}return i}function GR(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}function Wi(e,t,n={}){let i=B(e,t);if(!i)return{definitions:[],referencedBy:[]};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=Zt(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:KR(o,r?.display_name??null,i.symbol),source:zR(e,i.relativePath,i.startLine,i.endLine)}],a=Bt(e,i,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function zR(e,t,n,i){let r=M(e,t);if(!r)return null;let s=r.split(`
192
+ WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=ma([...t.map(m=>m.documentId),...s.flatMap(m=>m.document_id===null?[]:[m.document_id])]),c=new Map(a.flatMap(m=>e.all(`SELECT id, relative_path FROM documents
193
+ WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(p=>[p.id,p.relative_path]))),l=new Map;for(let m of s)l.has(m.symbol_id)||l.set(m.symbol_id,{symbol:m.symbol,file:m.document_id!==null?c.get(m.document_id)??"":""});let u=new Map,d=c;for(let m of t){let p=r.get(m.documentId)??[],h=new Set,g=[],b=null,S=()=>{if(b)return b;let x=d.get(m.documentId)??"",I=new Set;if(x){let L=md(e,x),C=Math.max(0,m.startLine),D=Math.min(L.length-1,m.endLine);for(let k=C;k<=D;k+=1)for(let A of L[k])I.add(A)}return b=I,I};for(let x of p){if(x.symbol_id===m.symbolId)continue;let I=l.get(x.symbol_id);if(!I)continue;if(!(x.start_line>=m.startLine&&x.end_line<=m.endLine)){if(!(x.start_line<=m.endLine&&x.end_line>=m.startLine))continue;let k=$(I.symbol);if(!k||!S().has(k))continue}let C=`${I.symbol}|${x.chunk_id}`;h.has(C)||(h.add(C),g.push({...I,chunkId:x.chunk_id,source:"scip-chunk"}))}u.set(m.symbolId,g)}return u}var Gd=500;function ma(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=Gd)n.push(t.slice(i,i+Gd));return n}function OR(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,r)}return t}function Kd(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=j(e,{includeIgnored:!1}),o=cn(e),s=t??rt(e),a=new Set(s.map(c=>c.symbolId));return jR(e,i,r,o,a),BR(e,i,s,a),UR(e,i,r,o,a),n.semantic!==!1&&GR(i,ri(e,WR(s))),i}function jR(e,t,n,i,r){for(let o of n){if(!W(o))continue;let s=Mn(e,o);if(s)for(let a of s){let c=lo(o,i.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=uo(e,o,c,a.memberAccess);l&&r.has(l.symbolId)&&l.file!==o&&pa(t,l.symbolId,o)}}}function BR(e,t,n,i){let r=VR(n);for(let o of HR(e,i))e.isIgnored(o.relative_path)||qR(o,r.get(o.symbol_id))||pa(t,o.symbol_id,o.relative_path)}function HR(e,t){return co(e,t?[...t]:void 0)}function VR(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function qR(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function UR(e,t,n,i,r){for(let o of n){if(W(o)!=="rust")continue;let s=Xt(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=i.get(a);if(c)for(let l of c)r.has(l.symbolId)&&l.file!==o&&pa(t,l.symbolId,o)}}}function pa(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function WR(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function GR(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function qe(e,t,n={}){return zd(e,t,n)}function fa(e,t,n={}){return Kd(e,t,n)}function ga(e,t){return Ud(e,t)}function Jd(e,t,n={}){let i=fa(e,t,{semantic:n.semantic});return n.sourceFallback===!1?i:zR(i,ga(e,t))}function zR(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function Qd(e,t,n){let i=t.identifierResolution==="strict"?oi:Vd;for(let r of t.paths)if(!(!W(r)&&!(t.includeVueSfc&&yt(r)))&&!e.isIgnored(r)&&!t.skipPath?.(r))try{let s=(c,l,u,d)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let m=t.resolveTargets?t.resolveTargets({sourceFile:r,name:c,kind:l,defaultTargets:d}):d();for(let p of m)n({sourceFile:r,name:c,target:p,occurrences:u,kind:l})},a=vt(e,r);for(let[c,l]of a)s(c,"identifier",l.length,()=>i(e,r,c));for(let c of Xt(e,r,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>oi(e,r,c.name):()=>i(e,r,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(r)}}function q(e){return e.endLine-e.startLine+1}function Xd(e,t={}){let{scope:n,minLoc:i=1,maxLoc:r=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:d=!1,includeSuppressed:m=!1,sortByLocDesc:p=!1}=t,h=[];for(let g of Ei(e,n)){let b=g.relativePath;if(e.isIgnored(b)||s&&we(e,b)||!KR(g,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&g.symbol===o)continue;let S=q(g);S<i||S>r||a&&JR(b)||c&&ie(e,g.symbol,b)||d&&Br(g.symbol)||K(b)!=="test"&&(Vn(g.symbol)||!m&&Pr(e,b,g.startLine)||h.push(g))}return p?h.sort((g,b)=>q(b)-q(g)):h}function KR(e,t){return t.requireCallableSymbol?xe(e.symbol):t.requireFunctionLikeSymbol?se(e.symbol):e.isFunctionLike}function JR(e){return(e.split("/").pop()??"").includes("types")}var T=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Ei(this.db,t)}definitionsForFile(t){return G(this.db,t)}productionCallableDefinitions(t={}){return Xd(this.db,t)}calleeMap(t,n={}){return yo(this.db,t,n)}crossFileCallerMap(t,n={}){return fa(this.db,t,n)}sourceFallbackCallerFiles(t){return ga(this.db,t)}callerFileMap(t,n={}){return Jd(this.db,t,n)}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of j(this.db,{includeIgnored:!1}))if(W(r)==="rust")for(let{name:o}of Xt(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(o=>[o.symbolId,o.symbol])),r=this.calleeMap(t,n);return new Set([...r.entries()].filter(([o,s])=>{let a=i.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ne(this.db,t)}fileKind(t){return K(t)}hasSuppressionComment(t){return Pr(this.db,t.relativePath,t.startLine)}sourceFiles(){return De(this.db)}scanSourceReferences(t,n){Qd(this.db,t,n)}callableSignature(t){let n=oe(this.db,t.relativePath)?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function ha(e,t){let n=B(e,t);if(!n)return[];let i=$(n.symbol),o=new T(e).definitionsForFile(n.relativePath).filter(c=>xe(c.symbol)),s=o.filter(c=>c.parentTypeName===i||c.symbol.includes(i));return(s.length>0?s:XR(QR(n.relativePath))===i?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:$(c.symbol)}))}function XR(e){return e.replace(/\.[^.]+$/,"")}function ba(e,t,n={}){let i=B(e,t);if(!i)return[];let o=!se(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=Bt(e,i,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=YR(e,i),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function YR(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=ZR(t.symbol);if(n.length===0)return[];let i=[];for(let r of j(e,{extensions:[".rb"],includeIgnored:!1})){let o=M(e,r);if(!o)continue;let s=o.split(`
194
+ `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&i.push({relativePath:r,line:a})}}return i}function ZR(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}function Wi(e,t,n={}){let i=B(e,t);if(!i)return{definitions:[],referencedBy:[]};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=Zt(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:tk(o,r?.display_name??null,i.symbol),source:ek(e,i.relativePath,i.startLine,i.endLine)}],a=Bt(e,i,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function ek(e,t,n,i){let r=M(e,t);if(!r)return null;let s=r.split(`
195
195
  `).slice(n,i+1).join(`
196
- `).trimEnd();return s.length>0?s:null}function KR(e,t,n){let i=Yt(e);if(i&&!JR(i))return i;let r=(t??"").trim();return r?se(n)&&!r.endsWith("()")?`${r}()`:r:y(n)}function JR(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Gi(e,t){let n=Ie(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
196
+ `).trimEnd();return s.length>0?s:null}function tk(e,t,n){let i=Yt(e);if(i&&!nk(i))return i;let r=(t??"").trim();return r?se(n)&&!r.endsWith("()")?`${r}()`:r:y(n)}function nk(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Gi(e,t){let n=Ie(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
197
197
  FROM mentions m
198
198
  JOIN chunks c ON m.chunk_id = c.id
199
199
  JOIN documents d1 ON c.document_id = d1.id
@@ -226,7 +226,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
226
226
  AND d1.relative_path != ?
227
227
  ORDER BY d1.relative_path`,n,n).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({relativePath:r.relative_path})):[]}function Ki(e,t){let n=Kn(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
228
228
  WHERE relative_path IN (${i})
229
- ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=Br(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
229
+ ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=Hr(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
230
230
  FROM mentions m
231
231
  JOIN chunks c ON m.chunk_id = c.id
232
232
  JOIN documents d1 ON c.document_id = d1.id
@@ -257,7 +257,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
257
257
  JOIN documents d2 ON sym_def.document_id = d2.id
258
258
  WHERE d2.relative_path IN (${i})
259
259
  AND d1.relative_path NOT IN (${i})
260
- ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function Ji(e,t){let n=Kn(e,t);return n.length===0?[]:YR([...QR(e,n),...XR(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(ZR)}function QR(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
260
+ ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function Ji(e,t){let n=Kn(e,t);return n.length===0?[]:ok([...ik(e,n),...rk(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(sk)}function ik(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
261
261
  FROM mentions m
262
262
  JOIN chunks c ON m.chunk_id = c.id
263
263
  JOIN documents d1 ON c.document_id = d1.id
@@ -284,7 +284,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
284
284
  AND m.role != 1
285
285
  AND ${e.localSymbolPredicate}
286
286
  ${e.pathExclusionsFor("d1")}
287
- ORDER BY d1.relative_path`,...t,...t,...t)}function XR(e,t){let n=new T(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>xe(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function YR(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function ZR(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:y(e.symbol)}}var Qi=new WeakMap;function Qd(e,t){let n=W(t);return n==="rust"?rk(e,t):n==="typescript"||n==="tsx"||n==="javascript"?tk(e,t):[]}var ek=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function tk(e,t){let n=me(e,t);if(!n)return[];let i=Qi.get(n);if(i)return i;let r=!1,o=n.rootNode;for(let a of o.namedChildren){if(a.type!=="expression_statement")continue;let c=a.namedChild(0);if(!c||c.type!=="call_expression")continue;let l=c.namedChild(0);if(!l)continue;let u=l.type==="member_expression"?l.namedChild(l.namedChildCount-1)?.text:l.text;if(u&&ek.has(u)){r=!0;break}}let s=[];r&&s.push({startLine:0,endLine:o.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"});for(let a of o.namedChildren){let c=null,l=null;if(a.type==="function_declaration")c=a.namedChild(0)?.text??null,l=a;else if(a.type==="export_statement"){let u=a.namedChild(0);u?.type==="function_declaration"&&(c=u.namedChild(0)?.text??null,l=u)}else if(a.type==="lexical_declaration"){let u=a.namedChild(0);if(u?.type==="variable_declarator"){let d=u.namedChild(0)?.text,m=u.namedChild(1);d&&(m?.type==="arrow_function"||m?.type==="function_expression")&&(c=d,l=u)}}c&&/^use[A-Z]/.test(c)&&l&&s.push({startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"React custom hook (use*)"})}return s.push(...Xd(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Qi.set(n,s),s}var nk=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function ik(e){return nk.test(e)}function Xd(e,t,n){let i=[],r=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(ik(u.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function rk(e,t){let n=me(e,t);if(!n)return[];let i=Qi.get(n);if(i)return i;let r=[],o=ok(n);return o?(Qi.set(n,o),o):(Yd(n.rootNode,r,!1,!1),r.push(...Xd(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),r.push(...pk(n.rootNode)),Qi.set(n,r),r)}function ok(e){return fk(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function Yd(e,t,n,i){let r=n,o=i;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?sk(e,t,n,i):i&&mk(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?ak(e,t,n):e.type==="mod_item"&&ga(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)Yd(s,t,r,o)}function sk(e,t,n,i){let r=ga(e),o=null;i?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of r){let a=lk(s);if(a){o=a;break}if(Zd(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function ak(e,t,n){let i=ga(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(dk)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:r}),i.some(Zd)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:r})}function ga(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var ck=[{re:/#\[\s*tauri::command\b/,reason:"#[tauri::command]"},{re:/#\[\s*command\b/,reason:"#[command]"},{re:/#\[\s*test\b/,reason:"#[test]"},{re:/#\[\s*bench\b/,reason:"#[bench]"},{re:/#\[\s*tokio::test\b/,reason:"#[tokio::test]"},{re:/#\[\s*async_std::test\b/,reason:"#[async_std::test]"},{re:/#\[\s*wasm_bindgen\b/,reason:"#[wasm_bindgen]"},{re:/#\[\s*no_mangle\b/,reason:"#[no_mangle]"},{re:/#\[\s*napi\b/,reason:"#[napi]"},{re:/#\[\s*pyfunction\b/,reason:"#[pyfunction]"},{re:/#\[\s*pymethod\b/,reason:"#[pymethod]"},{re:/#\[\s*pyo3\b/,reason:"#[pyo3]"},{re:/#\[\s*cfg\s*\(\s*test\s*\)/,reason:"#[cfg(test)]"},{re:/#\[\s*doc\s*\(\s*hidden\s*\)/,reason:"#[doc(hidden)]"}];function lk(e){return ck.find(({re:t})=>t.test(e))?.reason??null}var uk=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function dk(e){return/#\[\s*derive\s*\(/.test(e)?uk.some(t=>t.test(e)):!1}function Zd(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function mk(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function pk(e){let t=hk(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:r})}return n}function fk(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var gk=/^#!?\[\s*serde\s*\(/,Jd=/\bwith\s*=\s*"([^"]+)"/g;function hk(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!gk.test(n.text))continue;Jd.lastIndex=0;let i;for(;(i=Jd.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function em(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=Qd(e,i);return r={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i);for(let c of a.ranges)if(r>=c.startLine&&r<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of Vr(o))if(a.containers.has(c))return!0;return!1}}function ha(e,t={}){Ps(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function ba(e,t,n={}){Ps(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function nm(e,t){return t.isIgnoredPath(e.relativePath)?at("ignored-file"):Tt(e.symbol)?at("module-like-symbol"):tm(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&tm(e.enclosingSymbol)?at("nested-non-callable-value"):!t.includeTests&&!ya(e.relativePath)?at("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?at("excluded-file-region"):jr(e.symbol)?at("rust-trait-impl-member"):Vn(e.symbol)?at("rust-test-module"):!t.includeMembers&&!bk(e)?at("member"):e.endLine-e.startLine+1<t.minLoc?at("below-min-loc"):{accepted:!0}:at("non-value-symbol")}function ya(e){return K(e)!=="test"}function at(e){return{accepted:!1,rejectionReason:e}}function tm(e){return se(e)||e.endsWith("().")||e.endsWith(".")}function bk(e){return xe(e.symbol)||Vr(e.symbol).length===0}function yo(e,t){return q(e)-q(t)||e.relativePath.localeCompare(t.relativePath)}function Ue(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function si(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function im(){return new Map}function rm(e,t,n){let i=new Map;for(let r of ud(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||So(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function om(e,t,n){let i=new Set;for(let r of dd(e,t))e.isIgnored(r.relative_path)||n.has(r.relative_path)||i.add(r.symbol_id);return i}function Sa(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function sm(e){return e?.occurrences??0}function So(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=cm(e,t,n);o.occurrences+=i,o.sources.add(r)}function am(e,t,n,i,r){if(i<=0)return;let o=cm(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function cm(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}function Rt(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=Ue(yk(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),c),d=o?new Set(sd(e)):new Set,m=a?im():rm(e,d,u.map(S=>S.symbolId)),p=a?om(e,u.map(S=>S.symbolId),d):new Set,h=a?u.filter(S=>!p.has(S.symbolId)):u;a?Rk(e,h,m,d):vk(e,h,m,d);let g=a?h.filter(S=>!Sa(m,S.symbolId)):u;Ik(e,g,m,{includeTests:r,inactiveBarrelPaths:d,includeSemantic:!a&&l});let b=a?h.filter(S=>!Sa(m,S.symbolId)):u;return Ck(e,Sk(b,m))}function yk(e,t){let n=em(e),i=[];for(let r of j(e,{scope:t.scope}))try{for(let o of G(e,r))nm(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&i.push(o)}finally{ba(e,r,{definitions:!0})}return i}function Sk(e,t){return e.map(n=>xk(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function xk(e,t){let n=t.get(e.symbolId)??new Map,i=sm(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:i,cross_file_refs:r}}function Ck(e,t){let n=[],i=0,r=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||we(e,s.relative_path)||ie(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?i++:r++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:y(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,counts:{total:n.length,deadCode:i,fileInternal:r,loc:o},totalCount:n.length,deadCodeCount:i,fileInternalCount:r,totalLoc:o}}function vk(e,t,n,i){if(t.length===0)return;let r=new T(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let c of j(e))a.add(c);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>i.has(c)},c=>{o.has(c.target.symbolId)&&(Lk(e,c)||So(n,c.target.symbolId,c.sourceFile,Dk(c),"source-fallback"))})}function Rk(e,t,n,i){if(t.length===0)return;let r=new T(e),o=kk(t),s=new Set(r.sourceFiles());for(let u of j(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=ho(e,u),c.set(u,d)),d};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>i.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?wk(u,d,p,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),ba(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&lm(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||So(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function kk(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let i=t.get(n.leaf)??[];i.push(n),t.set(n.leaf,i)}return t}function wk(e,t,n,i,r){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i.get(t);if(s)for(let c of s){let l=n.filter(u=>Ot(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of i.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>Ot(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return r.permissive?[...n]:[]}function Lk(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&lm(e,t)}function Dk(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function lm(e,t){return t.occurrences>1?!1:fe(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Ik(e,t,n,i){for(let r of t){let o=qe(e,r,{semantic:i.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===r.relativePath||e.isIgnored(a)||i.inactiveBarrelPaths.has(a)||!i.includeTests&&!ya(a)||am(n,r.symbolId,a,1,"caller-map")}}}function xa(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"",s=e.all(`SELECT
287
+ ORDER BY d1.relative_path`,...t,...t,...t)}function rk(e,t){let n=new T(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>xe(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function ok(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function sk(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:y(e.symbol)}}var Qi=new WeakMap;function Zd(e,t){let n=W(t);return n==="rust"?dk(e,t):n==="typescript"||n==="tsx"||n==="javascript"?ck(e,t):[]}var ak=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function ck(e,t){let n=me(e,t);if(!n)return[];let i=Qi.get(n);if(i)return i;let r=!1,o=n.rootNode;for(let a of o.namedChildren){if(a.type!=="expression_statement")continue;let c=a.namedChild(0);if(!c||c.type!=="call_expression")continue;let l=c.namedChild(0);if(!l)continue;let u=l.type==="member_expression"?l.namedChild(l.namedChildCount-1)?.text:l.text;if(u&&ak.has(u)){r=!0;break}}let s=[];r&&s.push({startLine:0,endLine:o.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"});for(let a of o.namedChildren){let c=null,l=null;if(a.type==="function_declaration")c=a.namedChild(0)?.text??null,l=a;else if(a.type==="export_statement"){let u=a.namedChild(0);u?.type==="function_declaration"&&(c=u.namedChild(0)?.text??null,l=u)}else if(a.type==="lexical_declaration"){let u=a.namedChild(0);if(u?.type==="variable_declarator"){let d=u.namedChild(0)?.text,m=u.namedChild(1);d&&(m?.type==="arrow_function"||m?.type==="function_expression")&&(c=d,l=u)}}c&&/^use[A-Z]/.test(c)&&l&&s.push({startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"React custom hook (use*)"})}return s.push(...em(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Qi.set(n,s),s}var lk=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function uk(e){return lk.test(e)}function em(e,t,n){let i=[],r=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(uk(u.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function dk(e,t){let n=me(e,t);if(!n)return[];let i=Qi.get(n);if(i)return i;let r=[],o=mk(n);return o?(Qi.set(n,o),o):(tm(n.rootNode,r,!1,!1),r.push(...em(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),r.push(...xk(n.rootNode)),Qi.set(n,r),r)}function mk(e){return Ck(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function tm(e,t,n,i){let r=n,o=i;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?pk(e,t,n,i):i&&Sk(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?fk(e,t,n):e.type==="mod_item"&&ya(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)tm(s,t,r,o)}function pk(e,t,n,i){let r=ya(e),o=null;i?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of r){let a=hk(s);if(a){o=a;break}if(nm(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function fk(e,t,n){let i=ya(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(yk)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:r}),i.some(nm)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:r})}function ya(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var gk=[{re:/#\[\s*tauri::command\b/,reason:"#[tauri::command]"},{re:/#\[\s*command\b/,reason:"#[command]"},{re:/#\[\s*test\b/,reason:"#[test]"},{re:/#\[\s*bench\b/,reason:"#[bench]"},{re:/#\[\s*tokio::test\b/,reason:"#[tokio::test]"},{re:/#\[\s*async_std::test\b/,reason:"#[async_std::test]"},{re:/#\[\s*wasm_bindgen\b/,reason:"#[wasm_bindgen]"},{re:/#\[\s*no_mangle\b/,reason:"#[no_mangle]"},{re:/#\[\s*napi\b/,reason:"#[napi]"},{re:/#\[\s*pyfunction\b/,reason:"#[pyfunction]"},{re:/#\[\s*pymethod\b/,reason:"#[pymethod]"},{re:/#\[\s*pyo3\b/,reason:"#[pyo3]"},{re:/#\[\s*cfg\s*\(\s*test\s*\)/,reason:"#[cfg(test)]"},{re:/#\[\s*doc\s*\(\s*hidden\s*\)/,reason:"#[doc(hidden)]"}];function hk(e){return gk.find(({re:t})=>t.test(e))?.reason??null}var bk=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function yk(e){return/#\[\s*derive\s*\(/.test(e)?bk.some(t=>t.test(e)):!1}function nm(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Sk(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function xk(e){let t=Rk(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:r})}return n}function Ck(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var vk=/^#!?\[\s*serde\s*\(/,Yd=/\bwith\s*=\s*"([^"]+)"/g;function Rk(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!vk.test(n.text))continue;Yd.lastIndex=0;let i;for(;(i=Yd.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function im(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=Zd(e,i);return r={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i);for(let c of a.ranges)if(r>=c.startLine&&r<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of qr(o))if(a.containers.has(c))return!0;return!1}}function Sa(e,t={}){Ts(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function xa(e,t,n={}){Ts(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function om(e,t){return t.isIgnoredPath(e.relativePath)?st("ignored-file"):Tt(e.symbol)?st("module-like-symbol"):rm(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&rm(e.enclosingSymbol)?st("nested-non-callable-value"):!t.includeTests&&!Ca(e.relativePath)?st("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?st("excluded-file-region"):Br(e.symbol)?st("rust-trait-impl-member"):Vn(e.symbol)?st("rust-test-module"):!t.includeMembers&&!kk(e)?st("member"):e.endLine-e.startLine+1<t.minLoc?st("below-min-loc"):{accepted:!0}:st("non-value-symbol")}function Ca(e){return K(e)!=="test"}function st(e){return{accepted:!1,rejectionReason:e}}function rm(e){return se(e)||e.endsWith("().")||e.endsWith(".")}function kk(e){return xe(e.symbol)||qr(e.symbol).length===0}function So(e,t){return q(e)-q(t)||e.relativePath.localeCompare(t.relativePath)}function Ue(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function si(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function sm(){return new Map}function am(e,t,n){let i=new Map;for(let r of pd(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||xo(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function cm(e,t,n){let i=new Set;for(let r of fd(e,t))e.isIgnored(r.relative_path)||n.has(r.relative_path)||i.add(r.symbol_id);return i}function va(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function lm(e){return e?.occurrences??0}function xo(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=dm(e,t,n);o.occurrences+=i,o.sources.add(r)}function um(e,t,n,i,r){if(i<=0)return;let o=dm(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function dm(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}function Rt(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=Ue(wk(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),c),d=o?new Set(ld(e)):new Set,m=a?sm():am(e,d,u.map(S=>S.symbolId)),p=a?cm(e,u.map(S=>S.symbolId),d):new Set,h=a?u.filter(S=>!p.has(S.symbolId)):u;a?Nk(e,h,m,d):Pk(e,h,m,d);let g=a?h.filter(S=>!va(m,S.symbolId)):u;Fk(e,g,m,{includeTests:r,inactiveBarrelPaths:d,includeSemantic:!a&&l});let b=a?h.filter(S=>!va(m,S.symbolId)):u;return Ik(e,Lk(b,m))}function wk(e,t){let n=im(e),i=[];for(let r of j(e,{scope:t.scope}))try{for(let o of G(e,r))om(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&i.push(o)}finally{xa(e,r,{definitions:!0})}return i}function Lk(e,t){return e.map(n=>Dk(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function Dk(e,t){let n=t.get(e.symbolId)??new Map,i=lm(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:i,cross_file_refs:r}}function Ik(e,t){let n=[],i=0,r=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||we(e,s.relative_path)||ie(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?i++:r++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:y(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,counts:{total:n.length,deadCode:i,fileInternal:r,loc:o},totalCount:n.length,deadCodeCount:i,fileInternalCount:r,totalLoc:o}}function Pk(e,t,n,i){if(t.length===0)return;let r=new T(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let c of j(e))a.add(c);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>i.has(c)},c=>{o.has(c.target.symbolId)&&(_k(e,c)||xo(n,c.target.symbolId,c.sourceFile,$k(c),"source-fallback"))})}function Nk(e,t,n,i){if(t.length===0)return;let r=new T(e),o=Ek(t),s=new Set(r.sourceFiles());for(let u of j(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=bo(e,u),c.set(u,d)),d};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>i.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?Tk(u,d,p,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),xa(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&mm(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||xo(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function Ek(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let i=t.get(n.leaf)??[];i.push(n),t.set(n.leaf,i)}return t}function Tk(e,t,n,i,r){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i.get(t);if(s)for(let c of s){let l=n.filter(u=>Ot(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of i.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>Ot(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return r.permissive?[...n]:[]}function _k(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&mm(e,t)}function $k(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function mm(e,t){return t.occurrences>1?!1:fe(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Fk(e,t,n,i){for(let r of t){let o=qe(e,r,{semantic:i.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===r.relativePath||e.isIgnored(a)||i.inactiveBarrelPaths.has(a)||!i.includeTests&&!Ca(a)||um(n,r.symbolId,a,1,"caller-map")}}}function Ra(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"",s=e.all(`SELECT
288
288
  gs.symbol,
289
289
  COUNT(*) AS ref_count,
290
290
  COUNT(DISTINCT ref_d.id) AS file_count,
@@ -307,14 +307,14 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
307
307
  ${r}
308
308
  GROUP BY gs.id
309
309
  ORDER BY ref_count DESC
310
- LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:y(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:Pk(e,i,n)}function Pk(e,t,n){return ot(e,{scope:t}).filter(i=>!e.isIgnored(i.relativePath)).map(i=>Nk(e,i)).filter(i=>i.refCount>0).sort((i,r)=>r.refCount-i.refCount||r.fileCount-i.fileCount).slice(0,n)}function Nk(e,t){let n=qe(e,t,{limit:500});return{symbol:t.symbol,shortName:y(t.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:t.relativePath}}function Ca(e,t,n={}){return dm(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function va(e,t){let n=Ek(e,t);return n.length>0?n:Tk(e,t)}function Ra(e,t,n={}){return dm(e,t,n)?.filter(i=>!i.used).map(i=>({symbol:i.symbol,shortName:i.shortName,importedIn:i.importer}))??[]}function Ek(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
310
+ LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:y(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:Ak(e,i,n)}function Ak(e,t,n){return rt(e,{scope:t}).filter(i=>!e.isIgnored(i.relativePath)).map(i=>Mk(e,i)).filter(i=>i.refCount>0).sort((i,r)=>r.refCount-i.refCount||r.fileCount-i.fileCount).slice(0,n)}function Mk(e,t){let n=qe(e,t,{limit:500});return{symbol:t.symbol,shortName:y(t.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:t.relativePath}}function ka(e,t,n={}){return fm(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function wa(e,t){let n=Ok(e,t);return n.length>0?n:jk(e,t)}function La(e,t,n={}){return fm(e,t,n)?.filter(i=>!i.used).map(i=>({symbol:i.symbol,shortName:i.shortName,importedIn:i.importer}))??[]}function Ok(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
311
311
  FROM mentions m
312
312
  JOIN chunks c ON m.chunk_id = c.id
313
313
  JOIN documents d ON c.document_id = d.id
314
314
  JOIN global_symbols gs ON m.symbol_id = gs.id
315
315
  WHERE gs.symbol LIKE ?
316
316
  AND m.role = 2
317
- ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:y(i.symbol),fromFile:i.importer}))}function Tk(e,t){let n=B(e,t),i=n?.relativePath??null,r=n?F(n.symbol):t.replace(/\(\)$/,""),o=n?Tt(n.symbol):!1,s=new Set;for(let a of j(e,{includeIgnored:!1}))for(let c of fe(e,a))_k(c,a,{targetFile:i,targetLeaf:r,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??r,shortName:n?y(n.symbol):r,fromFile:a}))}function _k(e,t,n){return!e.sourcePath||n.targetFile&&um(e.sourcePath)!==um(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&Mk(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function dm(e,t,n={}){let i=Ie(e,t);return i?Fk(e,i,n)??(n.semantic===!1?null:$k(e,i))??Ak(e,i):null}function Fk(e,t,n){let r=e.all(`SELECT DISTINCT
317
+ ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:y(i.symbol),fromFile:i.importer}))}function jk(e,t){let n=B(e,t),i=n?.relativePath??null,r=n?$(n.symbol):t.replace(/\(\)$/,""),o=n?Tt(n.symbol):!1,s=new Set;for(let a of j(e,{includeIgnored:!1}))for(let c of fe(e,a))Bk(c,a,{targetFile:i,targetLeaf:r,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??r,shortName:n?y(n.symbol):r,fromFile:a}))}function Bk(e,t,n){return!e.sourcePath||n.targetFile&&pm(e.sourcePath)!==pm(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&Uk(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function fm(e,t,n={}){let i=Ie(e,t);return i?Hk(e,i,n)??(n.semantic===!1?null:Vk(e,i))??qk(e,i):null}function Hk(e,t,n){let r=e.all(`SELECT DISTINCT
318
318
  gs.symbol,
319
319
  def_d.relative_path AS from_file,
320
320
  imp_d.relative_path AS importer,
@@ -340,11 +340,11 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
340
340
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
341
341
  WHERE imp_d.relative_path = ?
342
342
  AND m.role = 2
343
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:qi(e,t);return r.map(s=>({symbol:s.symbol,shortName:y(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function $k(e,t){let n=qi(e,t);return n.length>0?n.map(i=>{let r=mm(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function Ak(e,t){return fe(e,t).map(n=>{let i=mm(n.importedName,n.localName,n.kind),r=n.kind==="side-effect"?!0:n.used;return{symbol:i,shortName:i,fromFile:n.sourcePath??"(external)",importer:t,used:r}})}function mm(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function um(e){return e.replace(/\\/g,"/")}function Mk(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function ka(e,t){let n=Kn(e,t),i=Br(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let c=i[a],l=r[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let m of r)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!Su(m.symbol,l.symbol))continue;let h=m.endLine-m.startLine;h<d&&(d=h,u=m)}u?u.children.push(l):s.push(l)}return s}function wa(e,t){let n=B(e,t);return n?new T(e).definitionsForFile(n.relativePath).filter(r=>r.symbol!==n.symbol).filter(r=>yu(n.symbol,r.symbol)).sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine).map(r=>({symbol:r.symbol,shortName:y(r.symbol),startLine:r.startLine,endLine:r.endLine,kind:Z(r.symbol)??"unknown"})):[]}function La(e,t){let n=B(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
343
+ ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:qi(e,t);return r.map(s=>({symbol:s.symbol,shortName:y(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function Vk(e,t){let n=qi(e,t);return n.length>0?n.map(i=>{let r=gm(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function qk(e,t){return fe(e,t).map(n=>{let i=gm(n.importedName,n.localName,n.kind),r=n.kind==="side-effect"?!0:n.used;return{symbol:i,shortName:i,fromFile:n.sourcePath??"(external)",importer:t,used:r}})}function gm(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function pm(e){return e.replace(/\\/g,"/")}function Uk(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Da(e,t){let n=Kn(e,t),i=Hr(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let c=i[a],l=r[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let m of r)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!vu(m.symbol,l.symbol))continue;let h=m.endLine-m.startLine;h<d&&(d=h,u=m)}u?u.children.push(l):s.push(l)}return s}function Ia(e,t){let n=B(e,t);return n?new T(e).definitionsForFile(n.relativePath).filter(r=>r.symbol!==n.symbol).filter(r=>Cu(n.symbol,r.symbol)).sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine).map(r=>({symbol:r.symbol,shortName:y(r.symbol),startLine:r.startLine,endLine:r.endLine,kind:Z(r.symbol)??"unknown"})):[]}function Pa(e,t){let n=B(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
344
344
  FROM mentions m
345
345
  JOIN chunks c ON m.chunk_id = c.id
346
346
  WHERE m.symbol_id = ?
347
- AND m.role != 1`,n.symbolId);return[{name:y(n.symbol),count:i?.file_count??0}]}function Da(e,t){let n=Ie(e,t);if(!n)return[];let r=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
347
+ AND m.role != 1`,n.symbolId);return[{name:y(n.symbol),count:i?.file_count??0}]}function Na(e,t){let n=Ie(e,t);if(!n)return[];let r=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
348
348
  FROM mentions m
349
349
  JOIN chunks c ON m.chunk_id = c.id
350
350
  JOIN documents d ON c.document_id = d.id
@@ -361,7 +361,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
361
361
  AND m.role != 1
362
362
  AND def_d.id != d.id
363
363
  GROUP BY d.id
364
- ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(r.length>0)return r;let s=ne(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Ia(e,t={}){return Ok(e,t).map(n=>({name:y(n.symbol),count:n.file_count}))}function Ok(e,t){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
364
+ ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(r.length>0)return r;let s=ne(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Ea(e,t={}){return Wk(e,t).map(n=>({name:y(n.symbol),count:n.file_count}))}function Wk(e,t){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
365
365
  FROM mentions m
366
366
  JOIN chunks c ON m.chunk_id = c.id
367
367
  JOIN global_symbols gs ON m.symbol_id = gs.id
@@ -380,7 +380,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
380
380
  GROUP BY gs.id
381
381
  HAVING file_count > 1
382
382
  ORDER BY file_count DESC
383
- LIMIT ?`,n)}function Pa(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
383
+ LIMIT ?`,n)}function Ta(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
384
384
  FROM mentions m
385
385
  JOIN chunks c ON m.chunk_id = c.id
386
386
  JOIN documents d ON c.document_id = d.id
@@ -400,7 +400,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
400
400
  ${r}
401
401
  GROUP BY d.id
402
402
  ORDER BY symbol_count DESC
403
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function Na(e,t,n){let i=Ie(e,t)??t,r=Ie(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
403
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function _a(e,t,n){let i=Ie(e,t)??t,r=Ie(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
404
404
  FROM global_symbols gs
405
405
  WHERE (
406
406
  -- Defined in file1, referenced in file2
@@ -432,7 +432,7 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
432
432
  JOIN documents d ON c.document_id = d.id
433
433
  WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
434
434
  )
435
- )`,i,r,r,i);return{...pm(i,r,o?.shared??0)}}function Ea(e,t={}){let{limit:n=20,scope:i}=t,r=i?`AND d1.relative_path LIKE '%${i}%' AND d2.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT
435
+ )`,i,r,r,i);return{...hm(i,r,o?.shared??0)}}function $a(e,t={}){let{limit:n=20,scope:i}=t,r=i?`AND d1.relative_path LIKE '%${i}%' AND d2.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT
436
436
  def_d.relative_path AS file1,
437
437
  ref_d.relative_path AS file2,
438
438
  COUNT(DISTINCT gs.id) AS shared
@@ -454,11 +454,11 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
454
454
  ${r}
455
455
  GROUP BY def_d.id, ref_d.id
456
456
  ORDER BY shared DESC
457
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>pm(s.file1,s.file2,s.shared))}function pm(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function mn(e,t={}){let{scope:n,maxDepth:i=10}=t,r=ne(e,n),o=[],s=new Set,a=new Set,c=[];function l(d,m){if(m>i)return;if(a.has(d)){let h=c.indexOf(d);if(h!==-1){let g=c.slice(h).concat(d),b=g.indexOf(g.reduce((I,L)=>I<L?I:L)),S=[...g.slice(b,-1),...g.slice(0,b),g[b]],x=S.join(" -> ");u.has(x)||(u.add(x),o.push({path:S,kind:jk(S)}))}return}if(s.has(d))return;s.add(d),a.add(d),c.push(d);let p=r.get(d);if(p)for(let h of p)l(h,m+1);c.pop(),a.delete(d)}let u=new Set;for(let d of r.keys())s.has(d)||l(d,0);return o.sort((d,m)=>d.kind!==m.kind?d.kind==="real"?-1:1:d.path.length-m.path.length),o}function jk(e){for(let i of e){let r=K(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":oo(t)||oo(n)||fm(t,n)||fm(n,t)||gm(t,n)||gm(n,t)||K(t)==="entry"||K(n)==="entry"?"module-hierarchy":"real"}function fm(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function gm(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function Ta(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new T(e);return Ue(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>Bk(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=r&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function Bk(e,t,n){let i=new Set(qe(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,r=new Set(Ae(e,t,{limit:500,semantic:n}).filter(s=>s.file!==t.relativePath).map(s=>`${s.symbol}|${s.file}`)).size,o=i*r;return{symbol:t.symbol,shortName:y(t.symbol),fanIn:i,fanOut:r,score:o,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${i} incoming file(s) reference this symbol`,`${r} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${o} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function pn(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new T(e),s=t.semantic!==!1,a=Ue(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof r=="number"&&r>0}),r),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let g of o.frameworkReferencedSymbolIds(a))l.add(g);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),d=a.filter(g=>!l.has(g.symbolId)).filter(g=>!u.has(g.symbolId)),m=o.sourceFallbackCallerFiles(d);for(let g of m.keys())l.add(g);let p=d.filter(g=>!l.has(g.symbolId)),h=o.symbolsWithNonSelfCallees(p,{additive:!0,semantic:s});for(let g of h)u.add(g);return p.filter(g=>!u.has(g.symbolId)).sort((g,b)=>q(b)-q(g)||g.relativePath.localeCompare(b.relativePath)||g.startLine-b.startLine).map(g=>({symbol:g.symbol,shortName:y(g.symbol),relativePath:g.relativePath,startLine:g.startLine,endLine:g.endLine,loc:q(g)}))}var Fa={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},_a=new Map;for(let[e,t]of Object.entries(Fa))_a.set(t.toLowerCase(),Number(e));function Hk(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=_a.get(n);if(i!==void 0)return i;for(let[r,o]of _a)if(r.includes(n))return o;return null}function $a(e,t,n={}){let{scope:i,limit:r=100}=n,o=Hk(t);return o===null?[]:hm(e,i).map(a=>({row:a,resolvedKind:bm(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:y(a.symbol),kind:c,kindName:Fa[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function Aa(e,t={}){let n=new Map;for(let i of hm(e,t.scope)){let r=bm(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:Fa[i]??"Unknown",count:r}))}function hm(e,t){return ot(e,{scope:t}).map(Vk)}function Vk(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function bm(e){return e.kind!==null&&e.kind!==0?qk(e.kind,e.symbol,e.documentation):Uk(e.symbol,e.documentation,e.enclosing_symbol)}function qk(e,t,n){let i=(n??"").toLowerCase();if(Z(t)==="type"){if(i.includes("type "))return 76;if(i.includes("interface "))return 27;if(i.includes("struct "))return 68;if(i.includes("trait "))return 73;if(i.includes("class "))return 9}return e}function Uk(e,t,n){let i=pe(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=Z(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):s==="method"?o?.suffix==="type"?33:23:s==="namespace"?39:s!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?Z(n):o?.suffix??null)==="type"?21:83}function Ma(e,t={}){let{limit:n=10,scope:i,minDepth:r=3}=t,o=ne(e,i),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],m=0;for(let C of o.keys()){if(c.has(C))continue;let D=[],k=(o.get(C)??new Set).values();for(c.set(C,m),l.set(C,m),m+=1,d.push(C),u.add(C),D.push({node:C,iter:k,pendingChild:null});D.length>0;){let A=D[D.length-1];if(A.pendingChild!==null){let Te=A.pendingChild;A.pendingChild=null,l.set(A.node,Math.min(l.get(A.node),l.get(Te)))}let Se=A.iter.next();if(Se.done){if(l.get(A.node)===c.get(A.node)){let Te=[];for(;;){let bt=d.pop();if(u.delete(bt),Te.push(bt),s.set(bt,a.length),bt===A.node)break}a.push(Te)}D.pop();continue}let de=Se.value;if(c.has(de))u.has(de)&&l.set(A.node,Math.min(l.get(A.node),c.get(de)));else{c.set(de,m),l.set(de,m),m+=1,d.push(de),u.add(de);let Te=(o.get(de)??new Set).values();A.pendingChild=de,D.push({node:de,iter:Te,pendingChild:null})}}}let p=new Map,h=new Array(a.length);for(let C=0;C<a.length;C++)h[C]=a[C].length,p.set(C,new Set);for(let[C,D]of o){let k=s.get(C);for(let A of D){let Se=s.get(A);Se!==k&&p.get(k).add(Se)}}let g=new Array(a.length),b=new Array(a.length);for(let C=0;C<a.length;C++){let D=[],k=0;for(let A of p.get(C)){let Se=b[A];Se>k&&(k=Se,D=g[A])}g[C]=[C,...D],b[C]=h[C]+k}function S(C){return g[C]}let x=a.map(C=>[...C].sort()),I=new Set,L=[];for(let C=0;C<a.length;C++){let D=S(C),k=[];for(let Se of D)k.push(...x[Se]);if(k.length<r)continue;let A=k.join(" ");I.has(A)||(I.add(A),L.push(Wk(k)))}return L.sort((C,D)=>D.depth-C.depth),Gk(L).slice(0,n)}function Wk(e){return{chain:e,depth:e.length,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${e.length} file(s) form the representative transitive dependency path`,"cycles are condensed before longest-path calculation"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function Gk(e){let t=[];for(let n of e)t.some(i=>zk(n.chain,i.chain))||t.push(n);return t}function zk(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function Oa(e,t){let n=B(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
458
- WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:y(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;r.push({symbol:d.symbol,shortName:y(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let c=pe(i.symbol);if("kind"in c)return r;let l=c.descriptors;if(l.length<=1)return r;let u=[r[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let h=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:h,shortName:h,depth:m})}return u}function Xi(e,t,n={}){let i=B(e,t);if(!i)return null;let r=n.semantic!==!1,o=qe(e,i,{limit:50,semantic:r}),s=si(Ae(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r}));return{symbol:i.symbol,shortName:y(i.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file}))}}function Le(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function ge(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function Ht(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function ym(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function ja(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let r of e)for(let o of r)n.set(o,(n.get(o)??0)+1);let i=new Map;for(let[r,o]of n)i.set(r,Math.log(t/o));return i}function Kk(e){let t=[...e.values()].sort((i,r)=>i-r);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Sm(e,t,n){let i=Le(e,t);if(i.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let r=0,o=0,s=0,a=new Set([...e,...t]);for(let p of a){let h=n.get(p)??0,g=e.has(p)?h:0,b=t.has(p)?h:0;r+=g*b,o+=g*g,s+=b*b}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?r/c:0,u=Kk(n),d=[],m=[];for(let p of i)(n.get(p)??0)>=u?d.push(p):m.push(p);return d.sort((p,h)=>(n.get(h)??0)-(n.get(p)??0)),{similarity:l,significantShared:d,trivialShared:m}}function Zi(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=Yk(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!se(o.symbol))return[];let s=Jk(e,o,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,r):sw(e,t,{minSimilarity:i,limit:r})}function Jk(e,t,n,i){let r=tw(e,{minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=iw(t,r),s=ja([t,...r.corpus].map(c=>c.callees)),a=[];for(let c of o){if(c.callees.size<3)continue;let l=vm(t,c,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});l&&a.push(l)}return a.sort((c,l)=>l.similarity-c.similarity),a}function vm(e,t,n,i){let{similarity:r,significantShared:o}=Sm(e.callees,t.callees,n);if(r<i.minSimilarity)return null;let s=Le(e.callees,t.callees).size;if(o.length<i.requireSignificantShared&&s<i.requireSharedCount)return null;let a=o.length>0?o:[...Le(e.callees,t.callees)],c=Rm(a,"callees");return{symbolA:e.symbol,shortNameA:y(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:y(t.symbol),fileB:t.file,similarity:r,similarityBasis:"callees",sharedCallees:a.map(y),uniqueToA:[...ge(e.callees,t.callees)].map(y),uniqueToB:[...ge(t.callees,e.callees)].map(y),...c}}function kt(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=xo(e,{minCallees:o,scope:r,scanLimit:a,semantic:t.semantic!==!1}),l=ja(c.map(b=>b.callees)),u=new Map;for(let b of c)for(let S of b.callees)u.set(S,(u.get(S)??0)+1);let d=Math.max(8,Math.ceil(Math.sqrt(c.length))),m=new Map;for(let b=0;b<c.length;b+=1)for(let S of c[b].callees){if((u.get(S)??0)>d)continue;let x=m.get(S);x||(x=[],m.set(S,x)),x.push(b)}let p=[],h=0,g=new Set;for(let b=0;b<c.length;b+=1){let S=c[b],x=new Set;for(let I of S.callees){let L=m.get(I);if(L)for(let C of L)C>b&&x.add(C)}for(let I of x){let L=`${b}|${I}`;if(g.has(L))continue;g.add(L);let C=c[I];if(s&&S.file===C.file)continue;if(S.paramCount>=0&&C.paramCount>=0){let k=Math.abs(S.paramCount-C.paramCount),A=Math.max(2,Math.ceil(Math.max(S.paramCount,C.paramCount)*.5));if(k>A)continue}let D=vm(S,C,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});D&&(Qk(p,D,i,h),h+=1)}}return p.sort((b,S)=>S.result.similarity-b.result.similarity||b.order-S.order),p.map(b=>b.result)}function Qk(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[r];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var Xk=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function Yk(e,t,n){let i=B(e,t),r=new T(e);if(!i)return null;let o=Ae(e,i,{semantic:n.semantic});return{symbol:i.symbol,file:i.relativePath,callees:Co(o.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}var Zk=Y("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),ew=Y("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function xo(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=Zk.get(e,()=>new Map),c=`${n}|${i??""}|${o??""}|${s}`,l=a.get(c);return l||(l=rw(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(c,l)),r===void 0?l:l.filter(u=>u.symbol!==r)}function tw(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=ew.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,c=s.get(a);return c||(c=nw(xo(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,c)),c}function nw(e){let t=new Map;for(let r of e)for(let o of r.callees)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.callees){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByCallee:i,docFreq:t,ubiquityThreshold:n}}function iw(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateByCallee.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function rw(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=new T(e),a=Ue(s.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r),c=s.calleeMap(a,{semantic:o});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:Co((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Co(e){return new Set([...e].filter(t=>!ow(t)))}function ow(e){return Xk.some(t=>e.includes(t))}function sw(e,t,n){let i=uw(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=bw(i,gw(e));for(let a of s){if(a.symbol===i.symbol||a.tokens.size<3)continue;let c=Le(i.tokens,a.tokens);if(c.size<2)continue;let l=new Set([...i.tokens,...a.tokens]),u=l.size>0?c.size/l.size:0;u<r||o.push({symbolA:i.symbol,shortNameA:y(i.symbol),fileA:i.file,symbolB:a.symbol,shortNameB:y(a.symbol),fileB:a.file,similarity:u,similarityBasis:"source-tokens",sharedCallees:[...c].sort(),uniqueToA:[...ge(i.tokens,a.tokens)].sort(),uniqueToB:[...ge(a.tokens,i.tokens)].sort(),...Rm([...c],"source-tokens")})}return o.sort((a,c)=>c.similarity-a.similarity||a.shortNameB.localeCompare(c.shortNameB)),o.slice(0,n.limit)}function Rm(e,t){let n=e.flatMap(Ha),i=e.flatMap(b=>xm(b,t)),r=Ba(n,km),o=Ba(n,wm),s=Ba(i,Va),a=[...new Set(i.filter(Cm))],c=e.filter(b=>{let S=xm(b,t);return S.some(x=>Va.has(x))&&S.some(Cm)}).length,l=[];r.length>0&&l.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(b=>Lm.has(b));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=r.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,h=p?"domain-behavior":d?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";h==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=h==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:h,actionTier:g,evidenceClassReasons:l,recommendation:aw(h,g)}}function aw(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function Ba(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Ha(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function xm(e,t){if(t==="source-tokens")return Ha(e);let n=F(e);return Ha(n.length>0?n:cw(e))}function cw(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function Cm(e){return e.length>3&&!Va.has(e)&&!km.has(e)&&!wm.has(e)&&!Lm.has(e)&&!lw.has(e)}var Va=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),km=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),wm=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),Lm=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),lw=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function uw(e,t){let n=B(e,t);if(!n||!se(n.symbol))return null;let i=dw(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function dw(e,t){let n=F(t.symbol),i=Dm(e,t.relativePath,t.startLine,t.endLine,n),r=Im(i,n);return r.size>0?r:null}var mw=Y("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),pw=Y("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function fw(e){return mw.get(e,()=>yw(e))}function gw(e){return pw.get(e,()=>hw(fw(e)))}function hw(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function bw(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function yw(e){return new T(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Im(Dm(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function Dm(e,t,n,i,r){let o=_e(e,t);if(o.length===0)return"";if(i>=n&&i-n<=12)return o.slice(n,i+1).join(`
459
- `);let s=[new RegExp(`\\bdef\\s+${Yi(r)}\\b`),new RegExp(`\\bfun\\s+${Yi(r)}\\b`),new RegExp(`\\bfn\\s+${Yi(r)}\\b`),new RegExp(`\\bfunction\\s+${Yi(r)}\\b`),new RegExp(`\\b${Yi(r)}\\s*\\(`)],a=o.findIndex(c=>s.some(l=>l.test(c)));if(a>=0){let c=a;for(let l=a+1;l<o.length&&l<=a+8;l++){let u=o[l]??"";if(l>a&&xw(u)||(c=l,u.trim()===""&&l>a+1))break}return o.slice(a,c+1).join(`
457
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>hm(s.file1,s.file2,s.shared))}function hm(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function mn(e,t={}){let{scope:n,maxDepth:i=10}=t,r=ne(e,n),o=[],s=new Set,a=new Set,c=[];function l(d,m){if(m>i)return;if(a.has(d)){let h=c.indexOf(d);if(h!==-1){let g=c.slice(h).concat(d),b=g.indexOf(g.reduce((I,L)=>I<L?I:L)),S=[...g.slice(b,-1),...g.slice(0,b),g[b]],x=S.join(" -> ");u.has(x)||(u.add(x),o.push({path:S,kind:Gk(S)}))}return}if(s.has(d))return;s.add(d),a.add(d),c.push(d);let p=r.get(d);if(p)for(let h of p)l(h,m+1);c.pop(),a.delete(d)}let u=new Set;for(let d of r.keys())s.has(d)||l(d,0);return o.sort((d,m)=>d.kind!==m.kind?d.kind==="real"?-1:1:d.path.length-m.path.length),o}function Gk(e){for(let i of e){let r=K(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":so(t)||so(n)||bm(t,n)||bm(n,t)||ym(t,n)||ym(n,t)||K(t)==="entry"||K(n)==="entry"?"module-hierarchy":"real"}function bm(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function ym(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function Fa(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new T(e);return Ue(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>zk(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=r&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function zk(e,t,n){let i=new Set(qe(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,r=new Set(Ae(e,t,{limit:500,semantic:n}).filter(s=>s.file!==t.relativePath).map(s=>`${s.symbol}|${s.file}`)).size,o=i*r;return{symbol:t.symbol,shortName:y(t.symbol),fanIn:i,fanOut:r,score:o,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${i} incoming file(s) reference this symbol`,`${r} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${o} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function pn(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new T(e),s=t.semantic!==!1,a=Ue(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof r=="number"&&r>0}),r),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let g of o.frameworkReferencedSymbolIds(a))l.add(g);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),d=a.filter(g=>!l.has(g.symbolId)).filter(g=>!u.has(g.symbolId)),m=o.sourceFallbackCallerFiles(d);for(let g of m.keys())l.add(g);let p=d.filter(g=>!l.has(g.symbolId)),h=o.symbolsWithNonSelfCallees(p,{additive:!0,semantic:s});for(let g of h)u.add(g);return p.filter(g=>!u.has(g.symbolId)).sort((g,b)=>q(b)-q(g)||g.relativePath.localeCompare(b.relativePath)||g.startLine-b.startLine).map(g=>({symbol:g.symbol,shortName:y(g.symbol),relativePath:g.relativePath,startLine:g.startLine,endLine:g.endLine,loc:q(g)}))}var Ma={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},Aa=new Map;for(let[e,t]of Object.entries(Ma))Aa.set(t.toLowerCase(),Number(e));function Kk(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=Aa.get(n);if(i!==void 0)return i;for(let[r,o]of Aa)if(r.includes(n))return o;return null}function Oa(e,t,n={}){let{scope:i,limit:r=100}=n,o=Kk(t);return o===null?[]:Sm(e,i).map(a=>({row:a,resolvedKind:xm(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:y(a.symbol),kind:c,kindName:Ma[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function ja(e,t={}){let n=new Map;for(let i of Sm(e,t.scope)){let r=xm(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:Ma[i]??"Unknown",count:r}))}function Sm(e,t){return rt(e,{scope:t}).map(Jk)}function Jk(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function xm(e){return e.kind!==null&&e.kind!==0?Qk(e.kind,e.symbol,e.documentation):Xk(e.symbol,e.documentation,e.enclosing_symbol)}function Qk(e,t,n){let i=(n??"").toLowerCase();if(Z(t)==="type"){if(i.includes("type "))return 76;if(i.includes("interface "))return 27;if(i.includes("struct "))return 68;if(i.includes("trait "))return 73;if(i.includes("class "))return 9}return e}function Xk(e,t,n){let i=pe(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=Z(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):s==="method"?o?.suffix==="type"?33:23:s==="namespace"?39:s!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?Z(n):o?.suffix??null)==="type"?21:83}function Ba(e,t={}){let{limit:n=10,scope:i,minDepth:r=3}=t,o=ne(e,i),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],m=0;for(let C of o.keys()){if(c.has(C))continue;let D=[],k=(o.get(C)??new Set).values();for(c.set(C,m),l.set(C,m),m+=1,d.push(C),u.add(C),D.push({node:C,iter:k,pendingChild:null});D.length>0;){let A=D[D.length-1];if(A.pendingChild!==null){let Te=A.pendingChild;A.pendingChild=null,l.set(A.node,Math.min(l.get(A.node),l.get(Te)))}let Se=A.iter.next();if(Se.done){if(l.get(A.node)===c.get(A.node)){let Te=[];for(;;){let bt=d.pop();if(u.delete(bt),Te.push(bt),s.set(bt,a.length),bt===A.node)break}a.push(Te)}D.pop();continue}let de=Se.value;if(c.has(de))u.has(de)&&l.set(A.node,Math.min(l.get(A.node),c.get(de)));else{c.set(de,m),l.set(de,m),m+=1,d.push(de),u.add(de);let Te=(o.get(de)??new Set).values();A.pendingChild=de,D.push({node:de,iter:Te,pendingChild:null})}}}let p=new Map,h=new Array(a.length);for(let C=0;C<a.length;C++)h[C]=a[C].length,p.set(C,new Set);for(let[C,D]of o){let k=s.get(C);for(let A of D){let Se=s.get(A);Se!==k&&p.get(k).add(Se)}}let g=new Array(a.length),b=new Array(a.length);for(let C=0;C<a.length;C++){let D=[],k=0;for(let A of p.get(C)){let Se=b[A];Se>k&&(k=Se,D=g[A])}g[C]=[C,...D],b[C]=h[C]+k}function S(C){return g[C]}let x=a.map(C=>[...C].sort()),I=new Set,L=[];for(let C=0;C<a.length;C++){let D=S(C),k=[];for(let Se of D)k.push(...x[Se]);if(k.length<r)continue;let A=k.join(" ");I.has(A)||(I.add(A),L.push(Yk(k)))}return L.sort((C,D)=>D.depth-C.depth),Zk(L).slice(0,n)}function Yk(e){return{chain:e,depth:e.length,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${e.length} file(s) form the representative transitive dependency path`,"cycles are condensed before longest-path calculation"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function Zk(e){let t=[];for(let n of e)t.some(i=>ew(n.chain,i.chain))||t.push(n);return t}function ew(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function Ha(e,t){let n=B(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
458
+ WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:y(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;r.push({symbol:d.symbol,shortName:y(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let c=pe(i.symbol);if("kind"in c)return r;let l=c.descriptors;if(l.length<=1)return r;let u=[r[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let h=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:h,shortName:h,depth:m})}return u}function Xi(e,t,n={}){let i=B(e,t);if(!i)return null;let r=n.semantic!==!1,o=qe(e,i,{limit:50,semantic:r}),s=si(Ae(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r}));return{symbol:i.symbol,shortName:y(i.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file}))}}function Le(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function ge(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function Ht(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function Cm(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function Va(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let r of e)for(let o of r)n.set(o,(n.get(o)??0)+1);let i=new Map;for(let[r,o]of n)i.set(r,Math.log(t/o));return i}function tw(e){let t=[...e.values()].sort((i,r)=>i-r);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function vm(e,t,n){let i=Le(e,t);if(i.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let r=0,o=0,s=0,a=new Set([...e,...t]);for(let p of a){let h=n.get(p)??0,g=e.has(p)?h:0,b=t.has(p)?h:0;r+=g*b,o+=g*g,s+=b*b}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?r/c:0,u=tw(n),d=[],m=[];for(let p of i)(n.get(p)??0)>=u?d.push(p):m.push(p);return d.sort((p,h)=>(n.get(h)??0)-(n.get(p)??0)),{similarity:l,significantShared:d,trivialShared:m}}function Zi(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=ow(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!se(o.symbol))return[];let s=nw(e,o,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,r):pw(e,t,{minSimilarity:i,limit:r})}function nw(e,t,n,i){let r=cw(e,{minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=uw(t,r),s=Va([t,...r.corpus].map(c=>c.callees)),a=[];for(let c of o){if(c.callees.size<3)continue;let l=wm(t,c,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});l&&a.push(l)}return a.sort((c,l)=>l.similarity-c.similarity),a}function wm(e,t,n,i){let{similarity:r,significantShared:o}=vm(e.callees,t.callees,n);if(r<i.minSimilarity)return null;let s=Le(e.callees,t.callees).size;if(o.length<i.requireSignificantShared&&s<i.requireSharedCount)return null;let a=o.length>0?o:[...Le(e.callees,t.callees)],c=Lm(a,"callees");return{symbolA:e.symbol,shortNameA:y(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:y(t.symbol),fileB:t.file,similarity:r,similarityBasis:"callees",sharedCallees:a.map(y),uniqueToA:[...ge(e.callees,t.callees)].map(y),uniqueToB:[...ge(t.callees,e.callees)].map(y),...c}}function kt(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=Co(e,{minCallees:o,scope:r,scanLimit:a,semantic:t.semantic!==!1}),l=Va(c.map(b=>b.callees)),u=new Map;for(let b of c)for(let S of b.callees)u.set(S,(u.get(S)??0)+1);let d=Math.max(8,Math.ceil(Math.sqrt(c.length))),m=new Map;for(let b=0;b<c.length;b+=1)for(let S of c[b].callees){if((u.get(S)??0)>d)continue;let x=m.get(S);x||(x=[],m.set(S,x)),x.push(b)}let p=[],h=0,g=new Set;for(let b=0;b<c.length;b+=1){let S=c[b],x=new Set;for(let I of S.callees){let L=m.get(I);if(L)for(let C of L)C>b&&x.add(C)}for(let I of x){let L=`${b}|${I}`;if(g.has(L))continue;g.add(L);let C=c[I];if(s&&S.file===C.file)continue;if(S.paramCount>=0&&C.paramCount>=0){let k=Math.abs(S.paramCount-C.paramCount),A=Math.max(2,Math.ceil(Math.max(S.paramCount,C.paramCount)*.5));if(k>A)continue}let D=wm(S,C,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});D&&(iw(p,D,i,h),h+=1)}}return p.sort((b,S)=>S.result.similarity-b.result.similarity||b.order-S.order),p.map(b=>b.result)}function iw(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[r];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var rw=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function ow(e,t,n){let i=B(e,t),r=new T(e);if(!i)return null;let o=Ae(e,i,{semantic:n.semantic});return{symbol:i.symbol,file:i.relativePath,callees:vo(o.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}var sw=Y("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),aw=Y("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Co(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=sw.get(e,()=>new Map),c=`${n}|${i??""}|${o??""}|${s}`,l=a.get(c);return l||(l=dw(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(c,l)),r===void 0?l:l.filter(u=>u.symbol!==r)}function cw(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=aw.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,c=s.get(a);return c||(c=lw(Co(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,c)),c}function lw(e){let t=new Map;for(let r of e)for(let o of r.callees)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.callees){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByCallee:i,docFreq:t,ubiquityThreshold:n}}function uw(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateByCallee.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function dw(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=new T(e),a=Ue(s.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r),c=s.calleeMap(a,{semantic:o});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:vo((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function vo(e){return new Set([...e].filter(t=>!mw(t)))}function mw(e){return rw.some(t=>e.includes(t))}function pw(e,t,n){let i=bw(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=kw(i,vw(e));for(let a of s){if(a.symbol===i.symbol||a.tokens.size<3)continue;let c=Le(i.tokens,a.tokens);if(c.size<2)continue;let l=new Set([...i.tokens,...a.tokens]),u=l.size>0?c.size/l.size:0;u<r||o.push({symbolA:i.symbol,shortNameA:y(i.symbol),fileA:i.file,symbolB:a.symbol,shortNameB:y(a.symbol),fileB:a.file,similarity:u,similarityBasis:"source-tokens",sharedCallees:[...c].sort(),uniqueToA:[...ge(i.tokens,a.tokens)].sort(),uniqueToB:[...ge(a.tokens,i.tokens)].sort(),...Lm([...c],"source-tokens")})}return o.sort((a,c)=>c.similarity-a.similarity||a.shortNameB.localeCompare(c.shortNameB)),o.slice(0,n.limit)}function Lm(e,t){let n=e.flatMap(Ua),i=e.flatMap(b=>Rm(b,t)),r=qa(n,Dm),o=qa(n,Im),s=qa(i,Wa),a=[...new Set(i.filter(km))],c=e.filter(b=>{let S=Rm(b,t);return S.some(x=>Wa.has(x))&&S.some(km)}).length,l=[];r.length>0&&l.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(b=>Pm.has(b));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=r.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,h=p?"domain-behavior":d?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";h==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=h==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:h,actionTier:g,evidenceClassReasons:l,recommendation:fw(h,g)}}function fw(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function qa(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Ua(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Rm(e,t){if(t==="source-tokens")return Ua(e);let n=$(e);return Ua(n.length>0?n:gw(e))}function gw(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function km(e){return e.length>3&&!Wa.has(e)&&!Dm.has(e)&&!Im.has(e)&&!Pm.has(e)&&!hw.has(e)}var Wa=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Dm=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Im=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),Pm=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),hw=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function bw(e,t){let n=B(e,t);if(!n||!se(n.symbol))return null;let i=yw(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function yw(e,t){let n=$(t.symbol),i=Nm(e,t.relativePath,t.startLine,t.endLine,n),r=Em(i,n);return r.size>0?r:null}var Sw=Y("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),xw=Y("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Cw(e){return Sw.get(e,()=>ww(e))}function vw(e){return xw.get(e,()=>Rw(Cw(e)))}function Rw(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function kw(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function ww(e){return new T(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Em(Nm(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function Nm(e,t,n,i,r){let o=_e(e,t);if(o.length===0)return"";if(i>=n&&i-n<=12)return o.slice(n,i+1).join(`
459
+ `);let s=[new RegExp(`\\bdef\\s+${Yi(r)}\\b`),new RegExp(`\\bfun\\s+${Yi(r)}\\b`),new RegExp(`\\bfn\\s+${Yi(r)}\\b`),new RegExp(`\\bfunction\\s+${Yi(r)}\\b`),new RegExp(`\\b${Yi(r)}\\s*\\(`)],a=o.findIndex(c=>s.some(l=>l.test(c)));if(a>=0){let c=a;for(let l=a+1;l<o.length&&l<=a+8;l++){let u=o[l]??"";if(l>a&&Dw(u)||(c=l,u.trim()===""&&l>a+1))break}return o.slice(a,c+1).join(`
460
460
  `)}return o.slice(n,Math.min(o.length,n+8)).join(`
461
- `)}function Im(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),i=Sw(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!i.has(s));return new Set(o)}function Sw(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function xw(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Yi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ct(e){let t=[];if(e.filePattern){let n=e.profiles.find(i=>i.file.includes(e.filePattern));if(!n)return[];for(let i of e.profiles){if(i.file===n.file)continue;let r=e.compare(n,i);r&&t.push(r)}}else{let n=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let i=0;i<e.profiles.length;i+=1){for(let r=i+1;r<e.profiles.length;r+=1){let o=e.compare(e.profiles[i],e.profiles[r]);o&&t.push(o)}if(t.length>n)break}}return t.sort(e.sort??((n,i)=>i.similarity-n.similarity)),t.slice(0,e.limit)}function qa(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=Cw(e,{scope:r,minDeps:s});return ct({profiles:a,limit:i,filePattern:o,overrunFactor:5,compare:(l,u)=>Rw(l,u,n,c)})}function Cw(e,t){let{scope:n,minDeps:i}=t,r=ne(e,n),{universalDeps:o,distinctiveDeps:s}=vw(r),a=[];for(let[c,l]of r)l.size>=i&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function vw(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function Rw(e,t,n,i){let r=new Set;for(let l of e.deps)t.deps.has(l)&&r.add(l);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of r)i.has(l)&&o++;if(o<2)return null;let s=Ht(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...r],uniqueToA:a,uniqueToB:c}}function vo(e){let t=[],n=[],i=[];for(let l of e.primitiveGroups)l.values.length!==0&&Pm(l.bucket,n,i).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)kw(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,Pm(l.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function Ro(e,t){if(e.size===0||t.size===0)return 0;let i=Le(e,t).size/Math.min(e.size,t.size);return Math.max(Ht(e,t),i)}function V(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Ce(e){return[...e].sort()}function kw(e,t,n,i,r,o){let s=[],a=[];for(let c of e)ww(c,i).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&r.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function ww(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Pm(e,t,n){return e==="generic"?t:n}function fn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Hn(e,{scope:o,minJsxTokens:i,scanLimit:s}).filter(l=>l.kind==="component").map(l=>({file:l.file,component:l.name,tokens:l.jsxTokens,profile:l}));return ct({profiles:c,limit:r,filePattern:a,compare:(l,u)=>Lw(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function Lw(e,t,n){let i=Le(e.tokens,t.tokens);if(i.size<6||!Dw(i))return null;let r=Ht(e.tokens,t.tokens);return r<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,sharedTokens:Ce(i),sharedComponents:V(i,"component:"),sharedNativeTags:V(i,"native:"),sharedProps:V(i,"prop:"),sharedEvents:V(i,"event:"),sharedBindings:V(i,"binding:"),uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function Dw(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return t>=1||n>=4}function gn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Hn(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(l=>({file:l.file,component:l.name,tokens:l.behaviorTokens,profile:l}));return ct({profiles:c,limit:r,filePattern:a,compare:(l,u)=>Iw(l,u,n,i),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function Iw(e,t,n,i){let r=Le(e.tokens,t.tokens);if(r.size<i||!Ew(r))return null;let o=Ro(e.tokens,t.tokens);if(o<n)return null;let s=V(r,"hook:"),a=V(r,"react-hook:"),c=V(r,"effect:"),l=V(r,"state:"),u=V(r,"request:"),d=V(r,"handler:"),m=V(r,"handler-verb:"),p=Pw({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:Ce(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),reason:Tw({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function Pw(e){return vo({genericWords:_w,stripPrefixes:Fw,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:Nw})}function Nw(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function Ew(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?i+=1:u.startsWith("request:")?r+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+i+r+o+c;return r>=1&&l>=4||t>=1&&(r>=1||s>=1||o>=2)&&l>=5||s>=1&&o>=2&&(i>=1||n>=2)&&l>=5}function Tw(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var _w=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),Fw=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function er(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return Hn(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>$w(d,{minComponentLines:n,minFileLines:i,minJsxTokens:r,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function $w(e,t){let n=[];e.loc>=t.minComponentLines&&n.push(`${e.loc} component line(s)`);let i=Math.max(80,Math.floor(t.minComponentLines/2));if(e.fileLines>=t.minFileLines&&e.loc>=i&&n.push(`${e.fileLines} file line(s)`),e.jsxTokens.size>=t.minJsxTokens&&n.push(`${e.jsxTokens.size} JSX structure token(s)`),e.behaviorTokens.size>=t.minBehaviorTokens&&n.push(`${e.behaviorTokens.size} behavior token(s)`),n.length===0)return null;let r=Aw(e),o=Mw(e,t,r),s=Ow(e),a=jw(r,o,s);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:Bw(a,s),reasons:n,loc:e.loc}}function Aw(e){let t=[{axis:"component",value:e.loc},{axis:"file",value:e.fileLines},{axis:"jsx-structure",value:e.jsxTokens.size*3},{axis:"hook-behavior",value:e.behaviorTokens.size*4}];return t.sort((n,i)=>i.value-n.value),t[0]?.axis??"component"}function Mw(e,t,n){let i=[];e.loc>=t.minComponentLines&&i.push("component");let r=Math.max(80,Math.floor(t.minComponentLines/2));return e.fileLines>=t.minFileLines&&e.loc>=r&&i.push("file"),e.jsxTokens.size>=t.minJsxTokens&&i.push("jsx-structure"),e.behaviorTokens.size>=t.minBehaviorTokens&&i.push("hook-behavior"),[...new Set(i.length>0?i:[n])]}function Ow(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(l=>l.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),r=`${i} ${e.name}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map(l=>l.toLowerCase()),o=n.findIndex(l=>Vw.has(l)),s=o>=0&&n.slice(o+1).some(l=>Hw.has(l)),a=Nm(i)||Nm(e.name);return/(?:Page|Route|Screen|View)$/.test(i)||/(?:Page|Route|Screen|View)$/.test(e.name)||r.some(l=>qw.has(l))||o>=0&&!s&&!a?"route-page":"component"}function Nm(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&Em.has(t.at(-1))?!0:[...Em].some(n=>e.endsWith(Uw(n)))}function jw(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function Bw(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var Hw=new Set(["component","components","panel","panels","partial","partials"]),Em=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),Vw=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),qw=new Set(["landing","page","route","screen","view"]);function Uw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function hn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Ww(e,{scope:o,minTokens:i,scanLimit:s});return ct({profiles:c,limit:r,filePattern:a,compare:(l,u)=>zw(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Ww(e,t){return Bn(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:Gw(n)}))}function Gw(e){return e.totalLines}function zw(e,t,n){let i=Le(e.tokens,t.tokens);if(i.size<6||!Kw(i))return null;let r=Ht(e.tokens,t.tokens);return r<n?null:{fileA:e.file,fileB:t.file,similarity:r,sharedTokens:Ce(i),sharedComponents:V(i,"component:"),sharedProps:V(i,"prop:"),sharedEvents:V(i,"event:"),sharedDirectives:V(i,"directive:"),sharedSlots:V(i,"slot:"),sharedIdentifiers:V(i,"id:"),uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function Kw(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return t>=1||n>=3}function bn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Bn(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(l=>({file:l.file,tokens:l.behaviorTokens,profile:l}));return ct({profiles:c,limit:r,filePattern:a,compare:(l,u)=>Jw(l,u,n,i),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Jw(e,t,n,i){let r=Le(e.tokens,t.tokens);if(r.size<i||!Yw(r))return null;let o=Ro(e.tokens,t.tokens);if(o<n)return null;let s=V(r,"composable:"),a=V(r,"store:"),c=V(r,"reactivity:"),l=V(r,"lifecycle:"),u=V(r,"request:"),d=V(r,"function:"),m=V(r,"function-verb:"),p=V(r,"template-binding:"),h=V(r,"template-event:"),g=Qw({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:h});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:Ce(r),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:h,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),reason:Zw({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function Qw(e){return vo({genericWords:eL,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:Xw})}function Xw(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function Yw(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?i+=1:u.startsWith("lifecycle:")?r+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+i+r+o+a;return i>=1&&l>=4||r>=1&&o>=2&&l>=4||c>=2&&(i>=1||o>=2)&&l>=5||o>=2&&s>=1&&l>=4}function Zw(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var eL=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function tr(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return Bn(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>tL(d,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function tL(e,t){let n=[];if(e.totalLines>=t.minTotalLines&&n.push(`${e.totalLines} total component line(s)`),e.templateLines>=t.minTemplateLines&&n.push(`${e.templateLines} template line(s)`),e.scriptLines>=t.minScriptLines&&n.push(`${e.scriptLines} script line(s)`),e.styleLines>=t.minStyleLines&&n.push(`${e.styleLines} style line(s)`),n.length===0)return null;let i=nL(e),r=iL(e,t,i),o=rL(e.file),s=oL(i,o);return{file:e.file,totalLines:e.totalLines,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,dominantPressure:i,pressureKinds:r,contextKind:o,recommendationKind:s,recommendation:sL(s,o),reasons:n,loc:e.totalLines}}function nL(e){let t=[{axis:"template",lines:e.templateLines},{axis:"script",lines:e.scriptLines-e.externalScriptLines},{axis:"style",lines:e.styleLines},{axis:"external-script",lines:e.externalScriptLines},{axis:"custom-block",lines:e.customBlockLines}];return t.sort((n,i)=>i.lines-n.lines),t[0]?.lines?t[0].axis:"total"}function iL(e,t,n){let i=[];return e.totalLines>=t.minTotalLines&&(i.push("total"),n!=="total"&&i.push(n)),e.templateLines>=t.minTemplateLines&&i.push("template"),e.scriptLines>=t.minScriptLines&&i.push("script"),e.styleLines>=t.minStyleLines&&i.push("style"),(e.externalScriptLines>=t.minScriptLines||n==="external-script")&&i.push("external-script"),e.customBlockLines>0&&n==="custom-block"&&i.push("custom-block"),[...new Set(i.length>0?i:[n])]}function rL(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>aL.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function oL(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function sL(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var aL=new Set(["landing","page","pages","route","routes","view","views"]);function Ua(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=ne(e,r),c=gL(a,o,s);if(c.length===0)return[];let l=cL(c);return l.length<2?[]:fL(dL(l,n,i),i)}function cL(e){let t=lL(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function lL(e){let{nodeFreq:t,tailFreq:n}=uL(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,c]of t)c>i&&o.add(a);for(let[a,c]of n)c>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function uL(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function dL(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=mL(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function mL(e,t,n){if(!pL(e.filtered,t.filtered))return null;let{distance:i,ops:r}=hL(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||r.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:bL(e.original,t.original),commonSuffix:yL(e.original,t.original)}}function pL(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function fL(e,t){let n=[];for(let i of e)if(n.some(o=>Tm(i.chainA,o.chainA)&&Tm(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function gL(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;_m(e,o,[o],new Set([o]),t,n,i,500)}return i}function _m(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=r&&s.push([...n]);return}let l=!1;for(let u of c)if(!i.has(u)&&(i.add(u),n.push(u),_m(e,u,n,i,r,o,s,a),n.pop(),i.delete(u),l=!0,s.length>=a))return;!l&&n.length>=r&&s.push([...n])}function hL(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let c=0;c<=n;c++)r[c][0]=c;for(let c=0;c<=i;c++)r[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=i;l++)e[c-1]===t[l-1]?r[c][l]=r[c-1][l-1]:r[c][l]=1+Math.min(r[c-1][l],r[c][l-1],r[c-1][l-1]);let o=[],s=n,a=i;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:r[n][i],ops:o}}function bL(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function yL(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function Tm(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function We(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Ue(t,e.scanLimit),i=e.prepare?.(n)??void 0,r=[];for(let o of n){let s=e.evaluate(o,i);s&&r.push(s)}return e.orderResults&&r.sort(e.orderResults),typeof e.limit=="number"?r.slice(0,e.limit):r}function yn(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new T(e);return We({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>SL(c,l.get(c.symbolId)??[],r),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function SL(e,t,n){let i=new Set(t.map(l=>l.symbol));if(i.size<n)return null;let r=kL(i,t),o=wL(i,r);if(o.length<2)return null;let s=LL(o,r);if(s.length===0)return null;let a=y(e.symbol),c=xL(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e),totalCallees:i.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function xL(e,t,n,i){let r=Math.max(...i.map(c=>c.callees.length)),o=Math.max(...i.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=CL(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:r>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function CL(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let i=vL(e);return RL.has(i)?`caller verb suggests orchestration: ${i}`:null}function vL(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var RL=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function kL(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function wL(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}i.push(o)}return i}function LL(e,t){return e.filter(n=>n.size>=3).map(n=>DL(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function DL(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let c of a)i.add(c);let r=0;for(let a of e)for(let c of n.get(a)??[])i.has(c)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(y),isolation:s}}import{posix as ai}from"path";var IL=U("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function Sn(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function ko(e,t,n){let i=[],r=0,o=0,s=F(t.symbol);for(let a of n)NL(e,a,t.relativePath,s)?r++:Wa(e,a,s)?o++:i.push(a);return{realConsumers:i,barrelConsumers:r,importOnlyConsumers:o}}function Wa(e,t,n){if(!n)return!1;let i=W(t);if(!i)return!1;let r=IL.get(e,t,()=>PL(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function PL(e,t,n){let i=new Set,r=new Set,o=me(e,t);if(!o)return{importedLeaves:i,usedLeaves:r};let s=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(c,l)=>{let u=l||s.has(c.type);(c.type==="identifier"||c.type==="type_identifier"||c.type==="property_identifier"||c.type==="field_identifier")&&(u?i.add(c.text):r.add(c.text));for(let d of c.children)a(d,u)};return a(o.rootNode,!1),{importedLeaves:i,usedLeaves:r}}function NL(e,t,n,i){if(!i)return!1;let r=_e(e,t);if(r.length===0)return!1;let o=Mi(e,t);if(o.length===0)return!1;let s=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=0;for(let l=0;l<r.length;l++){if(!a.test(r[l]??""))continue;if(c++,!o.find(d=>d.startLine<=l&&l<=d.endLine))return!1}return c>0}var EL=20,TL=1,_L=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),FL=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),$L=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function Ja(e,t={}){let n=Ka(t.limit,EL),i=Ka(t.minConsumers,TL),r=new T(e),o=r.fileDependencyGraph(t.scope),s=tD(j(e,{includeIgnored:!1})),a=rD(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?AL(e,r,t.target):ML(e,t.scope,t.scanLimit)).map(u=>OL(r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(eD).slice(0,n)}function AL(e,t,n){let i=HL(e,n);if(i)return[Om(i)];let r=B(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[VL(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:y(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function ML(e,t,n){let i=j(e,{scope:t,includeIgnored:!1}),r=Ka(n,i.length);return i.slice(0,r).map(o=>Om(o))}function OL(e,t,n,i,r,o){let s=n.definition?jL(e,n.definition,i.semantic):BL(t,n.unit.file),a=n.definition?s.length>0?"exact":"none":s.length>0?"file-level":"none",c=n.unit.file,l=Ze(ai.dirname(c)),u=UL(s),d=qL(l),m=Ya([...Fm(l),...u?Fm(u):[]]),p=WL(n.unit,l,u,s),h=GL(p,n.unit,l,u,s,r,o),g=XL(n.unit,a,u,s,l,h.whyNoSuggestedHome),b=YL(n.unit,l,u,s,h.suggestedHome,h.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:n.unit,candidatePath:c,currentDirectory:l,directoryAncestry:d,consumerFiles:s,consumerCoverage:a,nearestCommonOwner:u,boundaryMarkers:m,recommendedTier:p,suggestedHome:h.suggestedHome,destinationConfidence:h.confidence,whyNoSuggestedHome:h.whyNoSuggestedHome,counterevidence:g,reasons:b,recommendation:ZL(p,h.suggestedHome,a)}}function jL(e,t,n){let i=Sn(e,[t],{semantic:n!==!1,sourceFallback:!0});return qm(i.get(t.symbolId)??[])}function BL(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return qm(n)}function HL(e,t){let n=Xa(t),i=j(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function VL(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:y(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function Om(e){return{unit:{kind:"file",file:e,shortName:ai.basename(e)}}}function qL(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:Qa(r)})}return t}function Fm(e){return e==="."?[]:jm(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Qa(e){return Ya(jm(e).map(({marker:t})=>t))}function jm(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=_L.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function UL(e){if(e.length===0)return null;let t=e.map(i=>Ze(ai.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function WL(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":Am(n,"package")?"package-level-shared":Am(n,"app")?"app-level-shared":Mm(n,["feature","domain","module"])||Mm(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function GL(e,t,n,i,r,o,s){let a=zL(e,i);if(a)return Vt(a);let c=nD(t.file),l=KL(e,n,c,r,s);if(l)return l;let u=i;if(Ze(n)===Ze(u))return Vt(`${n} is already the nearest common owner for its consumers.`);let d=JL(u,n,c,s);return d||QL(u,n,c,o,s)}function zL(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function KL(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?Ga(o):Vt("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=Ze(ai.dirname(i[0])),s=Vm(t,n,o,r);return s?Vt(s):Ga(o)}return null}function JL(e,t,n,i){return sD(e)?Bm(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function QL(e,t,n,i,r){if(e===".")return Vt("The nearest common owner is the repository root.");let o=`${e}/shared`,s=Bm(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:Vt(`${o} does not exist in the indexed project.`)}function Bm(e,t,n,i,r){if(!Hm(e,n))return Vt(r);let o=Vm(t,n,e,i);return o?Vt(o):Ga(e)}function Ga(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Vt(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function XL(e,t,n,i,r,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),i.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function YL(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function ZL(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function eD(e,t){return $m(t)-$m(e)||e.candidatePath.localeCompare(t.candidatePath)}function $m(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t-=8),e.recommendedTier==="no-exact-consumers"&&(t-=12),t}function tD(e){let t=new Set(["."]);for(let n of e){let i=Ze(ai.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=Ze(ai.dirname(i))}return t}function nD(e){let t=za(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function Hm(e,t){let n=Ze(e),i=Ze(t);return i==="."||n===i||n.startsWith(`${i}/`)}function iD(e,t,n){let i=za(e),r=za(t);return(Hm(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function Vm(e,t,n,i){return Ze(e)===Ze(n)||!iD(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function rD(...e){let t=new Set($L);for(let n of e)for(let i of n??[]){let r=oD(i);r&&t.add(r)}return t}function oD(e){let t=e.trim().toLowerCase();return t===""?null:t}function Am(e,t){return Qa(e).includes(t)}function Mm(e,t){let n=Qa(e);return t.some(i=>n.includes(i))}function sD(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?FL.has(n):!1}function Xa(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function Ze(e){let t=Xa(e);return t===""?".":t}function za(e){let t=Xa(e);return t==="."?[]:t.split("/").filter(Boolean)}function Ka(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function qm(e){return Ya([...e]).sort((t,n)=>t.localeCompare(n))}function Ya(e){return[...new Set(e)]}function nr(e,t,n={}){let{maxDepth:i=5,scope:r}=n,o=B(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=i&&l.length!==0;u++){let d=[];for(let m of l)for(let p of aD(e,m,r)){let h=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(h))continue;c.add(h),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&d.push(p.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function aD(e,t,n){let i=qe(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),r=new Set(i.map(l=>l.file)),o=[];for(let l of cD(e,t,n)){if(r.has(l))continue;let u=G(e,l),d=u.length>0?je(u,u[0].startLine):null;o.push({symbol:d?.symbol??l,file:l})}let s=[...i,...o],a=[],c=new Set;for(let l of s){let u=zn(e,l.symbol);if(!u){let m=`${l.file}|${l.symbol}`;if(c.has(m))continue;c.add(m),a.push({symbolId:null,symbol:l.symbol,shortName:y(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!lD(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function cD(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
461
+ `)}function Em(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),i=Lw(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!i.has(s));return new Set(o)}function Lw(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function Dw(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Yi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(e){let t=[];if(e.filePattern){let n=e.profiles.find(i=>i.file.includes(e.filePattern));if(!n)return[];for(let i of e.profiles){if(i.file===n.file)continue;let r=e.compare(n,i);r&&t.push(r)}}else{let n=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let i=0;i<e.profiles.length;i+=1){for(let r=i+1;r<e.profiles.length;r+=1){let o=e.compare(e.profiles[i],e.profiles[r]);o&&t.push(o)}if(t.length>n)break}}return t.sort(e.sort??((n,i)=>i.similarity-n.similarity)),t.slice(0,e.limit)}function Ga(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=Iw(e,{scope:r,minDeps:s});return at({profiles:a,limit:i,filePattern:o,overrunFactor:5,compare:(l,u)=>Nw(l,u,n,c)})}function Iw(e,t){let{scope:n,minDeps:i}=t,r=ne(e,n),{universalDeps:o,distinctiveDeps:s}=Pw(r),a=[];for(let[c,l]of r)l.size>=i&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function Pw(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function Nw(e,t,n,i){let r=new Set;for(let l of e.deps)t.deps.has(l)&&r.add(l);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of r)i.has(l)&&o++;if(o<2)return null;let s=Ht(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...r],uniqueToA:a,uniqueToB:c}}function Ro(e){let t=[],n=[],i=[];for(let l of e.primitiveGroups)l.values.length!==0&&Tm(l.bucket,n,i).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)Ew(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,Tm(l.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function ko(e,t){if(e.size===0||t.size===0)return 0;let i=Le(e,t).size/Math.min(e.size,t.size);return Math.max(Ht(e,t),i)}function V(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Ce(e){return[...e].sort()}function Ew(e,t,n,i,r,o){let s=[],a=[];for(let c of e)Tw(c,i).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&r.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function Tw(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Tm(e,t,n){return e==="generic"?t:n}function fn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Hn(e,{scope:o,minJsxTokens:i,scanLimit:s}).filter(l=>l.kind==="component").map(l=>({file:l.file,component:l.name,tokens:l.jsxTokens,profile:l}));return at({profiles:c,limit:r,filePattern:a,compare:(l,u)=>_w(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function _w(e,t,n){let i=Le(e.tokens,t.tokens);if(i.size<6||!$w(i))return null;let r=Ht(e.tokens,t.tokens);return r<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,sharedTokens:Ce(i),sharedComponents:V(i,"component:"),sharedNativeTags:V(i,"native:"),sharedProps:V(i,"prop:"),sharedEvents:V(i,"event:"),sharedBindings:V(i,"binding:"),uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function $w(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return t>=1||n>=4}function gn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Hn(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(l=>({file:l.file,component:l.name,tokens:l.behaviorTokens,profile:l}));return at({profiles:c,limit:r,filePattern:a,compare:(l,u)=>Fw(l,u,n,i),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function Fw(e,t,n,i){let r=Le(e.tokens,t.tokens);if(r.size<i||!Ow(r))return null;let o=ko(e.tokens,t.tokens);if(o<n)return null;let s=V(r,"hook:"),a=V(r,"react-hook:"),c=V(r,"effect:"),l=V(r,"state:"),u=V(r,"request:"),d=V(r,"handler:"),m=V(r,"handler-verb:"),p=Aw({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:Ce(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),reason:jw({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function Aw(e){return Ro({genericWords:Bw,stripPrefixes:Hw,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:Mw})}function Mw(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function Ow(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?i+=1:u.startsWith("request:")?r+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+i+r+o+c;return r>=1&&l>=4||t>=1&&(r>=1||s>=1||o>=2)&&l>=5||s>=1&&o>=2&&(i>=1||n>=2)&&l>=5}function jw(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var Bw=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),Hw=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function er(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return Hn(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>Vw(d,{minComponentLines:n,minFileLines:i,minJsxTokens:r,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function Vw(e,t){let n=[];e.loc>=t.minComponentLines&&n.push(`${e.loc} component line(s)`);let i=Math.max(80,Math.floor(t.minComponentLines/2));if(e.fileLines>=t.minFileLines&&e.loc>=i&&n.push(`${e.fileLines} file line(s)`),e.jsxTokens.size>=t.minJsxTokens&&n.push(`${e.jsxTokens.size} JSX structure token(s)`),e.behaviorTokens.size>=t.minBehaviorTokens&&n.push(`${e.behaviorTokens.size} behavior token(s)`),n.length===0)return null;let r=qw(e),o=Uw(e,t,r),s=Ww(e),a=Gw(r,o,s);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:zw(a,s),reasons:n,loc:e.loc}}function qw(e){let t=[{axis:"component",value:e.loc},{axis:"file",value:e.fileLines},{axis:"jsx-structure",value:e.jsxTokens.size*3},{axis:"hook-behavior",value:e.behaviorTokens.size*4}];return t.sort((n,i)=>i.value-n.value),t[0]?.axis??"component"}function Uw(e,t,n){let i=[];e.loc>=t.minComponentLines&&i.push("component");let r=Math.max(80,Math.floor(t.minComponentLines/2));return e.fileLines>=t.minFileLines&&e.loc>=r&&i.push("file"),e.jsxTokens.size>=t.minJsxTokens&&i.push("jsx-structure"),e.behaviorTokens.size>=t.minBehaviorTokens&&i.push("hook-behavior"),[...new Set(i.length>0?i:[n])]}function Ww(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(l=>l.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),r=`${i} ${e.name}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map(l=>l.toLowerCase()),o=n.findIndex(l=>Jw.has(l)),s=o>=0&&n.slice(o+1).some(l=>Kw.has(l)),a=_m(i)||_m(e.name);return/(?:Page|Route|Screen|View)$/.test(i)||/(?:Page|Route|Screen|View)$/.test(e.name)||r.some(l=>Qw.has(l))||o>=0&&!s&&!a?"route-page":"component"}function _m(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&$m.has(t.at(-1))?!0:[...$m].some(n=>e.endsWith(Xw(n)))}function Gw(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function zw(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var Kw=new Set(["component","components","panel","panels","partial","partials"]),$m=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),Jw=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),Qw=new Set(["landing","page","route","screen","view"]);function Xw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function hn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Yw(e,{scope:o,minTokens:i,scanLimit:s});return at({profiles:c,limit:r,filePattern:a,compare:(l,u)=>eL(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Yw(e,t){return Bn(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:Zw(n)}))}function Zw(e){return e.totalLines}function eL(e,t,n){let i=Le(e.tokens,t.tokens);if(i.size<6||!tL(i))return null;let r=Ht(e.tokens,t.tokens);return r<n?null:{fileA:e.file,fileB:t.file,similarity:r,sharedTokens:Ce(i),sharedComponents:V(i,"component:"),sharedProps:V(i,"prop:"),sharedEvents:V(i,"event:"),sharedDirectives:V(i,"directive:"),sharedSlots:V(i,"slot:"),sharedIdentifiers:V(i,"id:"),uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function tL(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return t>=1||n>=3}function bn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Bn(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(l=>({file:l.file,tokens:l.behaviorTokens,profile:l}));return at({profiles:c,limit:r,filePattern:a,compare:(l,u)=>nL(l,u,n,i),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function nL(e,t,n,i){let r=Le(e.tokens,t.tokens);if(r.size<i||!oL(r))return null;let o=ko(e.tokens,t.tokens);if(o<n)return null;let s=V(r,"composable:"),a=V(r,"store:"),c=V(r,"reactivity:"),l=V(r,"lifecycle:"),u=V(r,"request:"),d=V(r,"function:"),m=V(r,"function-verb:"),p=V(r,"template-binding:"),h=V(r,"template-event:"),g=iL({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:h});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:Ce(r),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:h,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Ce(ge(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ce(ge(t.tokens,e.tokens)).slice(0,25),reason:sL({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function iL(e){return Ro({genericWords:aL,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:rL})}function rL(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function oL(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?i+=1:u.startsWith("lifecycle:")?r+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+i+r+o+a;return i>=1&&l>=4||r>=1&&o>=2&&l>=4||c>=2&&(i>=1||o>=2)&&l>=5||o>=2&&s>=1&&l>=4}function sL(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var aL=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function tr(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return Bn(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>cL(d,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function cL(e,t){let n=[];if(e.totalLines>=t.minTotalLines&&n.push(`${e.totalLines} total component line(s)`),e.templateLines>=t.minTemplateLines&&n.push(`${e.templateLines} template line(s)`),e.scriptLines>=t.minScriptLines&&n.push(`${e.scriptLines} script line(s)`),e.styleLines>=t.minStyleLines&&n.push(`${e.styleLines} style line(s)`),n.length===0)return null;let i=lL(e),r=uL(e,t,i),o=dL(e.file),s=mL(i,o);return{file:e.file,totalLines:e.totalLines,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,dominantPressure:i,pressureKinds:r,contextKind:o,recommendationKind:s,recommendation:pL(s,o),reasons:n,loc:e.totalLines}}function lL(e){let t=[{axis:"template",lines:e.templateLines},{axis:"script",lines:e.scriptLines-e.externalScriptLines},{axis:"style",lines:e.styleLines},{axis:"external-script",lines:e.externalScriptLines},{axis:"custom-block",lines:e.customBlockLines}];return t.sort((n,i)=>i.lines-n.lines),t[0]?.lines?t[0].axis:"total"}function uL(e,t,n){let i=[];return e.totalLines>=t.minTotalLines&&(i.push("total"),n!=="total"&&i.push(n)),e.templateLines>=t.minTemplateLines&&i.push("template"),e.scriptLines>=t.minScriptLines&&i.push("script"),e.styleLines>=t.minStyleLines&&i.push("style"),(e.externalScriptLines>=t.minScriptLines||n==="external-script")&&i.push("external-script"),e.customBlockLines>0&&n==="custom-block"&&i.push("custom-block"),[...new Set(i.length>0?i:[n])]}function dL(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>fL.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function mL(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function pL(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var fL=new Set(["landing","page","pages","route","routes","view","views"]);function za(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=ne(e,r),c=vL(a,o,s);if(c.length===0)return[];let l=gL(c);return l.length<2?[]:CL(yL(l,n,i),i)}function gL(e){let t=hL(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function hL(e){let{nodeFreq:t,tailFreq:n}=bL(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,c]of t)c>i&&o.add(a);for(let[a,c]of n)c>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function bL(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function yL(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=SL(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function SL(e,t,n){if(!xL(e.filtered,t.filtered))return null;let{distance:i,ops:r}=RL(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||r.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:kL(e.original,t.original),commonSuffix:wL(e.original,t.original)}}function xL(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function CL(e,t){let n=[];for(let i of e)if(n.some(o=>Fm(i.chainA,o.chainA)&&Fm(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function vL(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;Am(e,o,[o],new Set([o]),t,n,i,500)}return i}function Am(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=r&&s.push([...n]);return}let l=!1;for(let u of c)if(!i.has(u)&&(i.add(u),n.push(u),Am(e,u,n,i,r,o,s,a),n.pop(),i.delete(u),l=!0,s.length>=a))return;!l&&n.length>=r&&s.push([...n])}function RL(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let c=0;c<=n;c++)r[c][0]=c;for(let c=0;c<=i;c++)r[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=i;l++)e[c-1]===t[l-1]?r[c][l]=r[c-1][l-1]:r[c][l]=1+Math.min(r[c-1][l],r[c][l-1],r[c-1][l-1]);let o=[],s=n,a=i;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:r[n][i],ops:o}}function kL(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function wL(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function Fm(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function We(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Ue(t,e.scanLimit),i=e.prepare?.(n)??void 0,r=[];for(let o of n){let s=e.evaluate(o,i);s&&r.push(s)}return e.orderResults&&r.sort(e.orderResults),typeof e.limit=="number"?r.slice(0,e.limit):r}function yn(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new T(e);return We({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>LL(c,l.get(c.symbolId)??[],r),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function LL(e,t,n){let i=new Set(t.map(l=>l.symbol));if(i.size<n)return null;let r=EL(i,t),o=TL(i,r);if(o.length<2)return null;let s=_L(o,r);if(s.length===0)return null;let a=y(e.symbol),c=DL(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e),totalCallees:i.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function DL(e,t,n,i){let r=Math.max(...i.map(c=>c.callees.length)),o=Math.max(...i.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=IL(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:r>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function IL(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let i=PL(e);return NL.has(i)?`caller verb suggests orchestration: ${i}`:null}function PL(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var NL=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function EL(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function TL(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}i.push(o)}return i}function _L(e,t){return e.filter(n=>n.size>=3).map(n=>$L(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function $L(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let c of a)i.add(c);let r=0;for(let a of e)for(let c of n.get(a)??[])i.has(c)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(y),isolation:s}}import{posix as ai}from"path";var FL=U("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function Sn(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function wo(e,t,n){let i=[],r=0,o=0,s=$(t.symbol);for(let a of n)ML(e,a,t.relativePath,s)?r++:Ka(e,a,s)?o++:i.push(a);return{realConsumers:i,barrelConsumers:r,importOnlyConsumers:o}}function Ka(e,t,n){if(!n)return!1;let i=W(t);if(!i)return!1;let r=FL.get(e,t,()=>AL(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function AL(e,t,n){let i=new Set,r=new Set,o=me(e,t);if(!o)return{importedLeaves:i,usedLeaves:r};let s=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(c,l)=>{let u=l||s.has(c.type);(c.type==="identifier"||c.type==="type_identifier"||c.type==="property_identifier"||c.type==="field_identifier")&&(u?i.add(c.text):r.add(c.text));for(let d of c.children)a(d,u)};return a(o.rootNode,!1),{importedLeaves:i,usedLeaves:r}}function ML(e,t,n,i){if(!i)return!1;let r=_e(e,t);if(r.length===0)return!1;let o=Mi(e,t);if(o.length===0)return!1;let s=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=0;for(let l=0;l<r.length;l++){if(!a.test(r[l]??""))continue;if(c++,!o.find(d=>d.startLine<=l&&l<=d.endLine))return!1}return c>0}var OL=20,jL=1,BL=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),HL=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),VL=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function Ya(e,t={}){let n=Xa(t.limit,OL),i=Xa(t.minConsumers,jL),r=new T(e),o=r.fileDependencyGraph(t.scope),s=cD(j(e,{includeIgnored:!1})),a=dD(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?qL(e,r,t.target):UL(e,t.scope,t.scanLimit)).map(u=>WL(r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(aD).slice(0,n)}function qL(e,t,n){let i=KL(e,n);if(i)return[Hm(i)];let r=B(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[JL(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:y(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function UL(e,t,n){let i=j(e,{scope:t,includeIgnored:!1}),r=Xa(n,i.length);return i.slice(0,r).map(o=>Hm(o))}function WL(e,t,n,i,r,o){let s=n.definition?GL(e,n.definition,i.semantic):zL(t,n.unit.file),a=n.definition?s.length>0?"exact":"none":s.length>0?"file-level":"none",c=n.unit.file,l=Ye(ai.dirname(c)),u=XL(s),d=QL(l),m=tc([...Mm(l),...u?Mm(u):[]]),p=YL(n.unit,l,u,s),h=ZL(p,n.unit,l,u,s,r,o),g=rD(n.unit,a,u,s,l,h.whyNoSuggestedHome),b=oD(n.unit,l,u,s,h.suggestedHome,h.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:n.unit,candidatePath:c,currentDirectory:l,directoryAncestry:d,consumerFiles:s,consumerCoverage:a,nearestCommonOwner:u,boundaryMarkers:m,recommendedTier:p,suggestedHome:h.suggestedHome,destinationConfidence:h.confidence,whyNoSuggestedHome:h.whyNoSuggestedHome,counterevidence:g,reasons:b,recommendation:sD(p,h.suggestedHome,a)}}function GL(e,t,n){let i=Sn(e,[t],{semantic:n!==!1,sourceFallback:!0});return Gm(i.get(t.symbolId)??[])}function zL(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return Gm(n)}function KL(e,t){let n=ec(t),i=j(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function JL(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:y(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function Hm(e){return{unit:{kind:"file",file:e,shortName:ai.basename(e)}}}function QL(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:Za(r)})}return t}function Mm(e){return e==="."?[]:Vm(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Za(e){return tc(Vm(e).map(({marker:t})=>t))}function Vm(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=BL.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function XL(e){if(e.length===0)return null;let t=e.map(i=>Ye(ai.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function YL(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":jm(n,"package")?"package-level-shared":jm(n,"app")?"app-level-shared":Bm(n,["feature","domain","module"])||Bm(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function ZL(e,t,n,i,r,o,s){let a=eD(e,i);if(a)return Vt(a);let c=lD(t.file),l=tD(e,n,c,r,s);if(l)return l;let u=i;if(Ye(n)===Ye(u))return Vt(`${n} is already the nearest common owner for its consumers.`);let d=nD(u,n,c,s);return d||iD(u,n,c,o,s)}function eD(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function tD(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?Ja(o):Vt("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=Ye(ai.dirname(i[0])),s=Wm(t,n,o,r);return s?Vt(s):Ja(o)}return null}function nD(e,t,n,i){return pD(e)?qm(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function iD(e,t,n,i,r){if(e===".")return Vt("The nearest common owner is the repository root.");let o=`${e}/shared`,s=qm(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:Vt(`${o} does not exist in the indexed project.`)}function qm(e,t,n,i,r){if(!Um(e,n))return Vt(r);let o=Wm(t,n,e,i);return o?Vt(o):Ja(e)}function Ja(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Vt(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function rD(e,t,n,i,r,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),i.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function oD(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function sD(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function aD(e,t){return Om(t)-Om(e)||e.candidatePath.localeCompare(t.candidatePath)}function Om(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t-=8),e.recommendedTier==="no-exact-consumers"&&(t-=12),t}function cD(e){let t=new Set(["."]);for(let n of e){let i=Ye(ai.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=Ye(ai.dirname(i))}return t}function lD(e){let t=Qa(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function Um(e,t){let n=Ye(e),i=Ye(t);return i==="."||n===i||n.startsWith(`${i}/`)}function uD(e,t,n){let i=Qa(e),r=Qa(t);return(Um(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function Wm(e,t,n,i){return Ye(e)===Ye(n)||!uD(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function dD(...e){let t=new Set(VL);for(let n of e)for(let i of n??[]){let r=mD(i);r&&t.add(r)}return t}function mD(e){let t=e.trim().toLowerCase();return t===""?null:t}function jm(e,t){return Za(e).includes(t)}function Bm(e,t){let n=Za(e);return t.some(i=>n.includes(i))}function pD(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?HL.has(n):!1}function ec(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function Ye(e){let t=ec(e);return t===""?".":t}function Qa(e){let t=ec(e);return t==="."?[]:t.split("/").filter(Boolean)}function Xa(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Gm(e){return tc([...e]).sort((t,n)=>t.localeCompare(n))}function tc(e){return[...new Set(e)]}function nr(e,t,n={}){let{maxDepth:i=5,scope:r}=n,o=B(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=i&&l.length!==0;u++){let d=[];for(let m of l)for(let p of fD(e,m,r)){let h=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(h))continue;c.add(h),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&d.push(p.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function fD(e,t,n){let i=qe(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),r=new Set(i.map(l=>l.file)),o=[];for(let l of gD(e,t,n)){if(r.has(l))continue;let u=G(e,l),d=u.length>0?je(u,u[0].startLine):null;o.push({symbol:d?.symbol??l,file:l})}let s=[...i,...o],a=[],c=new Set;for(let l of s){let u=zn(e,l.symbol);if(!u){let m=`${l.file}|${l.symbol}`;if(c.has(m))continue;c.add(m),a.push({symbolId:null,symbol:l.symbol,shortName:y(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!hD(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function gD(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
462
462
  FROM mentions m
463
463
  JOIN chunks c ON m.chunk_id = c.id
464
464
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -466,47 +466,47 @@ ${m}`,l+=1+m.length,u+=$i(m),i+=m.length+1}let d=EC(c);d&&n.push({...d,start:a,e
466
466
  AND m.role != 1
467
467
  AND c.document_id != ?
468
468
  ${e.pathExclusionsFor("consumer_d")}
469
- ${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function lD(e){let t=Z(e);return t==="method"||t==="type"||e.endsWith("().")}function ir(e,t,n={}){let i=Ie(e,t);if(!i)return null;let r=uD(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=dD(e,r.relative_path),c=n.semantic===!1?new Map:ri(e,a);for(let l of a){let u=mD(e,r,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:y(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:pD(u)})}return{file:r.relative_path,symbols:o,totalExternalConsumers:s}}function uD(e,t){return e.get(`SELECT id, relative_path FROM documents
469
+ ${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function hD(e){let t=Z(e);return t==="method"||t==="type"||e.endsWith("().")}function ir(e,t,n={}){let i=Ie(e,t);if(!i)return null;let r=bD(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=yD(e,r.relative_path),c=n.semantic===!1?new Map:ri(e,a);for(let l of a){let u=SD(e,r,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:y(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:xD(u)})}return{file:r.relative_path,symbols:o,totalExternalConsumers:s}}function bD(e,t){return e.get(`SELECT id, relative_path FROM documents
470
470
  WHERE relative_path = ?
471
471
  ${e.pathExclusionsFor("documents")}
472
- LIMIT 1`,t)??null}function dD(e,t){return new T(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function mD(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
472
+ LIMIT 1`,t)??null}function yD(e,t){return new T(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function SD(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
473
473
  FROM mentions m
474
474
  JOIN chunks c ON m.chunk_id = c.id
475
475
  JOIN documents consumer_d ON consumer_d.id = c.document_id
476
476
  WHERE m.symbol_id = ?
477
477
  AND m.role != 1
478
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function pD(e){return e>10?"high":e>0?"medium":"low"}function wo(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new T(e),a=fD(e,n,i,o),c=new Za;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(Um(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=r&&d.length>0;g++){let b=s.calleeMap(d,{semantic:!1}),S=new Set;for(let I of d)for(let L of b.get(I.symbolId)??[])m.has(L.symbol)||S.add(L.symbol);let x=[];for(let I of S){m.add(I);let L=Wm(e,I);if(!L||e.isIgnored(L.relativePath)||we(e,L.relativePath)||ie(e,L.symbol,L.relativePath)||s.fileKind(L.relativePath)==="test"||s.hasSuppressionComment(L))continue;let C=hD(e,L,c);C.removable?x.push(gD(L,"cascade")):C.blockingFiles.length>0&&u.push({shortName:y(L.symbol),file:L.relativePath,blockingFiles:C.blockingFiles.slice(0,3)})}if(x.length===0)break;for(let I of x)c.add(I);l.push(Um(e,g,x,c)),d=x.map(I=>I.definition).filter(I=>I!==null)}let p=l.reduce((g,b)=>g+b.loc,0),h=l.reduce((g,b)=>g+b.entries.length,0);return{batches:l,totalSymbols:h,totalLoc:p,blocked:u}}function fD(e,t,n,i){let r=Rt(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(we(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:Wm(e,s.symbol)}));return o}function gD(e,t){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function Wm(e,t){let n=e.get(`SELECT d.relative_path
478
+ AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function xD(e){return e>10?"high":e>0?"medium":"low"}function Lo(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new T(e),a=CD(e,n,i,o),c=new nc;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(zm(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=r&&d.length>0;g++){let b=s.calleeMap(d,{semantic:!1}),S=new Set;for(let I of d)for(let L of b.get(I.symbolId)??[])m.has(L.symbol)||S.add(L.symbol);let x=[];for(let I of S){m.add(I);let L=Km(e,I);if(!L||e.isIgnored(L.relativePath)||we(e,L.relativePath)||ie(e,L.symbol,L.relativePath)||s.fileKind(L.relativePath)==="test"||s.hasSuppressionComment(L))continue;let C=RD(e,L,c);C.removable?x.push(vD(L,"cascade")):C.blockingFiles.length>0&&u.push({shortName:y(L.symbol),file:L.relativePath,blockingFiles:C.blockingFiles.slice(0,3)})}if(x.length===0)break;for(let I of x)c.add(I);l.push(zm(e,g,x,c)),d=x.map(I=>I.definition).filter(I=>I!==null)}let p=l.reduce((g,b)=>g+b.loc,0),h=l.reduce((g,b)=>g+b.entries.length,0);return{batches:l,totalSymbols:h,totalLoc:p,blocked:u}}function CD(e,t,n,i){let r=Rt(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(we(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:Km(e,s.symbol)}));return o}function vD(e,t){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function Km(e,t){let n=e.get(`SELECT d.relative_path
479
479
  FROM global_symbols gs
480
480
  JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
481
481
  JOIN documents d ON d.id = der.document_id
482
482
  WHERE gs.symbol = ?
483
- LIMIT 1`,t);return n?G(e,n.relative_path).find(i=>i.symbol===t)??null:null}function hD(e,t,n){let i=dn(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function Um(e,t,n,i){let r=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let c=G(e,a);c.length>0&&c.every(l=>i.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...c})=>c),loc:r.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var Za=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{createHash as DN}from"crypto";import{existsSync as Ep}from"fs";import{execFileSync as bD}from"child_process";var zm=2e3,Km=50,yD=8,SD=3,xD=2160*60*60,CD=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,vD=3,RD=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,kD=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function ec(e){let t=Y(e,{clearGroups:["whole-project"]});return(n,i)=>{let r=LD(n.config.projectRoot);if(!r)return null;let o=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return o&&o.head===r?o.value:(t.invalidate(n),t.get(n,()=>({head:r,value:i(n.config.projectRoot,r)})).value)}}var wD=ec("git-commit-history");function qt(e){return wD(e,DD)}function LD(e){try{return Lo(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Lo(e,t){return bD("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function DD(e,t){let n;try{n=Lo(e,["log","--no-merges","--name-only","-n",String(zm),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let i=[],r=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
483
+ LIMIT 1`,t);return n?G(e,n.relative_path).find(i=>i.symbol===t)??null:null}function RD(e,t,n){let i=dn(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function zm(e,t,n,i){let r=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let c=G(e,a);c.length>0&&c.every(l=>i.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...c})=>c),loc:r.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var nc=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{createHash as $N}from"crypto";import{existsSync as $p}from"fs";import{execFileSync as kD}from"child_process";var Qm=2e3,Xm=50,wD=8,LD=3,DD=2160*60*60,ID=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,PD=3,ND=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,ED=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function ic(e){let t=Y(e,{clearGroups:["whole-project"]});return(n,i)=>{let r=_D(n.config.projectRoot);if(!r)return null;let o=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return o&&o.head===r?o.value:(t.invalidate(n),t.get(n,()=>({head:r,value:i(n.config.projectRoot,r)})).value)}}var TD=ic("git-commit-history");function qt(e){return TD(e,$D)}function _D(e){try{return Do(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Do(e,t){return kD("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function $D(e,t){let n;try{n=Do(e,["log","--no-merges","--name-only","-n",String(Qm),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let i=[],r=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
484
484
  `),a=s>=0?o.slice(0,s):o,[c,l,u]=a.split("\0");if(!c||!l)continue;let d=s>=0?o.slice(s+1).split(`
485
- `).map(m=>m.trim()).filter(m=>m!==""):[];if(d.length>Km){r+=1;continue}i.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:d})}return{head:t,commits:i,skippedBulkCommits:r}}function ID(e){return CD.test(e.subject)}function Do(e){let t=qt(e);if(!t)return null;let n=new Map;for(let i of t.commits){let r=ID(i);for(let o of i.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,r&&(s.fixChanges+=1),i.timestamp>s.lastChangedAt&&(s.lastChangedAt=i.timestamp),n.set(o,s)}}return n}function Jm(e){let t=qt(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(i=>i.files.length).filter(i=>i>0).sort((i,r)=>i-r);return n.length===0?null:{medianFilesPerCommit:Gm(n,.5),p90FilesPerCommit:Gm(n,.9),commitsAnalyzed:n.length}}function Gm(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var PD=ec("git-tracked-files");function tc(e){return PD(e,t=>{try{let n=Lo(t,["ls-files"]);return new Set(n.split(`
486
- `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}})}var ND=ec("git-file-adds");function Qm(e){return ND(e,t=>ED(t))}function ED(e){let t;try{t=Lo(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(zm),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,i=-1;for(let r of t.split("")){if(r.trim()==="")continue;i+=1;let o=r.indexOf(`
485
+ `).map(m=>m.trim()).filter(m=>m!==""):[];if(d.length>Xm){r+=1;continue}i.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:d})}return{head:t,commits:i,skippedBulkCommits:r}}function FD(e){return ID.test(e.subject)}function Io(e){let t=qt(e);if(!t)return null;let n=new Map;for(let i of t.commits){let r=FD(i);for(let o of i.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,r&&(s.fixChanges+=1),i.timestamp>s.lastChangedAt&&(s.lastChangedAt=i.timestamp),n.set(o,s)}}return n}function Ym(e){let t=qt(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(i=>i.files.length).filter(i=>i>0).sort((i,r)=>i-r);return n.length===0?null:{medianFilesPerCommit:Jm(n,.5),p90FilesPerCommit:Jm(n,.9),commitsAnalyzed:n.length}}function Jm(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var AD=ic("git-tracked-files");function rc(e){return AD(e,t=>{try{let n=Do(t,["ls-files"]);return new Set(n.split(`
486
+ `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}})}var MD=ic("git-file-adds");function Zm(e){return MD(e,t=>OD(t))}function OD(e){let t;try{t=Do(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(Qm),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,i=-1;for(let r of t.split("")){if(r.trim()==="")continue;i+=1;let o=r.indexOf(`
487
487
  `),s=o>=0?r.slice(0,o):r,[,a]=s.split("\0"),c=Number(a)||0;if(!(o<0))for(let l of r.slice(o+1).split(`
488
- `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:i,addedAt:c})}}return n}function Xm(e,t={}){let n=qt(e);return n?Zm(n,t):null}function Ym(e,t,n={}){let i=qt(e);return i?t.size===0?[]:Zm(i,n,t):null}function Zm(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=Km}=t,s=new Map,a=new Map,c=0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;d.timestamp>c&&(c=d.timestamp);let p=TD(m),h=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(h)for(let g=0;g<m.length;g++)for(let b=g+1;b<m.length;b++){if(n&&!n.has(m[g])&&!n.has(m[b]))continue;let S=`${m[g]}\0${m[b]}`,x=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};x.together+=1,p?x.broadTogether+=1:x.focusedTogether+=1,d.timestamp>x.lastTogetherAt&&(x.lastTogetherAt=d.timestamp),x.timestamps.push(d.timestamp),x.subjects.push(d.subject),a.set(S,x)}}let l=[],u=c-xD;for(let[d,m]of a){let p=m.together;if(p<i)continue;let[h,g]=d.split("\0"),b=s.get(h)??p,S=s.get(g)??p,x=Math.max(p/b,p/S);if(x<r)continue;let I=m.broadTogether/p,L=m.timestamps.filter(C=>C>=u).length;l.push({fileA:h,fileB:g,together:p,confidence:x,changesA:b,changesB:S,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:I,lastTogetherAt:m.lastTogetherAt,recentTogether:L,commitScope:FD(m.broadTogether,p),recency:L>0?"recent":"stale",subjectContext:$D(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function TD(e){return e.length>=yD?!0:_D(e).size>=SD}function _D(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function FD(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function $D(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<vD&&i.push(r);for(let o of AD(r))t.add(o);for(let o of r.match(RD)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function AD(e){let t=new Set,n=kD.exec(e)?.[1]?.toLowerCase();return n&&t.add(MD(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function MD(e){return e==="feat"?"feature":e}import{existsSync as OD}from"fs";import{join as jD}from"path";function ic(e){return nc.test(e)}var nc=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function xn(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=qt(e),c=t!==void 0,l=Xm(e,{minTogether:c?Math.min(i,2):i,minConfidence:c?0:r,maxFilesPerCommit:s});if(!a||!l)return{available:!1,commitsAnalyzed:0,findings:[]};let u=ne(e),d=ip(e),m=sc(e,u,d),p=n.includeLinked===!0||c,h=[];for(let g of l){if(nc.test(g.fileA)||nc.test(g.fileB)||!ep(e,g.fileA)||!ep(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(K(g.fileA)==="test"||K(g.fileB)==="test"||BD(g.fileA,g.fileB)))continue;let b=m(g.fileA,g.fileB);if(!p&&b)continue;let S=rc(g.fileA,g.fileB),x=oc(g,S,b);if(h.push({...g,structurallyLinked:b,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,...x?{declaredCouplingSuggestion:x}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:a.commits.length,findings:h}}function ep(e,t){return OD(jD(e.config.projectRoot,t))}function rc(e,t){let n=tp(e),i=tp(t),r=[],o=c=>{r.includes(c)||r.push(c)},s=(c,l)=>n.tags.has(c)&&i.tags.has(l)||n.tags.has(l)&&i.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=XD(n.tokens,i.tokens).filter(c=>!JD.has(c));return np(e,t)||a.length>=2?(o(np(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function oc(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!KD.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${YD(i)}`,files:i,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function sc(e,t=ne(e),n=ip(e)){return(i,r)=>HD(t,n,i,r)}function BD(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function ip(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function HD(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var VD=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,qD=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,UD=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,WD=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,GD=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,zD=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,KD=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),JD=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function tp(e){let t=e.replace(/\\/g,"/"),n=new Set;return VD.test(t)&&n.add("doc"),qD.test(t)&&n.add("config"),UD.test(t)&&n.add("schema"),WD.test(t)&&n.add("script"),GD.test(t)&&n.add("model"),zD.test(t)&&n.add("view"),K(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:QD(t)}}function np(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function QD(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function XD(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function YD(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as lt}from"child_process";import{existsSync as ZD,readFileSync as eI}from"fs";import{basename as rp}from"path";function Io(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var ac="Unable to compute git diff.";function ci(e,t={}){let n=t.plan??ut(e,t);return n.note?tI(n.note,n.changedFileLines):n.changedFiles.length===0?nI(n.changedFileLines):No(n.changedFiles,[Po(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function ut(e,t={}){let{base:n="HEAD"}=t;try{let i=iI(e.config.projectRoot,n),r=lI(e,i),o=uI(e,rI(e.config.projectRoot,n));return{changedFileLines:i,changedFiles:r,changedRanges:o,renamedFiles:oI(e.config.projectRoot,n,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:ac}}}function Po(e,t,n,i=[]){let r=new T(e),o=new Set(n),s=Io(i),a=[],c=new Map,l=t.flatMap(h=>r.definitionsForFile(h)).filter(yI).filter(h=>mI(h,s)).sort((h,g)=>h.relativePath.localeCompare(g.relativePath)||h.startLine-g.startLine),u=l.map(h=>h.symbolId),d=gI(e,u),m=hI(e,u,n),p=ri(e,l.filter(h=>d.get(h.symbolId)===0));for(let h of l)fI(e,h,o,a,c,p.get(h.symbolId)??new Set,d.get(h.symbolId)??0,m.get(h.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([h,g])=>({file:h,symbols:[...g].sort()}))}}function No(e,t){let n=new Map,i=t.flatMap(o=>o.changedSymbols);for(let o of t)for(let s of o.consumerEntries){let a=n.get(s.file);a||(a=new Set,n.set(s.file,a));for(let c of s.symbols)a.add(c)}let r=bI(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:r,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:r.length}}}function tI(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function nI(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function iI(e,t){let n=lt("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=lt("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=lt("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,i,r].flatMap(o=>o.split(`
489
- `)).map(o=>o.trim()).filter(o=>o.length>0))]}function rI(e,t){let n=lt("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=lt("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return up([...ap(n),...ap(i)])}function rr(e,t,n){try{return lt("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function oI(e,t,n){if(n.length===0)return[];let i=new Map,r=new Set;for(let s of aI(e,t))n.includes(s.to)&&(i.set(s.to,s),r.add(s.from));let o=sI(e,t);if(o.length===0)return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to));for(let s of n){if(i.has(s)||!ZD(`${e}/${s}`))continue;let a=o.filter(u=>!r.has(u)).filter(u=>rp(u)===rp(s));if(a.length===0)continue;let c=eI(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:cI(rr(e,t,u)??"",c)})).sort((u,d)=>d.similarity-u.similarity)[0];l&&l.similarity>=.45&&(i.set(s,l),r.add(l.from))}return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to))}function sI(e,t){let n=lt("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=lt("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...sp(n),...sp(i)])]}function aI(e,t){let n=lt("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=lt("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.split(`
488
+ `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:i,addedAt:c})}}return n}function ep(e,t={}){let n=qt(e);return n?np(n,t):null}function tp(e,t,n={}){let i=qt(e);return i?t.size===0?[]:np(i,n,t):null}function np(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=Xm}=t,s=new Map,a=new Map,c=0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;d.timestamp>c&&(c=d.timestamp);let p=jD(m),h=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(h)for(let g=0;g<m.length;g++)for(let b=g+1;b<m.length;b++){if(n&&!n.has(m[g])&&!n.has(m[b]))continue;let S=`${m[g]}\0${m[b]}`,x=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};x.together+=1,p?x.broadTogether+=1:x.focusedTogether+=1,d.timestamp>x.lastTogetherAt&&(x.lastTogetherAt=d.timestamp),x.timestamps.push(d.timestamp),x.subjects.push(d.subject),a.set(S,x)}}let l=[],u=c-DD;for(let[d,m]of a){let p=m.together;if(p<i)continue;let[h,g]=d.split("\0"),b=s.get(h)??p,S=s.get(g)??p,x=Math.max(p/b,p/S);if(x<r)continue;let I=m.broadTogether/p,L=m.timestamps.filter(C=>C>=u).length;l.push({fileA:h,fileB:g,together:p,confidence:x,changesA:b,changesB:S,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:I,lastTogetherAt:m.lastTogetherAt,recentTogether:L,commitScope:HD(m.broadTogether,p),recency:L>0?"recent":"stale",subjectContext:VD(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function jD(e){return e.length>=wD?!0:BD(e).size>=LD}function BD(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function HD(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function VD(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<PD&&i.push(r);for(let o of qD(r))t.add(o);for(let o of r.match(ND)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function qD(e){let t=new Set,n=ED.exec(e)?.[1]?.toLowerCase();return n&&t.add(UD(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function UD(e){return e==="feat"?"feature":e}import{existsSync as WD}from"fs";import{join as GD}from"path";function sc(e){return oc.test(e)}var oc=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function xn(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=qt(e),c=t!==void 0,l=ep(e,{minTogether:c?Math.min(i,2):i,minConfidence:c?0:r,maxFilesPerCommit:s});if(!a||!l)return{available:!1,commitsAnalyzed:0,findings:[]};let u=ne(e),d=sp(e),m=lc(e,u,d),p=n.includeLinked===!0||c,h=[];for(let g of l){if(oc.test(g.fileA)||oc.test(g.fileB)||!ip(e,g.fileA)||!ip(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(K(g.fileA)==="test"||K(g.fileB)==="test"||zD(g.fileA,g.fileB)))continue;let b=m(g.fileA,g.fileB);if(!p&&b)continue;let S=ac(g.fileA,g.fileB),x=cc(g,S,b);if(h.push({...g,structurallyLinked:b,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,...x?{declaredCouplingSuggestion:x}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:a.commits.length,findings:h}}function ip(e,t){return WD(GD(e.config.projectRoot,t))}function ac(e,t){let n=rp(e),i=rp(t),r=[],o=c=>{r.includes(c)||r.push(c)},s=(c,l)=>n.tags.has(c)&&i.tags.has(l)||n.tags.has(l)&&i.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=rI(n.tokens,i.tokens).filter(c=>!nI.has(c));return op(e,t)||a.length>=2?(o(op(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function cc(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!tI.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${oI(i)}`,files:i,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function lc(e,t=ne(e),n=sp(e)){return(i,r)=>KD(t,n,i,r)}function zD(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function sp(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function KD(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var JD=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,QD=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,XD=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,YD=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,ZD=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,eI=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,tI=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),nI=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function rp(e){let t=e.replace(/\\/g,"/"),n=new Set;return JD.test(t)&&n.add("doc"),QD.test(t)&&n.add("config"),XD.test(t)&&n.add("schema"),YD.test(t)&&n.add("script"),ZD.test(t)&&n.add("model"),eI.test(t)&&n.add("view"),K(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:iI(t)}}function op(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function iI(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function rI(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function oI(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as ct}from"child_process";import{existsSync as sI,readFileSync as aI}from"fs";import{basename as ap}from"path";function Po(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var uc="Unable to compute git diff.";function ci(e,t={}){let n=t.plan??lt(e,t);return n.note?cI(n.note,n.changedFileLines):n.changedFiles.length===0?lI(n.changedFileLines):Eo(n.changedFiles,[No(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function lt(e,t={}){let{base:n="HEAD"}=t;try{let i=uI(e.config.projectRoot,n),r=hI(e,i),o=bI(e,dI(e.config.projectRoot,n));return{changedFileLines:i,changedFiles:r,changedRanges:o,renamedFiles:mI(e.config.projectRoot,n,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:uc}}}function No(e,t,n,i=[]){let r=new T(e),o=new Set(n),s=Po(i),a=[],c=new Map,l=t.flatMap(h=>r.definitionsForFile(h)).filter(wI).filter(h=>SI(h,s)).sort((h,g)=>h.relativePath.localeCompare(g.relativePath)||h.startLine-g.startLine),u=l.map(h=>h.symbolId),d=vI(e,u),m=RI(e,u,n),p=ri(e,l.filter(h=>d.get(h.symbolId)===0));for(let h of l)CI(e,h,o,a,c,p.get(h.symbolId)??new Set,d.get(h.symbolId)??0,m.get(h.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([h,g])=>({file:h,symbols:[...g].sort()}))}}function Eo(e,t){let n=new Map,i=t.flatMap(o=>o.changedSymbols);for(let o of t)for(let s of o.consumerEntries){let a=n.get(s.file);a||(a=new Set,n.set(s.file,a));for(let c of s.symbols)a.add(c)}let r=kI(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:r,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:r.length}}}function cI(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function lI(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function uI(e,t){let n=ct("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=ct("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=ct("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,i,r].flatMap(o=>o.split(`
489
+ `)).map(o=>o.trim()).filter(o=>o.length>0))]}function dI(e,t){let n=ct("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=ct("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return pp([...up(n),...up(i)])}function rr(e,t,n){try{return ct("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function mI(e,t,n){if(n.length===0)return[];let i=new Map,r=new Set;for(let s of fI(e,t))n.includes(s.to)&&(i.set(s.to,s),r.add(s.from));let o=pI(e,t);if(o.length===0)return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to));for(let s of n){if(i.has(s)||!sI(`${e}/${s}`))continue;let a=o.filter(u=>!r.has(u)).filter(u=>ap(u)===ap(s));if(a.length===0)continue;let c=aI(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:gI(rr(e,t,u)??"",c)})).sort((u,d)=>d.similarity-u.similarity)[0];l&&l.similarity>=.45&&(i.set(s,l),r.add(l.from))}return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to))}function pI(e,t){let n=ct("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=ct("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...lp(n),...lp(i)])]}function fI(e,t){let n=ct("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=ct("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.split(`
490
490
  `),...i.split(`
491
- `)].map(r=>r.trim()).filter(r=>r.startsWith("R")).map(r=>r.split(" ")).filter(r=>r.length>=3).map(([r,o,s])=>({from:o,to:s,similarity:Number(r.slice(1))/100}))}function cI(e,t){let n=new Set(op(e)),i=new Set(op(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function op(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function sp(e){return e.split(`
492
- `).map(t=>t.trim()).filter(t=>t.length>0)}function lI(e,t){let n=lp(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function uI(e,t){let n=lp(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return up(i)}function lp(e){let t=e.all(`SELECT relative_path FROM documents
493
- ORDER BY id`).map(i=>i.relative_path),n=new Map(t.map(i=>[i,i]));return i=>{let r=i.replace(/\\/g,"/"),o=n.get(r);return o||(t.find(s=>s.endsWith(r))??null)}}function ap(e){let t=[],n=null;for(let i of e.split(`
494
- `)){if(i.startsWith("+++ ")){n=dI(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function dI(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function up(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function mI(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>pI(e.startLine,e.endLine,i.startLine,i.endLine))}function pI(e,t,n,i){return e<=i&&n<=t}function fI(e,t,n,i,r,o,s,a){let c=Math.max(s,o.size);if(!SI(t,c))return;let l=y(t.symbol);i.push({symbol:t.symbol,shortName:l,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let u of a)cp(e,n,r,u,l);for(let u of o)cp(e,n,r,u,l)}function gI(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
491
+ `)].map(r=>r.trim()).filter(r=>r.startsWith("R")).map(r=>r.split(" ")).filter(r=>r.length>=3).map(([r,o,s])=>({from:o,to:s,similarity:Number(r.slice(1))/100}))}function gI(e,t){let n=new Set(cp(e)),i=new Set(cp(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function cp(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function lp(e){return e.split(`
492
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function hI(e,t){let n=mp(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function bI(e,t){let n=mp(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return pp(i)}function mp(e){let t=e.all(`SELECT relative_path FROM documents
493
+ ORDER BY id`).map(i=>i.relative_path),n=new Map(t.map(i=>[i,i]));return i=>{let r=i.replace(/\\/g,"/"),o=n.get(r);return o||(t.find(s=>s.endsWith(r))??null)}}function up(e){let t=[],n=null;for(let i of e.split(`
494
+ `)){if(i.startsWith("+++ ")){n=yI(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function yI(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function pp(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function SI(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>xI(e.startLine,e.endLine,i.startLine,i.endLine))}function xI(e,t,n,i){return e<=i&&n<=t}function CI(e,t,n,i,r,o,s,a){let c=Math.max(s,o.size);if(!LI(t,c))return;let l=y(t.symbol);i.push({symbol:t.symbol,shortName:l,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let u of a)dp(e,n,r,u,l);for(let u of o)dp(e,n,r,u,l)}function vI(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
495
495
  FROM mentions m
496
496
  JOIN chunks c ON m.chunk_id = c.id
497
497
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
498
498
  AND m.role != 1
499
- GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function hI(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
499
+ GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function RI(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
500
500
  FROM mentions m
501
501
  JOIN chunks c ON m.chunk_id = c.id
502
502
  JOIN documents ref_d ON c.document_id = ref_d.id
503
503
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
504
504
  AND m.role != 1
505
505
  AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
506
- ${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function cp(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function bI(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function yI(e){return!(Tt(e.symbol)||e.parentTypeName!==null&&!xe(e.symbol))}function SI(e,t){return xe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function dp(e){let[t,n]=Eo(e,":"),i=t||"unknown",r=(o={})=>{let s=o.actionTier??xI(i);return{sourceAnalyzer:i,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${i} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??CI(s,i),file:o.file}};if(!n)return r({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(i)){let[o,s]=Eo(n,":");return r({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${i} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(i==="cycle"){let o=n.split(">").filter(Boolean);return r({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(i==="similar"){let o=n.split("|").filter(Boolean);return r({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(i==="drift"){let[o,s]=Eo(n,":"),[a,c]=Eo(s,":");return r({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return r({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function xI(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function CI(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function Eo(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as DI,readFileSync as fp}from"fs";function Fo(e,t){let n=vI(e,t)??RI(e,t)??kI(e,t)??wI(e,t);return LI(e,n,t)}function vI(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=cc(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if(cc(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function cc(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function RI(e,t){if(!To(e[t]??""))return null;let n=t;for(;n>0&&To(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&To(e[i]??"");)i+=1;return{start:n,end:i}}function To(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function kI(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(_o(o)!==null)break;if(lc(o)!==null)return null;n-=1}if(n<0)return null;let i=_o(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=_o(o);if(s!==null){if(s<=i)break;r+=1;continue}if(lc(o)!==null)break;r+=1}return{start:n,end:r}}function _o(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function wI(e,t){let n=e[t]??"";if(pp(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&mp(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&mp(e[r]??"");)r+=1;return{start:i,end:r}}function mp(e){return lc(e)===null}function lc(e){return e.trim().length===0?"blank":pp(e)?"heading":cc(e)?"fence":To(e)?"table":_o(e)!==null?"list":null}function pp(e){return/^#{1,6}\s+/.test(e.trim())}function LI(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
507
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Cn(e,t){return t.filter(n=>e.includes(n))}var li={classifyCitation:II,citationContexts:PI,citationKindLabel:EI,citationRemediation:TI,referenceTargets:_I};function II(e){let t=e.join(`
508
- `).toLowerCase(),n=[],i=Cn(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=Cn(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Cn(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function PI(e,t,n){let i;try{i=fp(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let r=n.flatMap(NI),o=[];for(let s=0;s<i.length;s+=1){let a=i[s]??"";r.some(c=>a.includes(c))&&o.push(Fo(i,s))}return o}function NI(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function EI(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function TI(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function _I(e,t,n){let i=Io(n),r=new Set;for(let o of t)FI(e,o,i.get(o)??[])&&r.add(o);return r}function FI(e,t,n){if(n.length===0)return!1;if(!$I.test(t))return!0;let i=`${e.config.projectRoot}/${t}`;if(!DI(i))return!0;let r=fp(i,"utf-8").split(/\r?\n/),o=AI(r);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((r[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var $I=/\.(?:[cm]?[jt]sx?)$/i;function AI(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&MI(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function MI(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as gp,readFileSync as dc}from"fs";import{join as sr}from"path";var or=/\.(?:md|mdx|rst|txt)$/i;function OI(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var jI=3,hp=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function mc(e,t={}){let{doc:n,limit:i=20,minCoupling:r=jI}=t,o=VI(e);if(!o)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let s=[];for(let a of o.docFiles){if(n!==void 0&&!a.includes(n)||n===void 0&&!yp(e,a)||n!==void 0&&!gp(sr(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=BI(e,a),u=new Map,{resolved:d,broken:m,citations:p}=xp(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory),h=new Map(p.map(b=>[b.file,b.contexts]));for(let b of d){if(b===a||or.test(b))continue;let S=(o.changeTimes.get(b)??[]).filter(x=>x>c).length;S!==0&&u.set(b,{file:b,evidence:"reference",coChanges:0,changesSinceDocUpdate:S,...uc("reference",l),citationContexts:h.get(b)})}for(let[b,S]of o.coupling.get(a)??[]){if(S<r||!o.tracked.has(b))continue;let x=(o.changeTimes.get(b)??[]).filter(L=>L>c).length;if(x===0)continue;let I=u.get(b);I?(I.evidence="both",I.coChanges=S,Object.assign(I,uc("both",l))):u.set(b,{file:b,evidence:"co-change",coChanges:S,changesSinceDocUpdate:x,...uc("co-change",l)})}if(u.size===0&&m.length===0)continue;let g=[...u.values()].sort((b,S)=>S.changesSinceDocUpdate-b.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:g.reduce((b,S)=>b+S.changesSinceDocUpdate,0)+m.length*10,subjects:g.slice(0,8),brokenReferences:m})}return s.sort((a,c)=>c.staleness-a.staleness),{available:!0,commitsAnalyzed:o.historyCommitCount,docsScanned:o.docFiles.length,findings:s.slice(0,i)}}function BI(e,t){let n;try{n=dc(sr(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let i=`${t}
509
- ${n}`.toLowerCase(),r=Cn(i,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=Cn(i,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function uc(e,t){return{actionTier:HI(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function HI(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function VI(e){let t=qt(e);if(!t)return null;let n=tc(e)??new Set,i=new Map,r=new Map,o=new Set;for(let s of t.commits){let a=[...new Set(s.files)],c=a.filter(u=>or.test(u)),l=a.filter(u=>!or.test(u));for(let u of a){o.add(u);let d=i.get(u)??[];d.push(s.timestamp),i.set(u,d)}for(let u of c){let d=r.get(u);d||(d=new Map,r.set(u,d));for(let m of l)d.set(m,(d.get(m)??0)+1)}}return{changeTimes:i,coupling:r,docFiles:[...n].filter(s=>or.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:Sp(n)}}function bp(e,t){let n=tc(e)??new Set,i=Sp(n),r=[];for(let o of n){if(!yp(e,o))continue;let{resolved:s,citations:a}=xp(e,o,n,i,new Set),c=[...s].filter(l=>t.has(l));if(c.length>0){let l=c.sort(),u=new Set(l),d=a.filter(m=>u.has(m.file));r.push({doc:o,cited:l,citations:d,citedClaims:pc(d.flatMap(m=>m.contexts)).slice(0,3)})}}return r}function yp(e,t){return or.test(t)&&!OI(t)&&gp(sr(e.config.projectRoot,t))}function Sp(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function xp(e,t,n,i,r){let o=new Set,s=new Set,a=WI(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=qI(e,t,a),l=new Map,u=(d,m)=>{let p=c.get(m);if(!p||p.length===0)return;let h=l.get(d)??[];h.push(...p),l.set(d,pc(h).slice(0,3))};for(let d of a){if(n.has(d)){o.add(d),u(d,d);continue}let m=i.get(d);if(m&&m.length===1){o.add(m[0]),u(m[0],d);continue}m&&m.length>1||r.has(d)&&s.add(d)}return{resolved:o,broken:[...s],citations:[...l].map(([d,m])=>({file:d,contexts:m}))}}function qI(e,t,n){let i;try{i=dc(sr(e.config.projectRoot,t),"utf-8").split(/\r?\n/)}catch{return new Map}let r=new Set(n),o=new Map;for(let s=0;s<i.length;s+=1){let a=i[s]??"";for(let c of a.matchAll(hp)){let l=c[0].replace(/^\.?\//,"");if(!r.has(l))continue;let u=Fo(i,s);if(u.length===0)continue;let d=o.get(l)??[];d.push(u),o.set(l,pc(d).slice(0,3))}}return o}function pc(e){let t=[];for(let n of new Set(e))t.some(i=>UI(i,n))||t.push(n);return t}function UI(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}function WI(e,t){let n;try{n=dc(sr(e.config.projectRoot,t),"utf-8")}catch{return null}let i=Qt(e,t,n),r=Fr(e,"doc-path-tokens",t,i);if(r!==null)try{return JSON.parse(r)}catch{}let o=[...new Set([...n.matchAll(hp)].map(s=>s[0].replace(/^\.?\//,"")))];return $r(e,"doc-path-tokens",t,i,JSON.stringify(o)),o}import{existsSync as rN,readFileSync as oN,writeFileSync as sN}from"fs";import{isAbsolute as aN,join as cN}from"path";var ae={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0,semantic:!1},isolated:{minLoc:3,semantic:!1},similar:{minSimilarity:.6,limit:50,minCallees:4,semantic:!1},extract:{minLoc:15,minCallees:5,limit:50,semantic:!1},wrappers:{maxLoc:15,limit:50,semantic:!1},passthroughs:{maxLoc:15,limit:50,semantic:!1},stale:{minLoc:3,limit:50,semantic:!1},drift:{semantic:!1}};import ar from"path";function vn(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function fc(e,t){if(e===t)return"ok";let n=$o(e),i=$o(t);return n&&i?GI(n,i)?"ok":"violation":zI(e,t)}function Cp(e,t){let n=$o(vn(e)),i=$o(vn(t));return!!n&&!!i}function $o(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function GI(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","semantic","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["domain","queries","reindex","resolution","semantic","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function zI(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function Rn(e,t){let{scope:n,minDeviation:i=5}=t??{},r=t?.semantic!==!1,s=new T(e).fileDependencyGraph(n),a=eP(e,n);return XI([...KI(e,s,a,{semantic:r}),...JI(s),...QI(s,i)])}function KI(e,t,n,i){let r=[];for(let[o,s]of t){if(wt(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!wt(c)&&!a.has(c)){if(i.semantic&&sP(e,o,c)||aP(e,o,c)||cP(e,o,c)||oP(c)||uP(e,o,c)||lP(c))continue;r.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${o} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."})}}return r}function JI(e){let t=[],n=rP(e);for(let[i,r]of e){if(wt(i))continue;let o=vn(i);for(let s of r){if(wt(s))continue;let a=vn(s);if(o===a)continue;let c=fc(o,a),l=c?"explicit":"inferred";if((c??n.get(`${o}->${a}`))==="violation"){let d=l==="explicit"?"direct":"signal";t.push({file:i,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`,actionTier:d,policyBasis:l,evidenceReasons:[`dependency edge exists from ${i} to ${s}`,l==="explicit"?`explicit layer policy rejects ${o}/ -> ${a}/`:`rare cross-layer edge ${o}/ -> ${a}/ is inferred as a violation`],recommendation:l==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function QI(e,t){let n=[];for(let[i,r]of YI(e)){let o=r.filter(a=>!wt(a));if(o.length<t)continue;let s=ZI(e,o);for(let a of o)for(let c of e.get(a)??[])wt(c)||(s.get(c)??0)===1&&ar.dirname(c)!==i&&ar.dirname(c)!==ar.dirname(i)&&(Cp(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."}))}return n}function XI(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function YI(e){let t=new Map;for(let n of e.keys()){let i=ar.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function ZI(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])wt(r)||n.set(r,(n.get(r)??0)+1);return n}function eP(e,t){let n=new Map;return tP(e,n,t),iP(e,n),n}function tP(e,t,n){for(let i of nP(e,n))vp(e,t,i.from_file,i.to_file)}function nP(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
506
+ ${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function dp(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function kI(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function wI(e){return!(Tt(e.symbol)||e.parentTypeName!==null&&!xe(e.symbol))}function LI(e,t){return xe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function fp(e){let[t,n]=To(e,":"),i=t||"unknown",r=(o={})=>{let s=o.actionTier??DI(i);return{sourceAnalyzer:i,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${i} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??II(s,i),file:o.file}};if(!n)return r({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(i)){let[o,s]=To(n,":");return r({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${i} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(i==="cycle"){let o=n.split(">").filter(Boolean);return r({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(i==="similar"){let o=n.split("|").filter(Boolean);return r({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(i==="drift"){let[o,s]=To(n,":"),[a,c]=To(s,":");return r({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return r({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function DI(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function II(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function To(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as $I,readFileSync as bp}from"fs";function Fo(e,t){let n=PI(e,t)??NI(e,t)??EI(e,t)??TI(e,t);return _I(e,n,t)}function PI(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=dc(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if(dc(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function dc(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function NI(e,t){if(!_o(e[t]??""))return null;let n=t;for(;n>0&&_o(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&_o(e[i]??"");)i+=1;return{start:n,end:i}}function _o(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function EI(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if($o(o)!==null)break;if(mc(o)!==null)return null;n-=1}if(n<0)return null;let i=$o(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=$o(o);if(s!==null){if(s<=i)break;r+=1;continue}if(mc(o)!==null)break;r+=1}return{start:n,end:r}}function $o(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function TI(e,t){let n=e[t]??"";if(hp(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&gp(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&gp(e[r]??"");)r+=1;return{start:i,end:r}}function gp(e){return mc(e)===null}function mc(e){return e.trim().length===0?"blank":hp(e)?"heading":dc(e)?"fence":_o(e)?"table":$o(e)!==null?"list":null}function hp(e){return/^#{1,6}\s+/.test(e.trim())}function _I(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
507
+ `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Cn(e,t){return t.filter(n=>e.includes(n))}var li={classifyCitation:FI,citationContexts:AI,citationKindLabel:OI,citationRemediation:jI,referenceTargets:BI};function FI(e){let t=e.join(`
508
+ `).toLowerCase(),n=[],i=Cn(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=Cn(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Cn(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function AI(e,t,n){let i;try{i=bp(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let r=n.flatMap(MI),o=[];for(let s=0;s<i.length;s+=1){let a=i[s]??"";r.some(c=>a.includes(c))&&o.push(Fo(i,s))}return o}function MI(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function OI(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function jI(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function BI(e,t,n){let i=Po(n),r=new Set;for(let o of t)HI(e,o,i.get(o)??[])&&r.add(o);return r}function HI(e,t,n){if(n.length===0)return!1;if(!VI.test(t))return!0;let i=`${e.config.projectRoot}/${t}`;if(!$I(i))return!0;let r=bp(i,"utf-8").split(/\r?\n/),o=qI(r);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((r[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var VI=/\.(?:[cm]?[jt]sx?)$/i;function qI(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&UI(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function UI(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as yp,readFileSync as fc}from"fs";import{join as sr}from"path";var or=/\.(?:md|mdx|rst|txt)$/i;function WI(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var GI=3,Sp=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function gc(e,t={}){let{doc:n,limit:i=20,minCoupling:r=GI}=t,o=JI(e);if(!o)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let s=[];for(let a of o.docFiles){if(n!==void 0&&!a.includes(n)||n===void 0&&!Cp(e,a)||n!==void 0&&!yp(sr(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=zI(e,a),u=new Map,{resolved:d,broken:m,citations:p}=Rp(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory),h=new Map(p.map(b=>[b.file,b.contexts]));for(let b of d){if(b===a||or.test(b))continue;let S=(o.changeTimes.get(b)??[]).filter(x=>x>c).length;S!==0&&u.set(b,{file:b,evidence:"reference",coChanges:0,changesSinceDocUpdate:S,...pc("reference",l),citationContexts:h.get(b)})}for(let[b,S]of o.coupling.get(a)??[]){if(S<r||!o.tracked.has(b))continue;let x=(o.changeTimes.get(b)??[]).filter(L=>L>c).length;if(x===0)continue;let I=u.get(b);I?(I.evidence="both",I.coChanges=S,Object.assign(I,pc("both",l))):u.set(b,{file:b,evidence:"co-change",coChanges:S,changesSinceDocUpdate:x,...pc("co-change",l)})}if(u.size===0&&m.length===0)continue;let g=[...u.values()].sort((b,S)=>S.changesSinceDocUpdate-b.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:g.reduce((b,S)=>b+S.changesSinceDocUpdate,0)+m.length*10,subjects:g.slice(0,8),brokenReferences:m})}return s.sort((a,c)=>c.staleness-a.staleness),{available:!0,commitsAnalyzed:o.historyCommitCount,docsScanned:o.docFiles.length,findings:s.slice(0,i)}}function zI(e,t){let n;try{n=fc(sr(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let i=`${t}
509
+ ${n}`.toLowerCase(),r=Cn(i,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=Cn(i,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function pc(e,t){return{actionTier:KI(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function KI(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function JI(e){let t=qt(e);if(!t)return null;let n=rc(e)??new Set,i=new Map,r=new Map,o=new Set;for(let s of t.commits){let a=[...new Set(s.files)],c=a.filter(u=>or.test(u)),l=a.filter(u=>!or.test(u));for(let u of a){o.add(u);let d=i.get(u)??[];d.push(s.timestamp),i.set(u,d)}for(let u of c){let d=r.get(u);d||(d=new Map,r.set(u,d));for(let m of l)d.set(m,(d.get(m)??0)+1)}}return{changeTimes:i,coupling:r,docFiles:[...n].filter(s=>or.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:vp(n)}}function xp(e,t){let n=rc(e)??new Set,i=vp(n),r=[];for(let o of n){if(!Cp(e,o))continue;let{resolved:s,citations:a}=Rp(e,o,n,i,new Set),c=[...s].filter(l=>t.has(l));if(c.length>0){let l=c.sort(),u=new Set(l),d=a.filter(m=>u.has(m.file));r.push({doc:o,cited:l,citations:d,citedClaims:hc(d.flatMap(m=>m.contexts)).slice(0,3)})}}return r}function Cp(e,t){return or.test(t)&&!WI(t)&&yp(sr(e.config.projectRoot,t))}function vp(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function Rp(e,t,n,i,r){let o=new Set,s=new Set,a=YI(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=QI(e,t,a),l=new Map,u=(d,m)=>{let p=c.get(m);if(!p||p.length===0)return;let h=l.get(d)??[];h.push(...p),l.set(d,hc(h).slice(0,3))};for(let d of a){if(n.has(d)){o.add(d),u(d,d);continue}let m=i.get(d);if(m&&m.length===1){o.add(m[0]),u(m[0],d);continue}m&&m.length>1||r.has(d)&&s.add(d)}return{resolved:o,broken:[...s],citations:[...l].map(([d,m])=>({file:d,contexts:m}))}}function QI(e,t,n){let i;try{i=fc(sr(e.config.projectRoot,t),"utf-8").split(/\r?\n/)}catch{return new Map}let r=new Set(n),o=new Map;for(let s=0;s<i.length;s+=1){let a=i[s]??"";for(let c of a.matchAll(Sp)){let l=c[0].replace(/^\.?\//,"");if(!r.has(l))continue;let u=Fo(i,s);if(u.length===0)continue;let d=o.get(l)??[];d.push(u),o.set(l,hc(d).slice(0,3))}}return o}function hc(e){let t=[];for(let n of new Set(e))t.some(i=>XI(i,n))||t.push(n);return t}function XI(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}function YI(e,t){let n;try{n=fc(sr(e.config.projectRoot,t),"utf-8")}catch{return null}let i=Qt(e,t,n),r=Fr(e,"doc-path-tokens",t,i);if(r!==null)try{return JSON.parse(r)}catch{}let o=[...new Set([...n.matchAll(Sp)].map(s=>s[0].replace(/^\.?\//,"")))];return Ar(e,"doc-path-tokens",t,i,JSON.stringify(o)),o}import{existsSync as dN,readFileSync as mN,writeFileSync as pN}from"fs";import{isAbsolute as fN,join as gN}from"path";var ae={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0,semantic:!1},isolated:{minLoc:3,semantic:!1},similar:{minSimilarity:.6,limit:50,minCallees:4,semantic:!1},extract:{minLoc:15,minCallees:5,limit:50,semantic:!1},wrappers:{maxLoc:15,limit:50,semantic:!1},passthroughs:{maxLoc:15,limit:50,semantic:!1},stale:{minLoc:3,limit:50,semantic:!1},drift:{semantic:!1}};import ar from"path";function vn(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function bc(e,t){if(e===t)return"ok";let n=Ao(e),i=Ao(t);return n&&i?ZI(n,i)?"ok":"violation":eP(e,t)}function kp(e,t){let n=Ao(vn(e)),i=Ao(vn(t));return!!n&&!!i}function Ao(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function ZI(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","semantic","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["domain","queries","reindex","resolution","semantic","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function eP(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function Rn(e,t){let{scope:n,minDeviation:i=5}=t??{},r=t?.semantic!==!1,s=new T(e).fileDependencyGraph(n),a=aP(e,n);return rP([...tP(e,s,a,{semantic:r}),...nP(s),...iP(s,i)])}function tP(e,t,n,i){let r=[];for(let[o,s]of t){if(wt(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!wt(c)&&!a.has(c)){if(i.semantic&&pP(e,o,c)||fP(e,o,c)||gP(e,o,c)||mP(c)||bP(e,o,c)||hP(c))continue;r.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${o} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."})}}return r}function nP(e){let t=[],n=dP(e);for(let[i,r]of e){if(wt(i))continue;let o=vn(i);for(let s of r){if(wt(s))continue;let a=vn(s);if(o===a)continue;let c=bc(o,a),l=c?"explicit":"inferred";if((c??n.get(`${o}->${a}`))==="violation"){let d=l==="explicit"?"direct":"signal";t.push({file:i,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`,actionTier:d,policyBasis:l,evidenceReasons:[`dependency edge exists from ${i} to ${s}`,l==="explicit"?`explicit layer policy rejects ${o}/ -> ${a}/`:`rare cross-layer edge ${o}/ -> ${a}/ is inferred as a violation`],recommendation:l==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function iP(e,t){let n=[];for(let[i,r]of oP(e)){let o=r.filter(a=>!wt(a));if(o.length<t)continue;let s=sP(e,o);for(let a of o)for(let c of e.get(a)??[])wt(c)||(s.get(c)??0)===1&&ar.dirname(c)!==i&&ar.dirname(c)!==ar.dirname(i)&&(kp(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."}))}return n}function rP(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function oP(e){let t=new Map;for(let n of e.keys()){let i=ar.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function sP(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])wt(r)||n.set(r,(n.get(r)??0)+1);return n}function aP(e,t){let n=new Map;return cP(e,n,t),uP(e,n),n}function cP(e,t,n){for(let i of lP(e,n))wp(e,t,i.from_file,i.to_file)}function lP(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
510
510
  FROM mentions m
511
511
  JOIN chunks c ON m.chunk_id = c.id
512
512
  JOIN documents d1 ON c.document_id = d1.id
@@ -522,31 +522,31 @@ ${n}`.toLowerCase(),r=Cn(i,["historical note","historical record","history note"
522
522
  WHERE d1.id != d2.id
523
523
  AND m.role != 1
524
524
  ${e.pathExclusionsFor("d1","d2")}
525
- ${n}`)}function iP(e,t){new T(e).scanSourceReferences({paths:j(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||vp(e,t,i.sourceFile,i.target.relativePath))})}function vp(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function rP(e){let t=new Map;for(let[i,r]of e){if(wt(i))continue;let o=vn(i);for(let s of r){if(wt(s))continue;let a=vn(s);if(o===a||fc(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[i,r]of t)n.set(i,r<=2?"violation":"ok");return n}function oP(e){return e.includes("types")||e.endsWith(".d.ts")}function sP(e,t,n){let i=qi(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function aP(e,t,n){let i=fe(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function cP(e,t,n){let i=fe(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function lP(e){return e.endsWith(".vue")}function uP(e,t,n){let i=fe(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function wt(e){let t=K(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||dP(ar.basename(e)))}function dP(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as Rp,extname as kp}from"path";function Ao(e,t,n,i,r,o){let s=new Set;pP(e,t,n,i)&&s.add(r);for(let a of o)a.value&&mP(s,a.label,a.value);return[...s].slice(0,6)}function mP(e,t,n){let i=fP(n);t.endsWith("name")&&gP(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=hP.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function pP(e,t,n,i){if(n<=0)return!1;let r=_e(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(Li(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function fP(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function gP(e){return e.some(t=>bP.has(t))&&e.some(t=>yP.has(t))}var hP=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),bP=new Set(["can","has","is","should"]),yP=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function kn(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new T(e);return We({candidates:()=>IP(s,n,i),orderCandidates:yo,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>SP(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:r})}function SP(e,t,n){let i=DP(n);if(i.size!==1||!$s(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=xP(e,t,r),s=vP(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:y(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:q(t),forwardsTo:r.symbol,forwardsToShort:y(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:CP(a,o,s)}}function xP(e,t,n){return Ao(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:y(t.symbol)},{label:"callee name",value:y(n.symbol)},{label:"passthrough module",value:Rp(t.relativePath,kp(t.relativePath))},{label:"callee module",value:Rp(n.file,kp(n.file))}])}function CP(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let i=t.filter(wP);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function vP(e,t){return RP(e,t)?ei(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:ie(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function RP(e,t){let n=_e(e,t.relativePath);if(n.length===0)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
526
- `);return PP.test(i)?!0:kP(n,F(t.symbol))}function kP(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${LP(t)}\\b`);return e.some(i=>n.test(i))}function wP(e){return e.includes("public surface")}function LP(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DP(e){let t=e.some(i=>se(i.symbol))?e.filter(i=>se(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function IP(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}var PP=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function\b|(?:const|let|var)\b)/m;function wn(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new T(e),u=l.scopedDefinitions(n),d=VP(l,n),m={high:0,medium:1,low:2};return We({candidates:()=>NP(e,l,u,{minLoc:i,maxLoc:r}),orderCandidates:(p,h)=>q(h)-q(p)||p.relativePath.localeCompare(h.relativePath),scanLimit:a,prepare:p=>({consumerFileMap:EP(l,p,{semantic:c}),singletonBackedClassIds:AP(e,l,u,p,{semantic:c}),candidateIndex:TP(p)}),evaluate:(p,h)=>{if(h.singletonBackedClassIds.has(p.symbolId))return null;let g=_P(e,p,h.consumerFileMap,h.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!UP(g.definition,g.realConsumers.length,d))return null;let b=FP(e,g);return!s&&b.confidence==="low"?null:b},orderResults:(p,h)=>m[p.confidence]-m[h.confidence]||h.loc-p.loc||p.file.localeCompare(h.file)||p.startLine-h.startLine,limit:o})}function NP(e,t,n,i){return n.filter(r=>r.isTypeLike&&q(r)>=i.minLoc).filter(r=>q(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>K(r.relativePath)!=="test").filter(r=>!ie(e,r.symbol,r.relativePath)).filter(r=>!qP(r.symbol)).filter(r=>!t.hasSuppressionComment(r))}function EP(e,t,n){return Sn(e,t,{semantic:n.semantic})}function TP(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=F(n.symbol);r&&i.set(r,n)}return t}function _P(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=ko(e,t,o),l=WP(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function FP(e,t){let n=Dp(e,t.definition.relativePath,t.definition.startLine),i=Lp(t.definition.relativePath)?!0:GP(e,t.definition),{confidence:r,reason:o}=zP(t.realConsumers.length,n,i),s=$P(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:y(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:q(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function $P(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function AP(e,t,n,i,r){let o=OP(e,MP(n),i),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Sn(t,s,{semantic:r.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)BP(e,l,a)&&c.add(u);return c}function MP(e){let t=new Map;for(let n of e){let i=F(n.symbol);i&&t.set(wp(n.relativePath,i),n)}return t}function OP(e,t,n){let i=[];for(let r of n){let o=jP(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function jP(e,t,n){if(Dp(e,n.relativePath,n.startLine)!=="class")return null;let i=F(n.symbol);if(!i)return null;let r=HP(e,n.relativePath,i);return r?t.get(wp(n.relativePath,r))??null:null}function BP(e,t,n){let i=F(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Wa(e,o,i))}function wp(e,t){return`${e}\0${t}`}function HP(e,t,n){let i=M(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function VP(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function qP(e){let t=pe(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function Lp(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n.endsWith("-types")||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||n==="contracts"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e)||/(^|\/)contracts?(\/|\.)/.test(e))}function UP(e,t,n){return!(Lp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function WP(e,t,n,i){let r=Ms(e,t.relativePath),o=F(t.symbol);if(!o)return!1;let s=r.get(o);if(!s||s.size===0)return!1;let a=i.get(t.relativePath);if(!a)return!1;for(let c of s){let l=a.get(c);if(!l)continue;let u=n.get(l.symbolId);if(u){for(let d of u)if(d!==t.relativePath&&!e.isIgnored(d))return!0}}return!1}function Dp(e,t,n){let i=M(e,t);if(!i)return"other";let r=i.split(`
527
- `),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let l=(r[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function GP(e,t){let n=M(e,t.relativePath);if(!n)return!1;let i=F(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\b`),s=n.split(`
528
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function zP(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}import{basename as ui,extname as Mo}from"path";function Ln(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new T(e),a=tN(s.fileDependencyGraph(n));return We({candidates:()=>JP(s,n,i),orderCandidates:yo,scanLimit:o,prepare:c=>({callerFileMap:Sn(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>KP(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:r})}function KP(e,t,n,i){let r=QP(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=XP(e,n.symbolId,o);if(!s)return null;let a=YP(t,e,o,n.symbol,s);if(a&&Vn(a.symbol))return null;let{fanIn:c,source:l}=ZP(i.callerFileMap,i.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=iN(e,n,o,a);return{symbol:n.symbol,shortName:y(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:q(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?y(a.symbol):ui(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function JP(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function QP(e,t,n,i){let r=ui(n.relativePath,Mo(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>ui(s,Mo(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return ko(e,n,o).realConsumers}function XP(e,t,n){return e.get(`SELECT c.start_line, c.end_line
525
+ ${n}`)}function uP(e,t){new T(e).scanSourceReferences({paths:j(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||wp(e,t,i.sourceFile,i.target.relativePath))})}function wp(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function dP(e){let t=new Map;for(let[i,r]of e){if(wt(i))continue;let o=vn(i);for(let s of r){if(wt(s))continue;let a=vn(s);if(o===a||bc(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[i,r]of t)n.set(i,r<=2?"violation":"ok");return n}function mP(e){return e.includes("types")||e.endsWith(".d.ts")}function pP(e,t,n){let i=qi(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function fP(e,t,n){let i=fe(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function gP(e,t,n){let i=fe(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function hP(e){return e.endsWith(".vue")}function bP(e,t,n){let i=fe(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function wt(e){let t=K(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||yP(ar.basename(e)))}function yP(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as Lp,extname as Dp}from"path";function Mo(e,t,n,i,r,o){let s=new Set;xP(e,t,n,i)&&s.add(r);for(let a of o)a.value&&SP(s,a.label,a.value);return[...s].slice(0,6)}function SP(e,t,n){let i=CP(n);t.endsWith("name")&&vP(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=RP.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function xP(e,t,n,i){if(n<=0)return!1;let r=_e(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(Li(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function CP(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function vP(e){return e.some(t=>kP.has(t))&&e.some(t=>wP.has(t))}var RP=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),kP=new Set(["can","has","is","should"]),wP=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function kn(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new T(e);return We({candidates:()=>FP(s,n,i),orderCandidates:So,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>LP(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:r})}function LP(e,t,n){let i=$P(n);if(i.size!==1||!Os(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=DP(e,t,r),s=PP(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:y(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:q(t),forwardsTo:r.symbol,forwardsToShort:y(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:IP(a,o,s)}}function DP(e,t,n){return Mo(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:y(t.symbol)},{label:"callee name",value:y(n.symbol)},{label:"passthrough module",value:Lp(t.relativePath,Dp(t.relativePath))},{label:"callee module",value:Lp(n.file,Dp(n.file))}])}function IP(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let i=t.filter(TP);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function PP(e,t){return NP(e,t)?ei(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:ie(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function NP(e,t){let n=_e(e,t.relativePath);if(n.length===0)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
526
+ `);return AP.test(i)?!0:EP(n,$(t.symbol))}function EP(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${_P(t)}\\b`);return e.some(i=>n.test(i))}function TP(e){return e.includes("public surface")}function _P(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $P(e){let t=e.some(i=>se(i.symbol))?e.filter(i=>se(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function FP(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}var AP=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function\b|(?:const|let|var)\b)/m;function wn(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new T(e),u=l.scopedDefinitions(n),d=JP(l,n),m={high:0,medium:1,low:2};return We({candidates:()=>MP(e,l,u,{minLoc:i,maxLoc:r}),orderCandidates:(p,h)=>q(h)-q(p)||p.relativePath.localeCompare(h.relativePath),scanLimit:a,prepare:p=>({consumerFileMap:OP(l,p,{semantic:c}),singletonBackedClassIds:qP(e,l,u,p,{semantic:c}),candidateIndex:jP(p)}),evaluate:(p,h)=>{if(h.singletonBackedClassIds.has(p.symbolId))return null;let g=BP(e,p,h.consumerFileMap,h.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!XP(g.definition,g.realConsumers.length,d))return null;let b=HP(e,g);return!s&&b.confidence==="low"?null:b},orderResults:(p,h)=>m[p.confidence]-m[h.confidence]||h.loc-p.loc||p.file.localeCompare(h.file)||p.startLine-h.startLine,limit:o})}function MP(e,t,n,i){return n.filter(r=>r.isTypeLike&&q(r)>=i.minLoc).filter(r=>q(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>K(r.relativePath)!=="test").filter(r=>!ie(e,r.symbol,r.relativePath)).filter(r=>!QP(r.symbol)).filter(r=>!t.hasSuppressionComment(r))}function OP(e,t,n){return Sn(e,t,{semantic:n.semantic})}function jP(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=$(n.symbol);r&&i.set(r,n)}return t}function BP(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=wo(e,t,o),l=YP(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function HP(e,t){let n=Np(e,t.definition.relativePath,t.definition.startLine),i=Pp(t.definition.relativePath)?!0:ZP(e,t.definition),{confidence:r,reason:o}=eN(t.realConsumers.length,n,i),s=VP(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:y(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:q(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function VP(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function qP(e,t,n,i,r){let o=WP(e,UP(n),i),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Sn(t,s,{semantic:r.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)zP(e,l,a)&&c.add(u);return c}function UP(e){let t=new Map;for(let n of e){let i=$(n.symbol);i&&t.set(Ip(n.relativePath,i),n)}return t}function WP(e,t,n){let i=[];for(let r of n){let o=GP(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function GP(e,t,n){if(Np(e,n.relativePath,n.startLine)!=="class")return null;let i=$(n.symbol);if(!i)return null;let r=KP(e,n.relativePath,i);return r?t.get(Ip(n.relativePath,r))??null:null}function zP(e,t,n){let i=$(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Ka(e,o,i))}function Ip(e,t){return`${e}\0${t}`}function KP(e,t,n){let i=M(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function JP(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function QP(e){let t=pe(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function Pp(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n.endsWith("-types")||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||n==="contracts"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e)||/(^|\/)contracts?(\/|\.)/.test(e))}function XP(e,t,n){return!(Pp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function YP(e,t,n,i){let r=Bs(e,t.relativePath),o=$(t.symbol);if(!o)return!1;let s=r.get(o);if(!s||s.size===0)return!1;let a=i.get(t.relativePath);if(!a)return!1;for(let c of s){let l=a.get(c);if(!l)continue;let u=n.get(l.symbolId);if(u){for(let d of u)if(d!==t.relativePath&&!e.isIgnored(d))return!0}}return!1}function Np(e,t,n){let i=M(e,t);if(!i)return"other";let r=i.split(`
527
+ `),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let l=(r[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function ZP(e,t){let n=M(e,t.relativePath);if(!n)return!1;let i=$(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\b`),s=n.split(`
528
+ `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function eN(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}import{basename as ui,extname as Oo}from"path";function Ln(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new T(e),a=cN(s.fileDependencyGraph(n));return We({candidates:()=>nN(s,n,i),orderCandidates:So,scanLimit:o,prepare:c=>({callerFileMap:Sn(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>tN(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:r})}function tN(e,t,n,i){let r=iN(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=rN(e,n.symbolId,o);if(!s)return null;let a=oN(t,e,o,n.symbol,s);if(a&&Vn(a.symbol))return null;let{fanIn:c,source:l}=sN(i.callerFileMap,i.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=uN(e,n,o,a);return{symbol:n.symbol,shortName:y(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:q(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?y(a.symbol):ui(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function nN(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function iN(e,t,n,i){let r=ui(n.relativePath,Oo(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>ui(s,Oo(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return wo(e,n,o).realConsumers}function rN(e,t,n){return e.get(`SELECT c.start_line, c.end_line
529
529
  FROM mentions m
530
530
  JOIN chunks c ON m.chunk_id = c.id
531
531
  JOIN documents d ON c.document_id = d.id
532
532
  WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
533
- LIMIT 1`,t,n)}function YP(e,t,n,i,r){let o=e.definitionsForFile(n),s=eN(t,n,i,r.start_line,r.end_line);return je(o,s)}function ZP(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:nN(t,n),source:"file"}}function eN(e,t,n,i,r){let o=F(n);if(!o)return i;let s=vt(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function tN(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function nN(e,t){let n=e.get(t)??0;if(n>0)return n;let i=ui(t,Mo(t)),r=0;for(let[o,s]of e)o!==t&&ui(o,Mo(o))===i&&s>r&&(r=s);return r}function iN(e,t,n,i){return Ao(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:y(t.symbol)},{label:"caller name",value:i?.symbol?y(i.symbol):ui(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var lN=75e3,uN=5e3,dN=2500;function mN(e){let t=Oe(e);return t.symbols>=lN||t.documents>=uN?dN:void 0}var pN=".scipquery-baseline.json";function Oo(e,t){return t&&aN(t)?t:cN(e.config.projectRoot,t??pN)}function gc(e,t={}){let{scope:n}=t,i=mN(e),r=[],o=Rt(e,{scope:n,...ae.dead,scanLimit:i});for(let s of o.symbols)we(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of pn(e,{scope:n,...ae.isolated,scanLimit:i}))we(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of mn(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${fN(s.path)}`);for(let s of kt(e,{scope:n,...ae.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of yn(e,{scope:n,...ae.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Ln(e,{scope:n,...ae.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of kn(e,{scope:n,...ae.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of wn(e,{scope:n,...ae.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of Rn(e,{scope:n,...ae.drift}).results)s.kind!=="pattern-deviation"&&r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(r)].sort()}function fN(e){if(e.length===0)return"";let t=0;for(let n=1;n<e.length;n++)e[n]<e[t]&&(t=n);return[...e.slice(t),...e.slice(0,t)].join(">")}function hc(e,t={}){let n=gc(e,{scope:t.scope}),i=Oo(e,t.path);return sN(i,JSON.stringify({version:1,findings:n},null,2)+`
534
- `),{path:i,findingCount:n.length}}function cr(e,t={}){let n=Oo(e,t.path);if(!rN(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let i=JSON.parse(oN(n,"utf-8")),r=new Set(i.findings??[]),o=gc(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:r.size,current:o,newFindings:o.filter(a=>!r.has(a)),fixedFindings:[...r].filter(a=>!s.has(a))}}var gN=5;function lr(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20}=t,c=t.semantic!==!1,l=t.diffPlan??ut(e,{base:n}),u={available:l.note!==ac,base:n,changedFiles:l.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!u.available||l.changedFiles.length===0)return u;let d=new T(e),m=new Set(l.changedFiles),p=new Map(l.renamedFiles.map(L=>[L.to,L.from])),h=vN(e,d,m,n,p);if(h.length===0)return u;let g=h.slice(0,s);h.length>s&&(u.note=`helper scoring capped at ${s} of ${h.length} new symbols`);let b=xo(e,{minCallees:Math.min(3,r),semantic:c}),S=hN(b),x=d.calleeMap(g,{semantic:c}),I=g.map(L=>({def:L,callees:Co((x.get(L.symbolId)??[]).map(C=>C.symbol))}));for(let{def:L,callees:C}of I){let D=y(L.symbol);if(C.size<r){u.skipped.push({helperShortName:D,helperFile:L.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let k=CN(C,S);if(k===0){u.skipped.push({helperShortName:D,helperFile:L.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let A=RN(e,L.symbolId);if(A.length===0){u.skipped.push({helperShortName:D,helperFile:L.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}u.helpersChecked+=1;let Se=bN({candidateIndex:S,changed:m,helperCallees:C,helperFile:L.relativePath,helperSymbol:L.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:A});Se.length!==0&&(Se.sort((de,Te)=>Ip(Te.migrationScope)-Ip(de.migrationScope)||Te.containment-de.containment||Te.siteCoverage-de.siteCoverage||de.file.localeCompare(Te.file)),u.findings.push({helperSymbol:L.symbol,helperShortName:D,helperFile:L.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:k,migratedFiles:A.sort(),leftovers:Se.slice(0,gN)}))}return u.findings.sort((L,C)=>(C.leftovers[0]?.containment??0)-(L.leftovers[0]?.containment??0)||L.helperFile.localeCompare(C.helperFile)),u.findings=u.findings.slice(0,a),u}function hN(e){let t=new Map,n=new Map;for(let i of e)for(let r of i.callees){t.set(r,(t.get(r)??0)+1);let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return{candidatesByCallee:n,docFreq:t,ubiquityThreshold:Math.max(8,Math.ceil(Math.sqrt(e.length)))}}function bN(e){let t=[],n=yN(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidatesByCallee.get(r)??[])i.add(o);for(let r of i){if(r.symbol===e.helperSymbol||e.changed.has(r.file)||r.callees.has(e.helperSymbol))continue;let o=ym(e.helperCallees,r.callees);if(o<e.minContainment)continue;let s=[...e.helperCallees].filter(l=>r.callees.has(l)),a=r.callees.size===0?0:s.length/r.callees.size;if(a<e.minSiteCoverage||!s.some(l=>(e.candidateIndex.docFreq.get(l)??0)<=e.candidateIndex.ubiquityThreshold))continue;let c=SN(n,r.symbol,r.file);t.push({symbol:r.symbol,shortName:y(r.symbol),file:r.file,...c,containment:o,siteCoverage:a,uniqueSiteCalleeCount:Math.max(0,r.callees.size-s.length),sharedCallees:s.map(y).sort()})}return t}function Ip(e){return e==="same-scope"?2:e==="unknown"?1:0}function yN(e,t,n){let i=new Set([...bc(t),...yc(F(e))]);for(let r of n)for(let o of bc(r))i.add(o);return i}function SN(e,t,n){let i=new Set([...bc(n),...yc(F(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var xN=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function bc(e){return yc(e.replace(/\.[^.]+$/,""))}function yc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!xN.has(t))}function CN(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function vN(e,t,n,i,r){let o=new Map;return t.productionCallableDefinitions({requireFunctionLikeSymbol:!0}).filter(s=>{if(!n.has(s.relativePath))return!1;let a=r.get(s.relativePath)??s.relativePath,c=o.get(a);return c===void 0&&(c=rr(e.config.projectRoot,i,a),o.set(a,c)),c===null||!new RegExp(`\\b${kN(s.leaf)}\\b`).test(c)})}function RN(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
533
+ LIMIT 1`,t,n)}function oN(e,t,n,i,r){let o=e.definitionsForFile(n),s=aN(t,n,i,r.start_line,r.end_line);return je(o,s)}function sN(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:lN(t,n),source:"file"}}function aN(e,t,n,i,r){let o=$(n);if(!o)return i;let s=vt(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function cN(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function lN(e,t){let n=e.get(t)??0;if(n>0)return n;let i=ui(t,Oo(t)),r=0;for(let[o,s]of e)o!==t&&ui(o,Oo(o))===i&&s>r&&(r=s);return r}function uN(e,t,n,i){return Mo(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:y(t.symbol)},{label:"caller name",value:i?.symbol?y(i.symbol):ui(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var hN=75e3,bN=5e3,yN=2500;function SN(e){let t=Oe(e);return t.symbols>=hN||t.documents>=bN?yN:void 0}var xN=".scipquery-baseline.json";function jo(e,t){return t&&fN(t)?t:gN(e.config.projectRoot,t??xN)}function yc(e,t={}){let{scope:n}=t,i=SN(e),r=[],o=Rt(e,{scope:n,...ae.dead,scanLimit:i});for(let s of o.symbols)we(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of pn(e,{scope:n,...ae.isolated,scanLimit:i}))we(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of mn(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${CN(s.path)}`);for(let s of kt(e,{scope:n,...ae.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of yn(e,{scope:n,...ae.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Ln(e,{scope:n,...ae.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of kn(e,{scope:n,...ae.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of wn(e,{scope:n,...ae.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of Rn(e,{scope:n,...ae.drift}).results)s.kind!=="pattern-deviation"&&r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(r)].sort()}function CN(e){if(e.length===0)return"";let t=0;for(let n=1;n<e.length;n++)e[n]<e[t]&&(t=n);return[...e.slice(t),...e.slice(0,t)].join(">")}function Sc(e,t={}){let n=yc(e,{scope:t.scope}),i=jo(e,t.path);return pN(i,JSON.stringify({version:1,findings:n},null,2)+`
534
+ `),{path:i,findingCount:n.length}}function cr(e,t={}){let n=jo(e,t.path);if(!dN(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let i=JSON.parse(mN(n,"utf-8")),r=new Set(i.findings??[]),o=yc(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:r.size,current:o,newFindings:o.filter(a=>!r.has(a)),fixedFindings:[...r].filter(a=>!s.has(a))}}var vN=5;function lr(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20}=t,c=t.semantic!==!1,l=t.diffPlan??lt(e,{base:n}),u={available:l.note!==uc,base:n,changedFiles:l.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!u.available||l.changedFiles.length===0)return u;let d=new T(e),m=new Set(l.changedFiles),p=new Map(l.renamedFiles.map(L=>[L.to,L.from])),h=PN(e,d,m,n,p);if(h.length===0)return u;let g=h.slice(0,s);h.length>s&&(u.note=`helper scoring capped at ${s} of ${h.length} new symbols`);let b=Co(e,{minCallees:Math.min(3,r),semantic:c}),S=RN(b),x=d.calleeMap(g,{semantic:c}),I=g.map(L=>({def:L,callees:vo((x.get(L.symbolId)??[]).map(C=>C.symbol))}));for(let{def:L,callees:C}of I){let D=y(L.symbol);if(C.size<r){u.skipped.push({helperShortName:D,helperFile:L.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let k=IN(C,S);if(k===0){u.skipped.push({helperShortName:D,helperFile:L.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let A=NN(e,L.symbolId);if(A.length===0){u.skipped.push({helperShortName:D,helperFile:L.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}u.helpersChecked+=1;let Se=kN({candidateIndex:S,changed:m,helperCallees:C,helperFile:L.relativePath,helperSymbol:L.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:A});Se.length!==0&&(Se.sort((de,Te)=>Ep(Te.migrationScope)-Ep(de.migrationScope)||Te.containment-de.containment||Te.siteCoverage-de.siteCoverage||de.file.localeCompare(Te.file)),u.findings.push({helperSymbol:L.symbol,helperShortName:D,helperFile:L.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:k,migratedFiles:A.sort(),leftovers:Se.slice(0,vN)}))}return u.findings.sort((L,C)=>(C.leftovers[0]?.containment??0)-(L.leftovers[0]?.containment??0)||L.helperFile.localeCompare(C.helperFile)),u.findings=u.findings.slice(0,a),u}function RN(e){let t=new Map,n=new Map;for(let i of e)for(let r of i.callees){t.set(r,(t.get(r)??0)+1);let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return{candidatesByCallee:n,docFreq:t,ubiquityThreshold:Math.max(8,Math.ceil(Math.sqrt(e.length)))}}function kN(e){let t=[],n=wN(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidatesByCallee.get(r)??[])i.add(o);for(let r of i){if(r.symbol===e.helperSymbol||e.changed.has(r.file)||r.callees.has(e.helperSymbol))continue;let o=Cm(e.helperCallees,r.callees);if(o<e.minContainment)continue;let s=[...e.helperCallees].filter(l=>r.callees.has(l)),a=r.callees.size===0?0:s.length/r.callees.size;if(a<e.minSiteCoverage||!s.some(l=>(e.candidateIndex.docFreq.get(l)??0)<=e.candidateIndex.ubiquityThreshold))continue;let c=LN(n,r.symbol,r.file);t.push({symbol:r.symbol,shortName:y(r.symbol),file:r.file,...c,containment:o,siteCoverage:a,uniqueSiteCalleeCount:Math.max(0,r.callees.size-s.length),sharedCallees:s.map(y).sort()})}return t}function Ep(e){return e==="same-scope"?2:e==="unknown"?1:0}function wN(e,t,n){let i=new Set([...xc(t),...Cc($(e))]);for(let r of n)for(let o of xc(r))i.add(o);return i}function LN(e,t,n){let i=new Set([...xc(n),...Cc($(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var DN=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function xc(e){return Cc(e.replace(/\.[^.]+$/,""))}function Cc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!DN.has(t))}function IN(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function PN(e,t,n,i,r){let o=new Map;return t.productionCallableDefinitions({requireFunctionLikeSymbol:!0}).filter(s=>{if(!n.has(s.relativePath))return!1;let a=r.get(s.relativePath)??s.relativePath,c=o.get(a);return c===void 0&&(c=rr(e.config.projectRoot,i,a),o.set(a,c)),c===null||!new RegExp(`\\b${EN(s.leaf)}\\b`).test(c)})}function NN(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
535
535
  FROM mentions m
536
536
  JOIN chunks c ON m.chunk_id = c.id
537
537
  JOIN documents ref_d ON c.document_id = ref_d.id
538
538
  WHERE m.symbol_id = ?
539
539
  AND m.role != 1
540
- ${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}function kN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ur(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=t.files===void 0?null:new Set(t.files),s=new T(e);return We({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>wN(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:r,evaluate:a=>{let c=oe(e,a.relativePath)?.callables.find(d=>d.startLine===a.startLine&&d.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(d=>!d.simple)||c.paramsEndLine>=c.endLine)return null;let l=vt(e,a.relativePath),u=[];for(let d=c.params.length-1;d>=0;d--){let m=c.params[d];if(m.name===""||m.name.startsWith("_")||LN(l.get(m.name),c.paramsEndLine,c.endLine))break;u.unshift(m.name)}return u.length===0?null:{symbol:a.symbol,shortName:y(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,paramCount:c.paramCount,unusedTrailing:u}},orderResults:(a,c)=>c.unusedTrailing.length-a.unusedTrailing.length||a.file.localeCompare(c.file)||a.startLine-c.startLine,limit:i})}function wN(e){let t=W(e);return t==="typescript"||t==="tsx"||t==="javascript"}function LN(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var Bo=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function dr(e,t={}){let n=t.base??"HEAD",{minTogether:i=6,minConfidence:r=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8}=t,c=new Set(t.skip??[]),l=ut(e,{base:n}),u=ci(e,{base:n,plan:l}),d=u.changedFiles,m=new Set(d),p=new Set(l.changedFileLines),h=YN(e.config.projectRoot,n,l),g={base:n,changedFiles:d,changedSymbols:u.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:u.summary.note};if(d.length===0)return g;let b=(S,x)=>{if(c.has(S)){g.skipped.push({check:S,reason:"skipped via --skip"});return}x()};return b("echo",()=>_N(e,u.changedSymbols,m,h,o,a,g)),b("incomplete-migration",()=>VN(e,n,l,s,g)),b("co-change-partner",()=>qN(e,m,i,r,g)),b("doc-reference",()=>KN(e,m,p,l.changedRanges,g)),b("unused-params",()=>JN(e,d,g)),b("new-dead",()=>QN(e,u.changedSymbols,h,g)),b("baseline",()=>tE(e,g)),EN(g,e.config.suppressions??[]),g.rootCauseGroups=IN(g.findings),g}function IN(e){let t=new Map;for(let n of e){let i=n.groupKey??`${n.check}:${n.id}`,r=t.get(i);r||(r={groupKey:i,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(i,r)),r.count+=1,r.findingIds.push(n.id),r.severity=PN(r.severity,n.severity),r.actionTier=NN(r.actionTier,n.actionTier),n.file&&r.files.add(n.file);for(let o of n.relatedFiles??[])r.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,i)=>i.count-n.count||jo(i.severity)-jo(n.severity)||n.groupKey.localeCompare(i.groupKey))}function PN(e,t){return jo(t)>jo(e)?t:e}function jo(e){return e==="error"?2:e==="warning"?1:0}function NN(e,t){return e?t&&Pp(t)>Pp(e)?t:e:t}function Pp(e){return e==="direct"?2:e==="signal"?1:0}function EN(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let i of e.findings){let r=t.find(o=>TN(o,i));r?e.suppressed.push({finding:i,suppression:r}):n.push(i)}e.findings=n}function TN(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function di(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function _N(e,t,n,i,r,o,s){s.checksRun.push("echo");for(let a of t.slice(0,r)){if(i(a))continue;let c=Zi(e,a.symbol,{minSimilarity:o,limit:5}),l=[];for(let p of c){let h=p.fileA===a.file?p.fileB:p.fileA,g=p.fileA===a.file?p.shortNameB:p.shortNameA,b=p.fileA===a.file?p.symbolB:p.symbolA;n.has(h)||l.push({otherFile:h,otherShort:g,otherSymbol:b,similarity:p.similarity,similarityBasis:p.similarityBasis??"callees",sharedEvidence:p.sharedCallees})}if(l.length===0)continue;let u=l[0],d=Dn("echo",a.symbol,a.file,...l.map(p=>`${p.otherSymbol}|${p.otherFile}`).sort()),m=FN(a,l);di(s,{id:d,groupKey:d,actionTier:m,check:"echo",severity:"warning",evidence:"heuristic",confidence:u.similarity,file:a.file,symbol:a.symbol,relatedFiles:[...new Set(l.map(p=>p.otherFile))].sort(),message:jN(a,l),why:BN(a,l),remediation:HN(m,a.shortName,u.otherShort)})}t.length>r&&s.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function FN(e,t){return t.some(i=>$N(e.symbol,i))?"direct":"signal"}function $N(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=F(e),i=F(t.otherSymbol);return!n||!i?!1:n===i?!0:ON(t.sharedEvidence)?!1:AN(n,i)}function AN(e,t){let n=Np(e),i=Np(t);if(n.length===0||i.length===0)return!1;let r=new Set(i),o=n.filter(s=>r.has(s)).length;return o>=2&&o/Math.min(n.length,i.length)>=.5}function Np(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var MN=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function ON(e){return e.length>=3&&e.every(t=>MN.has(t.toLowerCase()))}function jN(e,t){let n=t[0],i=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${i}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${i}% similar to ${n.otherShort} (${n.otherFile})`}function BN(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let i of t.slice(0,3))n.push(`${i.otherShort} is outside this diff and scored ${Math.round(i.similarity*100)}% similar by ${i.similarityBasis} evidence.`),n.push(`Shared evidence: ${i.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function HN(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function VN(e,t,n,i,r){let o=lr(e,{base:t,maxHelpers:i,diffPlan:n});if(!o.available){r.skipped.push({check:"incomplete-migration",reason:"no git history"});return}r.checksRun.push("incomplete-migration"),o.note&&r.skipped.push({check:"incomplete-migration",reason:o.note});for(let s of o.findings){let a=s.leftovers.map(p=>`${p.shortName} (${p.file}, ${Math.round(p.containment*100)}% helper / ${Math.round(p.siteCoverage*100)}% site, ${p.migrationScope})`).join(", "),c=s.leftovers.map(p=>`${p.shortName}: ${p.migrationScope} (${p.migrationScopeReasons[0]})`).join("; "),l=[...s.migratedFiles,...s.leftovers.map(p=>p.file)],u=s.leftovers.length===0?void 0:Math.max(...s.leftovers.map(p=>Math.min(p.containment,p.siteCoverage))),d=s.leftovers.some(p=>p.migrationScope==="possible-subtype"),m=Dn("incomplete-migration",s.helperSymbol,s.helperFile,l.join("|"));di(r,{id:m,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:u,file:s.helperFile,symbol:s.helperSymbol,relatedFiles:l,message:`new helper ${s.helperShortName} (${s.helperFile}) is wired into ${s.migratedFiles.length} file(s), but ${s.leftovers.length} similar un-migrated site(s) remain: ${a}`,why:[`${s.helperShortName} is new in this diff and already referenced by ${s.migratedFiles.join(", ")}.`,`Helper shape: ${s.helperShape}; ${s.specificHelperCalleeCount}/${s.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${a}.`,`Migration scope hints: ${c}.`],remediation:d?`Migrate same-scope sites to ${s.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${s.helperShortName}, or confirm they are intentionally different.`})}}function qN(e,t,n,i,r){let o=Ym(e,t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!o){r.skipped.push({check:"co-change-partner",reason:"no git history"});return}r.checksRun.push("co-change-partner");let s=new Set,a;for(let c of o){let l=t.has(c.fileA),u=t.has(c.fileB);if(l===u)continue;let d=l?c.fileA:c.fileB,m=l?c.fileB:c.fileA,p=l?c.changesA:c.changesB,h=p>0?c.together/p:0;if(h<i||ic(m)||ic(d)||!Ep(`${e.config.projectRoot}/${m}`))continue;let g=`${d}|${m}`;if(s.has(g))continue;s.add(g);let b=Dn("co-change-partner",d,m,String(c.together)),S=rc(d,m),x=oc({fileA:d,fileB:m,together:c.together,confidence:h,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},S,(a??=sc(e))(d,m)),I=[d,m].sort().join("|");r.findings.push({id:b,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${I}`,confidence:h,file:d,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:I,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,commitScope:c.commitScope,recency:c.recency,focusedTogether:c.focusedTogether,broadTogether:c.broadTogether,broadCommitRatio:c.broadCommitRatio,lastTogetherAt:c.lastTogetherAt,recentTogether:c.recentTogether,subjectContext:c.subjectContext,...x?{declaredCouplingSuggestion:x}:{},message:`${d} changed, but ${m} did not \u2014 they change together ${c.together}x (${Math.round(h*100)}% of the time)`,why:[`${d} is in this diff and ${m} is not.`,`Git history shows ${c.together} co-change(s), which is ${Math.round(h*100)}% of changes to the edited side.`,`History context: ${UN(c)}.`,`Subject context: ${WN(c.subjectContext)}.`,...GN(c),`Partner class: ${S.partnerClass} (${S.reasons.join("; ")}).`],remediation:x?`Update ${m} alongside this change, declare the coupling "${x.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function UN(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${zN(e.lastTogetherAt)}`}function WN(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}function GN(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function zN(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function KN(e,t,n,i,r){r.checksRun.push("doc-reference");let o=li.referenceTargets(e,t,i);if(o.size!==0)for(let s of bp(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:li.citationContexts(e,s.doc,s.cited),c=li.classifyCitation(a),l=Dn("doc-reference",s.doc,s.cited.join("|"));di(r,{id:l,check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:c.actionTier,confidence:1,file:s.doc,relatedFiles:s.cited,citationKind:c.citationKind,citationKindReasons:c.reasons,citedClaims:a,message:`${s.doc} cites ${s.cited.join(", ")} as ${li.citationKindLabel(c.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${s.cited.join(", ")} changed in this diff.`,`${s.doc} cites the changed file(s) but was not updated in the same diff.`,...c.reasons.map(u=>`Citation kind evidence: ${u}`)],remediation:li.citationRemediation(c.citationKind,s.doc)})}}function JN(e,t,n){n.checksRun.push("unused-params");for(let i of ur(e,{files:t,limit:50})){let r=Dn("unused-params",i.symbol,i.file,i.unusedTrailing.join("|"));di(n,{id:r,check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:i.file,startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,message:`${i.shortName} (${i.file}) has trailing unused parameter(s): ${i.unusedTrailing.join(", ")}`,why:[`${i.shortName} is in a changed file.`,`The trailing parameter(s) ${i.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function QN(e,t,n,i){i.checksRun.push("new-dead");let r=new T(e);for(let o of t){if(n(o)||o.fanIn>0||r.fileKind(o.file)==="test"||we(e,o.file)||ie(e,o.symbol,o.file)||XN(o.symbol))continue;let s=Dn("new-dead",o.symbol,o.file);di(i,{id:s,check:"new-dead",severity:"warning",evidence:"graph-fact",confidence:.9,file:o.file,symbol:o.symbol,message:`${o.shortName} (${o.file}) was changed but has zero indexed consumers`,why:[`${o.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:"Wire it up, or remove it before it becomes permanent dead code."})}}function XN(e){if(Z(e)!=="type")return!1;let t=F(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function YN(e,t,n){let i=new Map(n.renamedFiles.map(o=>[o.to,o.from])),r=new Map;return o=>{let s=i.get(o.file)??o.file,a=F(o.symbol);if(!a)return!1;let c=r.get(s);return c===void 0&&(c=rr(e,t,s),r.set(s,c)),c!==null&&ZN(c,a)}}function ZN(e,t){return new RegExp(`\\b${eE(t)}\\b`).test(e)}function eE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tE(e,t){if(!Ep(Oo(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let n=cr(e);for(let i of n.newFindings){let r=dp(i),o=Dn("baseline",i);di(t,{id:o,groupKey:`baseline:${r.sourceAnalyzer}:${r.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:r.actionTier,confidence:1,file:r.file,relatedFiles:r.relatedFiles.length>0?r.relatedFiles:void 0,sourceAnalyzer:r.sourceAnalyzer,rootCauseKey:r.rootCauseKey,message:`new ${r.label} vs committed baseline: ${i}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${r.sourceAnalyzer}.`,`Inherited action tier: ${r.actionTier}.`,`Root cause key: ${r.rootCauseKey}.`,...r.why],remediation:r.remediation})}}function Dn(e,...t){return`SQ${DN("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var nE=.7,Tp=.62,_p=.45;function Sc(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Qm(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let c=iE(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic}).map(u=>lE(u,s,n)).filter(u=>u!==null);c.sort((u,d)=>(u.kind===d.kind?0:u.kind==="echo"?-1:1)||d.similarity-u.similarity||u.echoFile.localeCompare(d.echoFile)||u.echoSymbol.localeCompare(d.echoSymbol)||u.domain.localeCompare(d.domain));let l=c.slice(0,i).map(uE);return{available:!0,windowCommits:n,findings:l,rootCauseGroups:dE(l)}}function iE(e,t){let n=pE(t.limit);return[...rE(e,{scope:t.scope,minSimilarity:t.minSimilarity??nE,limit:n,scanLimit:t.scanLimit,semantic:t.semantic}),...oE(e,{scope:t.scope,minSimilarity:t.minSimilarity??Tp,limit:n,scanLimit:t.scanLimit}),...sE(e,{scope:t.scope,minSimilarity:t.minSimilarity??_p,limit:n,scanLimit:t.scanLimit}),...aE(e,{scope:t.scope,minSimilarity:t.minSimilarity??Tp,limit:n,scanLimit:t.scanLimit}),...cE(e,{scope:t.scope,minSimilarity:t.minSimilarity??_p,limit:n,scanLimit:t.scanLimit})]}function rE(e,t){return kt(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic}).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function oE(e,t){return Vo(e,t,{query:fn,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function Vo(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:fE(...n.evidenceBuckets(i)),sharedCallees:[]}))}function sE(e,t){return Vo(e,t,{query:gn,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}function aE(e,t){return Vo(e,t,{query:hn,domain:"vue-component",basis:"vue-template",symbolA:n=>Ho(n.fileA),symbolB:n=>Ho(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function cE(e,t){return Vo(e,t,{query:bn,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Ho(n.fileA),symbolB:n=>Ho(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function lE(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function uE(e){let t=Fp(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function Fp(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function dE(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??Fp(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:mE(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function mE(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function pE(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function fE(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Ho(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var gE=Y("suppression-inventory",{clearGroups:["whole-project"]});function qo(e){return gE.get(e,()=>hE(e))}function hE(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,i=0;for(let r of De(e)){let o=M(e,r);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Li(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let c=bE(a);t[c]+=1}}return{total:i,byCategory:t,byFile:n}}function bE(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as yE}from"fs";import{join as SE}from"path";function mr(e,t,n={}){let i=B(e,t);if(!i)return null;let r=new T(e),o=kE(CE(e,i.relativePath,i.startLine,i.endLine),xE(e,i.relativePath)),s=i.endLine-i.startLine+1,c=r.calleeMap([i],{additive:!0,semantic:n.semantic}).get(i.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:i.symbol,shortName:y(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:vE(e,i.symbolId),fanOut:RE(c,i.relativePath)}}function xE(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function CE(e,t,n,i){try{return yE(SE(e.config.projectRoot,t),"utf-8").split(`
540
+ ${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}function EN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ur(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=t.files===void 0?null:new Set(t.files),s=new T(e);return We({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>TN(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:r,evaluate:a=>{let c=oe(e,a.relativePath)?.callables.find(d=>d.startLine===a.startLine&&d.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(d=>!d.simple)||c.paramsEndLine>=c.endLine)return null;let l=vt(e,a.relativePath),u=[];for(let d=c.params.length-1;d>=0;d--){let m=c.params[d];if(m.name===""||m.name.startsWith("_")||_N(l.get(m.name),c.paramsEndLine,c.endLine))break;u.unshift(m.name)}return u.length===0?null:{symbol:a.symbol,shortName:y(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,paramCount:c.paramCount,unusedTrailing:u}},orderResults:(a,c)=>c.unusedTrailing.length-a.unusedTrailing.length||a.file.localeCompare(c.file)||a.startLine-c.startLine,limit:i})}function TN(e){let t=W(e);return t==="typescript"||t==="tsx"||t==="javascript"}function _N(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var Ho=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function dr(e,t={}){let n=t.base??"HEAD",{minTogether:i=6,minConfidence:r=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8}=t,c=new Set(t.skip??[]),l=lt(e,{base:n}),u=ci(e,{base:n,plan:l}),d=u.changedFiles,m=new Set(d),p=new Set(l.changedFileLines),h=oE(e.config.projectRoot,n,l),g={base:n,changedFiles:d,changedSymbols:u.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:u.summary.note};if(d.length===0)return g;let b=(S,x)=>{if(c.has(S)){g.skipped.push({check:S,reason:"skipped via --skip"});return}x()};return b("echo",()=>BN(e,u.changedSymbols,m,h,o,a,g)),b("incomplete-migration",()=>JN(e,n,l,s,g)),b("co-change-partner",()=>QN(e,m,i,r,g)),b("doc-reference",()=>tE(e,m,p,l.changedRanges,g)),b("unused-params",()=>nE(e,d,g)),b("new-dead",()=>iE(e,u.changedSymbols,h,g)),b("baseline",()=>cE(e,g)),ON(g,e.config.suppressions??[]),g.rootCauseGroups=FN(g.findings),g}function FN(e){let t=new Map;for(let n of e){let i=n.groupKey??`${n.check}:${n.id}`,r=t.get(i);r||(r={groupKey:i,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(i,r)),r.count+=1,r.findingIds.push(n.id),r.severity=AN(r.severity,n.severity),r.actionTier=MN(r.actionTier,n.actionTier),n.file&&r.files.add(n.file);for(let o of n.relatedFiles??[])r.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,i)=>i.count-n.count||Bo(i.severity)-Bo(n.severity)||n.groupKey.localeCompare(i.groupKey))}function AN(e,t){return Bo(t)>Bo(e)?t:e}function Bo(e){return e==="error"?2:e==="warning"?1:0}function MN(e,t){return e?t&&Tp(t)>Tp(e)?t:e:t}function Tp(e){return e==="direct"?2:e==="signal"?1:0}function ON(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let i of e.findings){let r=t.find(o=>jN(o,i));r?e.suppressed.push({finding:i,suppression:r}):n.push(i)}e.findings=n}function jN(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function di(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function BN(e,t,n,i,r,o,s){s.checksRun.push("echo");for(let a of t.slice(0,r)){if(i(a))continue;let c=Zi(e,a.symbol,{minSimilarity:o,limit:5}),l=[];for(let p of c){let h=p.fileA===a.file?p.fileB:p.fileA,g=p.fileA===a.file?p.shortNameB:p.shortNameA,b=p.fileA===a.file?p.symbolB:p.symbolA;n.has(h)||l.push({otherFile:h,otherShort:g,otherSymbol:b,similarity:p.similarity,similarityBasis:p.similarityBasis??"callees",sharedEvidence:p.sharedCallees})}if(l.length===0)continue;let u=l[0],d=Dn("echo",a.symbol,a.file,...l.map(p=>`${p.otherSymbol}|${p.otherFile}`).sort()),m=HN(a,l);di(s,{id:d,groupKey:d,actionTier:m,check:"echo",severity:"warning",evidence:"heuristic",confidence:u.similarity,file:a.file,symbol:a.symbol,relatedFiles:[...new Set(l.map(p=>p.otherFile))].sort(),message:GN(a,l),why:zN(a,l),remediation:KN(m,a.shortName,u.otherShort)})}t.length>r&&s.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function HN(e,t){return t.some(i=>VN(e.symbol,i))?"direct":"signal"}function VN(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=$(e),i=$(t.otherSymbol);return!n||!i?!1:n===i?!0:WN(t.sharedEvidence)?!1:qN(n,i)}function qN(e,t){let n=_p(e),i=_p(t);if(n.length===0||i.length===0)return!1;let r=new Set(i),o=n.filter(s=>r.has(s)).length;return o>=2&&o/Math.min(n.length,i.length)>=.5}function _p(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var UN=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function WN(e){return e.length>=3&&e.every(t=>UN.has(t.toLowerCase()))}function GN(e,t){let n=t[0],i=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${i}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${i}% similar to ${n.otherShort} (${n.otherFile})`}function zN(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let i of t.slice(0,3))n.push(`${i.otherShort} is outside this diff and scored ${Math.round(i.similarity*100)}% similar by ${i.similarityBasis} evidence.`),n.push(`Shared evidence: ${i.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function KN(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function JN(e,t,n,i,r){let o=lr(e,{base:t,maxHelpers:i,diffPlan:n});if(!o.available){r.skipped.push({check:"incomplete-migration",reason:"no git history"});return}r.checksRun.push("incomplete-migration"),o.note&&r.skipped.push({check:"incomplete-migration",reason:o.note});for(let s of o.findings){let a=s.leftovers.map(p=>`${p.shortName} (${p.file}, ${Math.round(p.containment*100)}% helper / ${Math.round(p.siteCoverage*100)}% site, ${p.migrationScope})`).join(", "),c=s.leftovers.map(p=>`${p.shortName}: ${p.migrationScope} (${p.migrationScopeReasons[0]})`).join("; "),l=[...s.migratedFiles,...s.leftovers.map(p=>p.file)],u=s.leftovers.length===0?void 0:Math.max(...s.leftovers.map(p=>Math.min(p.containment,p.siteCoverage))),d=s.leftovers.some(p=>p.migrationScope==="possible-subtype"),m=Dn("incomplete-migration",s.helperSymbol,s.helperFile,l.join("|"));di(r,{id:m,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:u,file:s.helperFile,symbol:s.helperSymbol,relatedFiles:l,message:`new helper ${s.helperShortName} (${s.helperFile}) is wired into ${s.migratedFiles.length} file(s), but ${s.leftovers.length} similar un-migrated site(s) remain: ${a}`,why:[`${s.helperShortName} is new in this diff and already referenced by ${s.migratedFiles.join(", ")}.`,`Helper shape: ${s.helperShape}; ${s.specificHelperCalleeCount}/${s.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${a}.`,`Migration scope hints: ${c}.`],remediation:d?`Migrate same-scope sites to ${s.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${s.helperShortName}, or confirm they are intentionally different.`})}}function QN(e,t,n,i,r){let o=tp(e,t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!o){r.skipped.push({check:"co-change-partner",reason:"no git history"});return}r.checksRun.push("co-change-partner");let s=new Set,a;for(let c of o){let l=t.has(c.fileA),u=t.has(c.fileB);if(l===u)continue;let d=l?c.fileA:c.fileB,m=l?c.fileB:c.fileA,p=l?c.changesA:c.changesB,h=p>0?c.together/p:0;if(h<i||sc(m)||sc(d)||!$p(`${e.config.projectRoot}/${m}`))continue;let g=`${d}|${m}`;if(s.has(g))continue;s.add(g);let b=Dn("co-change-partner",d,m,String(c.together)),S=ac(d,m),x=cc({fileA:d,fileB:m,together:c.together,confidence:h,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},S,(a??=lc(e))(d,m)),I=[d,m].sort().join("|");r.findings.push({id:b,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${I}`,confidence:h,file:d,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:I,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,commitScope:c.commitScope,recency:c.recency,focusedTogether:c.focusedTogether,broadTogether:c.broadTogether,broadCommitRatio:c.broadCommitRatio,lastTogetherAt:c.lastTogetherAt,recentTogether:c.recentTogether,subjectContext:c.subjectContext,...x?{declaredCouplingSuggestion:x}:{},message:`${d} changed, but ${m} did not \u2014 they change together ${c.together}x (${Math.round(h*100)}% of the time)`,why:[`${d} is in this diff and ${m} is not.`,`Git history shows ${c.together} co-change(s), which is ${Math.round(h*100)}% of changes to the edited side.`,`History context: ${XN(c)}.`,`Subject context: ${YN(c.subjectContext)}.`,...ZN(c),`Partner class: ${S.partnerClass} (${S.reasons.join("; ")}).`],remediation:x?`Update ${m} alongside this change, declare the coupling "${x.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function XN(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${eE(e.lastTogetherAt)}`}function YN(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}function ZN(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function eE(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function tE(e,t,n,i,r){r.checksRun.push("doc-reference");let o=li.referenceTargets(e,t,i);if(o.size!==0)for(let s of xp(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:li.citationContexts(e,s.doc,s.cited),c=li.classifyCitation(a),l=Dn("doc-reference",s.doc,s.cited.join("|"));di(r,{id:l,check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:c.actionTier,confidence:1,file:s.doc,relatedFiles:s.cited,citationKind:c.citationKind,citationKindReasons:c.reasons,citedClaims:a,message:`${s.doc} cites ${s.cited.join(", ")} as ${li.citationKindLabel(c.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${s.cited.join(", ")} changed in this diff.`,`${s.doc} cites the changed file(s) but was not updated in the same diff.`,...c.reasons.map(u=>`Citation kind evidence: ${u}`)],remediation:li.citationRemediation(c.citationKind,s.doc)})}}function nE(e,t,n){n.checksRun.push("unused-params");for(let i of ur(e,{files:t,limit:50})){let r=Dn("unused-params",i.symbol,i.file,i.unusedTrailing.join("|"));di(n,{id:r,check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:i.file,startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,message:`${i.shortName} (${i.file}) has trailing unused parameter(s): ${i.unusedTrailing.join(", ")}`,why:[`${i.shortName} is in a changed file.`,`The trailing parameter(s) ${i.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function iE(e,t,n,i){i.checksRun.push("new-dead");let r=new T(e);for(let o of t){if(n(o)||o.fanIn>0||r.fileKind(o.file)==="test"||we(e,o.file)||ie(e,o.symbol,o.file)||rE(o.symbol))continue;let s=Dn("new-dead",o.symbol,o.file);di(i,{id:s,check:"new-dead",severity:"warning",evidence:"graph-fact",confidence:.9,file:o.file,symbol:o.symbol,message:`${o.shortName} (${o.file}) was changed but has zero indexed consumers`,why:[`${o.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:"Wire it up, or remove it before it becomes permanent dead code."})}}function rE(e){if(Z(e)!=="type")return!1;let t=$(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function oE(e,t,n){let i=new Map(n.renamedFiles.map(o=>[o.to,o.from])),r=new Map;return o=>{let s=i.get(o.file)??o.file,a=$(o.symbol);if(!a)return!1;let c=r.get(s);return c===void 0&&(c=rr(e,t,s),r.set(s,c)),c!==null&&sE(c,a)}}function sE(e,t){return new RegExp(`\\b${aE(t)}\\b`).test(e)}function aE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cE(e,t){if(!$p(jo(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let n=cr(e);for(let i of n.newFindings){let r=fp(i),o=Dn("baseline",i);di(t,{id:o,groupKey:`baseline:${r.sourceAnalyzer}:${r.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:r.actionTier,confidence:1,file:r.file,relatedFiles:r.relatedFiles.length>0?r.relatedFiles:void 0,sourceAnalyzer:r.sourceAnalyzer,rootCauseKey:r.rootCauseKey,message:`new ${r.label} vs committed baseline: ${i}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${r.sourceAnalyzer}.`,`Inherited action tier: ${r.actionTier}.`,`Root cause key: ${r.rootCauseKey}.`,...r.why],remediation:r.remediation})}}function Dn(e,...t){return`SQ${$N("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var lE=.7,Fp=.62,Ap=.45;function vc(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Zm(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let c=uE(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic}).map(u=>hE(u,s,n)).filter(u=>u!==null);c.sort((u,d)=>(u.kind===d.kind?0:u.kind==="echo"?-1:1)||d.similarity-u.similarity||u.echoFile.localeCompare(d.echoFile)||u.echoSymbol.localeCompare(d.echoSymbol)||u.domain.localeCompare(d.domain));let l=c.slice(0,i).map(bE);return{available:!0,windowCommits:n,findings:l,rootCauseGroups:yE(l)}}function uE(e,t){let n=xE(t.limit);return[...dE(e,{scope:t.scope,minSimilarity:t.minSimilarity??lE,limit:n,scanLimit:t.scanLimit,semantic:t.semantic}),...mE(e,{scope:t.scope,minSimilarity:t.minSimilarity??Fp,limit:n,scanLimit:t.scanLimit}),...pE(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ap,limit:n,scanLimit:t.scanLimit}),...fE(e,{scope:t.scope,minSimilarity:t.minSimilarity??Fp,limit:n,scanLimit:t.scanLimit}),...gE(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ap,limit:n,scanLimit:t.scanLimit})]}function dE(e,t){return kt(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic}).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function mE(e,t){return qo(e,t,{query:fn,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function qo(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:CE(...n.evidenceBuckets(i)),sharedCallees:[]}))}function pE(e,t){return qo(e,t,{query:gn,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}function fE(e,t){return qo(e,t,{query:hn,domain:"vue-component",basis:"vue-template",symbolA:n=>Vo(n.fileA),symbolB:n=>Vo(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function gE(e,t){return qo(e,t,{query:bn,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Vo(n.fileA),symbolB:n=>Vo(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function hE(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function bE(e){let t=Mp(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function Mp(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function yE(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??Mp(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:SE(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function SE(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function xE(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function CE(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Vo(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var vE=Y("suppression-inventory",{clearGroups:["whole-project"]});function Uo(e){return vE.get(e,()=>RE(e))}function RE(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,i=0;for(let r of De(e)){let o=M(e,r);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Li(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let c=kE(a);t[c]+=1}}return{total:i,byCategory:t,byFile:n}}function kE(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as wE}from"fs";import{join as LE}from"path";function mr(e,t,n={}){let i=B(e,t);if(!i)return null;let r=new T(e),o=EE(IE(e,i.relativePath,i.startLine,i.endLine),DE(e,i.relativePath)),s=i.endLine-i.startLine+1,c=r.calleeMap([i],{additive:!0,semantic:n.semantic}).get(i.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:i.symbol,shortName:y(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:PE(e,i.symbolId),fanOut:NE(c,i.relativePath)}}function DE(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function IE(e,t,n,i){try{return wE(LE(e.config.projectRoot,t),"utf-8").split(`
541
541
  `).slice(n,i+1).join(`
542
- `)}catch{return""}}function vE(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
542
+ `)}catch{return""}}function PE(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
543
543
  FROM mentions m
544
544
  JOIN chunks c ON m.chunk_id = c.id
545
- WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function RE(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function kE(e,t){let n=rn(e),i=0,r=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of r){let s=n.match(o);s&&(i+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}return i}function pr(e,t,n={}){let i=B(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=Bt(e,i,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=wE(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:y(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:y(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":y(c.symbol),file:c.file}))}}function wE(e,t,n,i){let r=si(Ae(e,t,{limit:30,semantic:i.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=si(qe(e,t,{limit:30,semantic:i.semantic})),s=o.length>0?o:si(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:r,consumers:s}}function mi(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=B(e,t);return o?i==="backward"?LE(e,o,r,{semantic:n.semantic!==!1}):DE(e,o,{semantic:n.semantic!==!1}):null}function LE(e,t,n,i){let r=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=Ae(e,l,{semantic:i.semantic});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),r.push({symbol:d.symbol,shortName:y(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=zn(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:y(t.symbol),direction:"backward",connectedSymbols:r}}function DE(e,t,n){let i=new Set,r=[],o=new T(e);for(let s of Bt(e,t,{semantic:n.semantic})){if(r.length>=30)break;let a=s.enclosingSymbol??je(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=zn(e,a);!c||e.isIgnored(c.relativePath)||i.has(c.symbol)||(i.add(c.symbol),r.push({symbol:c.symbol,shortName:y(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:y(t.symbol),direction:"forward",connectedSymbols:r}}function xc(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=!PE(t),a=s?Wi(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Xi(e,t,{semantic:o}):null,l=s?mr(e,t,{semantic:o}):null,u=s?pr(e,t,{semantic:o}):null,d=s?mi(e,t,{direction:"backward",maxDepth:r,semantic:o}):null,m=s?mi(e,t,{direction:"forward",maxDepth:r,semantic:o}):null,p=s?nr(e,t,{maxDepth:i,scope:n.scope}):[],h=ir(e,t,{semantic:o}),g=Gi(e,t),b=zi(e,t),S=Ki(e,t),x=Ji(e,t),I={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||p.length>0,file:h!==null||g.length>0||b.length>0,module:S.files.length>0||S.symbols.length>0||x.length>0},L=[];!I.symbol&&!I.file&&!I.module&&L.push("No symbol, file, or module matched target.");let C=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:I,history:IE(e,C),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:p,changeSurface:h,deps:g,rdeps:b,system:S,surface:x,warnings:L}}function IE(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let i=Do(e);if(!i)return n;let r=xn(e,t,{limit:5});return{available:!0,file:t,churn:i.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:r.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence,subjectContext:o.subjectContext})),suppressionsInFile:qo(e).byFile.get(t)??0}}function PE(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function fr(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new T(e);return We({candidates:()=>s.productionCallableDefinitions({scope:n,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>NE(a,c,i),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:r})}function NE(e,t,n){let i=e.endLine-e.startLine+1;if(i<n)return null;let r=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=o.filter(l=>l.file!==e.relativePath),a=new Set(s.map(l=>`${l.symbol}|${l.file}`)).size,c=new Set(o.map(l=>`${l.symbol}|${l.file}`)).size;return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:a,calleeCount:c,score:Math.round(i/50*(r/5)*Math.max(a/5,1)*100)/100}}function Lt(e){return e.scoreCount??e.count}function Mp(e){let t=FE(e),{breakdown:n,pressure:i}=$E(e),r=Ap(n,"risk"),o=Ap(n,"hygiene");return{score:Math.min(r,o),riskScore:r,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Lt(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Lt(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Lt(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null},axes:EE(e),validation:_E(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function EE(e){return{deletable:{loc:e.dead.loc+e.isolated.loc,symbols:e.dead.count+e.isolated.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,churnWeightedComplexity:TE(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function TE(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:dt(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function _E(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[u,d]of Object.entries(t))i.has(u)?r+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=i.size>0?dt(r/i.size):0,c=s>0?dt(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let h=dt(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:h,lift:c>0?dt(h/c):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:i.size>0&&c>0?dt(a/c):null,byCategory:l}}function dt(e){return Math.round(e*100)/100}function Op(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Uo(e,t="existing shared infrastructure discount"){let n=Lt(e);return Math.abs(n-e.count)<.01?"":` (${Op(n)} score-weighted after ${t})`}function gr(e,t){let n=Lt(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${Op(n)} score-weighted)`}function FE(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${Uo(e.reactHookCandidates)} \u2014 extract or reuse a hook`,effort:"medium",impact:"medium",count:e.reactHookCandidates.count,locRecoverable:e.reactHookCandidates.loc}),e.reactLargeComponentPressure.count>0&&t.push({category:"Large React components",evidence:"heuristic",description:`${e.reactLargeComponentPressure.count} React component(s) concentrate JSX/behavior pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.reactLargeComponentPressure.count,locRecoverable:0}),e.vueComponentDuplicates.count>0&&t.push({category:"Duplicated Vue components",evidence:"heuristic",description:`${e.vueComponentDuplicates.count} Vue component pair(s) share template structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.vueComponentDuplicates.count,locRecoverable:e.vueComponentDuplicates.loc}),e.vueComposableCandidates.count>0&&t.push({category:"Duplicated Vue behavior",evidence:"heuristic",description:`${e.vueComposableCandidates.count} Vue component pair(s) share state/effect/request behavior${Uo(e.vueComposableCandidates)} \u2014 extract or reuse a composable`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${Uo(e.wrappers,"boundary-evidence discount")} \u2014 inline direct wrappers or review boundary signals`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove unused abstractions; review single-consumer ownership before moving or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&r.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove direct drift; review signal drift against layer ownership`,effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let r=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+Uo({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.fileB})`:"")+" \u2014 name the shared concept or enforce the sync",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var $p={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function Ap(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function $E(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(C,D,k)=>{D>0&&i.push({axis:C,points:D,detail:k,kind:$p[C]??"hygiene"})},s=(C,D,k,A,Se,de,Te)=>{let bt=Math.max(A,1);if(k<=bt)return;let Ls=k/bt,Ds=Math.min(Se,Math.ceil(Math.log2(Ls)*de));if(Ds<=0)return;let Cb=$p[C]??"hygiene";r.push({axis:C,category:D,kind:Cb,count:k,threshold:dt(bt),ratio:dt(Ls),extraPenalty:Ds}),o(C,Ds,`${k} ${Te} exceed pressure threshold ${dt(bt)} (${dt(Ls)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(u)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let d=Lt(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),gr(e.reactHookCandidates,"duplicated React behavior pair(s)"));let p=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(p/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let g=Lt(e.vueComposableCandidates),b=g/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(b)),gr(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let S=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(S/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let x=Lt(e.wrappers);o("wrappers",Math.min(3,x),gr(e.wrappers,"wrapper candidate(s)"));let I=Lt(e.passthroughs);o("passthroughs",Math.min(3,I),gr(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let L=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(L*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let C=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(C/10)),gr({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:C},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let C=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",C,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",d,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",g,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",x,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",I,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:i,pressure:r}}import{getHeapStatistics as AE}from"v8";var ME=64*1024*1024;function Cc(){let e=globalThis.gc;if(!e)return;let t=AE();t.heap_size_limit-t.used_heap_size<ME||e()}var OE=50,jE=75e3,BE=5e3,jp=2500,Bp=50,HE=10,hr=["overview","dead","isolated","cycles","similar","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions"],VE={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:WE(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:GE(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:zE(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:KE(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:QE(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:XE(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:YE(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:ZE(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:eT(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:tT(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:JE(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:nT(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:iT(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:rT(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:aT(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:cT(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:oT(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:sT(e,n)})};function vc(e,t,n={}){return qE(e,n.full!==!1,(i,r)=>VE[t](e,n.scope,r,i))}function qE(e,t,n){let i=Oe(e),r=lT(i,t);try{return n(i,r)}finally{ha(e,{semanticProvider:!0}),Cc()}}function Rc(e){return Mp(UE(e))}function UE(e){let t=he(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:he(e,"dead").dead,isolated:he(e,"isolated").isolated,realCycleCount:he(e,"cycles").realCycleCount,similarCount:he(e,"similar").similarCount,reactComponentDuplicates:he(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:he(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:he(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:he(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:he(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:he(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:he(e,"extract-candidates").extractCount,wrappers:he(e,"wrapper-candidates").wrappers,passthroughs:he(e,"passthrough-candidates").passthroughs,stale:he(e,"stale-abstractions").stale,drift:he(e,"drift").drift,complexity:he(e,"complexity-hotspots").complexity,gitEvidence:Hp(e,"git-evidence")?.gitEvidence??null,suppressions:Hp(e,"suppressions")?.suppressions??null}}function Hp(e,t){return e.find(n=>n.phase===t)}function he(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function WE(e,t,n){return ce(e,n,"dead",()=>{let i=Rt(e,{scope:t,...ae.dead,scanLimit:n.candidateScanLimit});return Wo(mT(e,i.symbols))})}function GE(e,t,n){return ce(e,n,"isolated",()=>{let i=pn(e,{scope:t,...ae.isolated,scanLimit:n.candidateScanLimit});return Wo(pT(e,i))})}function zE(e,t,n){return ce(e,n,"cycles",()=>mn(e,{scope:t}).filter(r=>r.kind==="real").length)}function KE(e,t,n){return ce(e,n,"similar",()=>kt(e,{scope:t,...ae.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function JE(e,t,n){return ce(e,n,"extract-candidates",()=>yn(e,{scope:t,...ae.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function QE(e,t,n){return ce(e,n,"react-component-duplicates",()=>{let i=fn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return kc(i)})}function XE(e,t,n){return ce(e,n,"react-hook-candidates",()=>{let i=gn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Up(i,gT)})}function YE(e,t,n){return ce(e,n,"react-large-component-pressure",()=>{let i=er(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return fT(i)})}function ZE(e,t,n){return ce(e,n,"vue-component-duplicates",()=>{let i=hn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return kc(i)})}function eT(e,t,n){return ce(e,n,"vue-composable-candidates",()=>{let i=bn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Up(i,hT)})}function tT(e,t,n){return ce(e,n,"vue-large-view-pressure",()=>{let i=tr(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Wo(i)})}function nT(e,t,n){return ce(e,n,"wrapper-candidates",()=>{let i=Ln(e,{scope:t,...ae.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return qp(i,bT)})}function iT(e,t,n){return ce(e,n,"passthrough-candidates",()=>{let i=kn(e,{scope:t,...ae.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return qp(i,yT)})}function rT(e,t,n){return ce(e,n,"stale-abstractions",()=>{let i=wn(e,{scope:t,...ae.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function oT(e,t){return ce(e,t,"git-evidence",()=>{let n=Do(e);if(!n)return null;let i=xn(e,void 0,{limit:t.candidateResultLimit}),r={};for(let[o,s]of n)r[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Jm(e),hiddenCoupling:{pairCount:i.findings.length,scoreCount:wc(i.findings.reduce((o,s)=>o+Vp(s),0)),top:i.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence,focusedTogether:o.focusedTogether,broadTogether:o.broadTogether,broadCommitRatio:o.broadCommitRatio,lastTogetherAt:o.lastTogetherAt,recentTogether:o.recentTogether,commitScope:o.commitScope,recency:o.recency,scoreWeight:Vp(o),subjectContext:o.subjectContext}))},fileStats:r}})}function sT(e,t){return ce(e,t,"suppressions",()=>{let n=qo(e);return{total:n.total,byCategory:{...n.byCategory}}})}function aT(e,t,n){return ce(e,n,"drift",()=>{let i=Rn(e,{scope:t,...ae.drift}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,layerViolations:i.layerViolations,direct:o,signal:s}})}function cT(e,t,n){return ce(e,n,"complexity-hotspots",()=>{let i=fr(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:!1});return{top:i.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.filter(r=>r.score>OE).length}})}function lT(e,t){let n=e.symbols>=jE||e.documents>=BE,i=t?Number.POSITIVE_INFINITY:Bp,r=t?Number.POSITIVE_INFINITY:HE;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:jp,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${jp} symbols and reported their top ${Bp} findings. Enable full mode for unbounded candidate counts.`]}}function uT(e,t){t.releaseCachesBetweenPhases&&(ha(e),Cc())}function ce(e,t,n,i){dT(n);try{return i()}finally{uT(e,t)}}function dT(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function mT(e,t){return t.filter(n=>!we(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function pT(e,t){return t.filter(n=>!we(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath))}function Wo(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function qp(e,t){return{...Wo(e),scoreCount:wc(e.reduce((i,r)=>i+t(r),0))}}function fT(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function kc(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function Up(e,t){return{...kc(e),scoreCount:wc(e.reduce((i,r)=>i+t(r),0))}}function gT(e){let t=e.sharedHooks.length>0,n=Wp({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:Gp(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function hT(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=Wp({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:Gp(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function Wp(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!Kp.has(zp(t))).length+Math.min(e.functions.length,3)}function Gp(e,t,n){let i=[...e,...t,...n].map(zp);return i.length>0&&i.every(r=>Kp.has(r))}function zp(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function bT(e){return e.actionTier==="signal"?.25:1}function yT(e){return e.actionTier==="signal"?.25:1}function Vp(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function wc(e){return Math.round(e*100)/100}var Kp=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function Lc(e,t,n,i={}){let r=B(e,t),o=B(e,n);if(!r||!o)return null;let s=new Set(Ae(e,r,{semantic:i.semantic}).map(b=>b.symbol)),a=new Set(Ae(e,o,{semantic:i.semantic}).map(b=>b.symbol)),c=[];for(let b of s)a.has(b)&&c.push(b);let l=[];for(let b of s)a.has(b)||l.push(b);let u=[];for(let b of a)s.has(b)||u.push(b);let d=new Set([...s,...a]),m=d.size>0?c.length/d.size:0,p;d.size===0?p="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?p="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?p="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?p="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?p="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?p=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:p=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let h=r.endLine-r.startLine+1,g=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:y(r.symbol),file:r.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:y(o.symbol),file:o.relativePath,loc:g},similarity:m,sharedCallees:c.map(y),uniqueToA:l.map(y),uniqueToB:u.map(y),consolidationStrategy:p}}import{readFileSync as Jp}from"fs";import{extname as ST,join as Qp}from"path";function Dc(e,t,n={}){let{context:i=0}=n,r=xT(t);if(r)return vT(e,r.filePath,r.startLine,r.endLine,i);let o=B(e,t);return o?CT(e,o,i):null}function xT(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function CT(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=Qp(e.config.projectRoot,t.relativePath),o;try{o=Jp(r,"utf-8")}catch{return null}let s=o.split(`
545
+ WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function NE(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function EE(e,t){let n=rn(e),i=0,r=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of r){let s=n.match(o);s&&(i+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}return i}function pr(e,t,n={}){let i=B(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=Bt(e,i,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=TE(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:y(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:y(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":y(c.symbol),file:c.file}))}}function TE(e,t,n,i){let r=si(Ae(e,t,{limit:30,semantic:i.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=si(qe(e,t,{limit:30,semantic:i.semantic})),s=o.length>0?o:si(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:r,consumers:s}}function mi(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=B(e,t);return o?i==="backward"?_E(e,o,r,{semantic:n.semantic!==!1}):$E(e,o,{semantic:n.semantic!==!1}):null}function _E(e,t,n,i){let r=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=Ae(e,l,{semantic:i.semantic});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),r.push({symbol:d.symbol,shortName:y(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=zn(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:y(t.symbol),direction:"backward",connectedSymbols:r}}function $E(e,t,n){let i=new Set,r=[],o=new T(e);for(let s of Bt(e,t,{semantic:n.semantic})){if(r.length>=30)break;let a=s.enclosingSymbol??je(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=zn(e,a);!c||e.isIgnored(c.relativePath)||i.has(c.symbol)||(i.add(c.symbol),r.push({symbol:c.symbol,shortName:y(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:y(t.symbol),direction:"forward",connectedSymbols:r}}function Rc(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=!AE(t),a=s?Wi(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Xi(e,t,{semantic:o}):null,l=s?mr(e,t,{semantic:o}):null,u=s?pr(e,t,{semantic:o}):null,d=s?mi(e,t,{direction:"backward",maxDepth:r,semantic:o}):null,m=s?mi(e,t,{direction:"forward",maxDepth:r,semantic:o}):null,p=s?nr(e,t,{maxDepth:i,scope:n.scope}):[],h=ir(e,t,{semantic:o}),g=Gi(e,t),b=zi(e,t),S=Ki(e,t),x=Ji(e,t),I={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||p.length>0,file:h!==null||g.length>0||b.length>0,module:S.files.length>0||S.symbols.length>0||x.length>0},L=[];!I.symbol&&!I.file&&!I.module&&L.push("No symbol, file, or module matched target.");let C=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:I,history:FE(e,C),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:p,changeSurface:h,deps:g,rdeps:b,system:S,surface:x,warnings:L}}function FE(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let i=Io(e);if(!i)return n;let r=xn(e,t,{limit:5});return{available:!0,file:t,churn:i.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:r.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence,subjectContext:o.subjectContext})),suppressionsInFile:Uo(e).byFile.get(t)??0}}function AE(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function fr(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new T(e);return We({candidates:()=>s.productionCallableDefinitions({scope:n,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>ME(a,c,i),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:r})}function ME(e,t,n){let i=e.endLine-e.startLine+1;if(i<n)return null;let r=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=o.filter(l=>l.file!==e.relativePath),a=new Set(s.map(l=>`${l.symbol}|${l.file}`)).size,c=new Set(o.map(l=>`${l.symbol}|${l.file}`)).size;return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:a,calleeCount:c,score:Math.round(i/50*(r/5)*Math.max(a/5,1)*100)/100}}function Lt(e){return e.scoreCount??e.count}function Bp(e){let t=HE(e),{breakdown:n,pressure:i}=VE(e),r=jp(n,"risk"),o=jp(n,"hygiene");return{score:Math.min(r,o),riskScore:r,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Lt(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Lt(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Lt(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null},axes:OE(e),validation:BE(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function OE(e){return{deletable:{loc:e.dead.loc+e.isolated.loc,symbols:e.dead.count+e.isolated.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,churnWeightedComplexity:jE(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function jE(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:ut(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function BE(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[u,d]of Object.entries(t))i.has(u)?r+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=i.size>0?ut(r/i.size):0,c=s>0?ut(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let h=ut(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:h,lift:c>0?ut(h/c):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:i.size>0&&c>0?ut(a/c):null,byCategory:l}}function ut(e){return Math.round(e*100)/100}function Hp(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Wo(e,t="existing shared infrastructure discount"){let n=Lt(e);return Math.abs(n-e.count)<.01?"":` (${Hp(n)} score-weighted after ${t})`}function gr(e,t){let n=Lt(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${Hp(n)} score-weighted)`}function HE(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${Wo(e.reactHookCandidates)} \u2014 extract or reuse a hook`,effort:"medium",impact:"medium",count:e.reactHookCandidates.count,locRecoverable:e.reactHookCandidates.loc}),e.reactLargeComponentPressure.count>0&&t.push({category:"Large React components",evidence:"heuristic",description:`${e.reactLargeComponentPressure.count} React component(s) concentrate JSX/behavior pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.reactLargeComponentPressure.count,locRecoverable:0}),e.vueComponentDuplicates.count>0&&t.push({category:"Duplicated Vue components",evidence:"heuristic",description:`${e.vueComponentDuplicates.count} Vue component pair(s) share template structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.vueComponentDuplicates.count,locRecoverable:e.vueComponentDuplicates.loc}),e.vueComposableCandidates.count>0&&t.push({category:"Duplicated Vue behavior",evidence:"heuristic",description:`${e.vueComposableCandidates.count} Vue component pair(s) share state/effect/request behavior${Wo(e.vueComposableCandidates)} \u2014 extract or reuse a composable`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${Wo(e.wrappers,"boundary-evidence discount")} \u2014 inline direct wrappers or review boundary signals`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove unused abstractions; review single-consumer ownership before moving or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&r.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove direct drift; review signal drift against layer ownership`,effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let r=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+Wo({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.fileB})`:"")+" \u2014 name the shared concept or enforce the sync",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var Op={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function jp(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function VE(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(C,D,k)=>{D>0&&i.push({axis:C,points:D,detail:k,kind:Op[C]??"hygiene"})},s=(C,D,k,A,Se,de,Te)=>{let bt=Math.max(A,1);if(k<=bt)return;let Ps=k/bt,Ns=Math.min(Se,Math.ceil(Math.log2(Ps)*de));if(Ns<=0)return;let Ib=Op[C]??"hygiene";r.push({axis:C,category:D,kind:Ib,count:k,threshold:ut(bt),ratio:ut(Ps),extraPenalty:Ns}),o(C,Ns,`${k} ${Te} exceed pressure threshold ${ut(bt)} (${ut(Ps)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(u)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let d=Lt(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),gr(e.reactHookCandidates,"duplicated React behavior pair(s)"));let p=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(p/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let g=Lt(e.vueComposableCandidates),b=g/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(b)),gr(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let S=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(S/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let x=Lt(e.wrappers);o("wrappers",Math.min(3,x),gr(e.wrappers,"wrapper candidate(s)"));let I=Lt(e.passthroughs);o("passthroughs",Math.min(3,I),gr(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let L=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(L*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let C=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(C/10)),gr({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:C},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let C=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",C,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",d,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",g,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",x,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",I,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:i,pressure:r}}import{getHeapStatistics as qE}from"v8";var UE=64*1024*1024;function kc(){let e=globalThis.gc;if(!e)return;let t=qE();t.heap_size_limit-t.used_heap_size<UE||e()}var WE=50,GE=75e3,zE=5e3,Vp=2500,qp=50,KE=10,hr=["overview","dead","isolated","cycles","similar","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions"],JE={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:YE(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:ZE(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:eT(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:tT(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:iT(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:rT(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:oT(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:sT(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:aT(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:cT(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:nT(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:lT(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:uT(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:dT(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:fT(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:gT(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:mT(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:pT(e,n)})};function wc(e,t,n={}){return QE(e,n.full!==!1,(i,r)=>JE[t](e,n.scope,r,i))}function QE(e,t,n){let i=Oe(e),r=hT(i,t);try{return n(i,r)}finally{Sa(e,{semanticProvider:!0}),kc()}}function Lc(e){return Bp(XE(e))}function XE(e){let t=he(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:he(e,"dead").dead,isolated:he(e,"isolated").isolated,realCycleCount:he(e,"cycles").realCycleCount,similarCount:he(e,"similar").similarCount,reactComponentDuplicates:he(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:he(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:he(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:he(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:he(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:he(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:he(e,"extract-candidates").extractCount,wrappers:he(e,"wrapper-candidates").wrappers,passthroughs:he(e,"passthrough-candidates").passthroughs,stale:he(e,"stale-abstractions").stale,drift:he(e,"drift").drift,complexity:he(e,"complexity-hotspots").complexity,gitEvidence:Up(e,"git-evidence")?.gitEvidence??null,suppressions:Up(e,"suppressions")?.suppressions??null}}function Up(e,t){return e.find(n=>n.phase===t)}function he(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function YE(e,t,n){return ce(e,n,"dead",()=>{let i=Rt(e,{scope:t,...ae.dead,scanLimit:n.candidateScanLimit});return Go(ST(e,i.symbols))})}function ZE(e,t,n){return ce(e,n,"isolated",()=>{let i=pn(e,{scope:t,...ae.isolated,scanLimit:n.candidateScanLimit});return Go(xT(e,i))})}function eT(e,t,n){return ce(e,n,"cycles",()=>mn(e,{scope:t}).filter(r=>r.kind==="real").length)}function tT(e,t,n){return ce(e,n,"similar",()=>kt(e,{scope:t,...ae.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function nT(e,t,n){return ce(e,n,"extract-candidates",()=>yn(e,{scope:t,...ae.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function iT(e,t,n){return ce(e,n,"react-component-duplicates",()=>{let i=fn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Dc(i)})}function rT(e,t,n){return ce(e,n,"react-hook-candidates",()=>{let i=gn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return zp(i,vT)})}function oT(e,t,n){return ce(e,n,"react-large-component-pressure",()=>{let i=er(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return CT(i)})}function sT(e,t,n){return ce(e,n,"vue-component-duplicates",()=>{let i=hn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Dc(i)})}function aT(e,t,n){return ce(e,n,"vue-composable-candidates",()=>{let i=bn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return zp(i,RT)})}function cT(e,t,n){return ce(e,n,"vue-large-view-pressure",()=>{let i=tr(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Go(i)})}function lT(e,t,n){return ce(e,n,"wrapper-candidates",()=>{let i=Ln(e,{scope:t,...ae.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Gp(i,kT)})}function uT(e,t,n){return ce(e,n,"passthrough-candidates",()=>{let i=kn(e,{scope:t,...ae.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Gp(i,wT)})}function dT(e,t,n){return ce(e,n,"stale-abstractions",()=>{let i=wn(e,{scope:t,...ae.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function mT(e,t){return ce(e,t,"git-evidence",()=>{let n=Io(e);if(!n)return null;let i=xn(e,void 0,{limit:t.candidateResultLimit}),r={};for(let[o,s]of n)r[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Ym(e),hiddenCoupling:{pairCount:i.findings.length,scoreCount:Ic(i.findings.reduce((o,s)=>o+Wp(s),0)),top:i.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence,focusedTogether:o.focusedTogether,broadTogether:o.broadTogether,broadCommitRatio:o.broadCommitRatio,lastTogetherAt:o.lastTogetherAt,recentTogether:o.recentTogether,commitScope:o.commitScope,recency:o.recency,scoreWeight:Wp(o),subjectContext:o.subjectContext}))},fileStats:r}})}function pT(e,t){return ce(e,t,"suppressions",()=>{let n=Uo(e);return{total:n.total,byCategory:{...n.byCategory}}})}function fT(e,t,n){return ce(e,n,"drift",()=>{let i=Rn(e,{scope:t,...ae.drift}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,layerViolations:i.layerViolations,direct:o,signal:s}})}function gT(e,t,n){return ce(e,n,"complexity-hotspots",()=>{let i=fr(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:!1});return{top:i.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.filter(r=>r.score>WE).length}})}function hT(e,t){let n=e.symbols>=GE||e.documents>=zE,i=t?Number.POSITIVE_INFINITY:qp,r=t?Number.POSITIVE_INFINITY:KE;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:Vp,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Vp} symbols and reported their top ${qp} findings. Enable full mode for unbounded candidate counts.`]}}function bT(e,t){t.releaseCachesBetweenPhases&&(Sa(e),kc())}function ce(e,t,n,i){yT(n);try{return i()}finally{bT(e,t)}}function yT(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function ST(e,t){return t.filter(n=>!we(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function xT(e,t){return t.filter(n=>!we(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath))}function Go(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function Gp(e,t){return{...Go(e),scoreCount:Ic(e.reduce((i,r)=>i+t(r),0))}}function CT(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function Dc(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function zp(e,t){return{...Dc(e),scoreCount:Ic(e.reduce((i,r)=>i+t(r),0))}}function vT(e){let t=e.sharedHooks.length>0,n=Kp({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:Jp(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function RT(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=Kp({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:Jp(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function Kp(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!Xp.has(Qp(t))).length+Math.min(e.functions.length,3)}function Jp(e,t,n){let i=[...e,...t,...n].map(Qp);return i.length>0&&i.every(r=>Xp.has(r))}function Qp(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function kT(e){return e.actionTier==="signal"?.25:1}function wT(e){return e.actionTier==="signal"?.25:1}function Wp(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function Ic(e){return Math.round(e*100)/100}var Xp=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function Pc(e,t,n,i={}){let r=B(e,t),o=B(e,n);if(!r||!o)return null;let s=new Set(Ae(e,r,{semantic:i.semantic}).map(b=>b.symbol)),a=new Set(Ae(e,o,{semantic:i.semantic}).map(b=>b.symbol)),c=[];for(let b of s)a.has(b)&&c.push(b);let l=[];for(let b of s)a.has(b)||l.push(b);let u=[];for(let b of a)s.has(b)||u.push(b);let d=new Set([...s,...a]),m=d.size>0?c.length/d.size:0,p;d.size===0?p="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?p="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?p="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?p="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?p="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?p=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:p=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let h=r.endLine-r.startLine+1,g=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:y(r.symbol),file:r.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:y(o.symbol),file:o.relativePath,loc:g},similarity:m,sharedCallees:c.map(y),uniqueToA:l.map(y),uniqueToB:u.map(y),consolidationStrategy:p}}import{readFileSync as Yp}from"fs";import{extname as LT,join as Zp}from"path";function Nc(e,t,n={}){let{context:i=0}=n,r=DT(t);if(r)return PT(e,r.filePath,r.startLine,r.endLine,i);let o=B(e,t);return o?IT(e,o,i):null}function DT(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function IT(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=Zp(e.config.projectRoot,t.relativePath),o;try{o=Yp(r,"utf-8")}catch{return null}let s=o.split(`
546
546
  `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
547
- `);return{symbol:t.symbol,shortName:y(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:i?.language??Xp(t.relativePath),source:l}}function vT(e,t,n,i,r){let o=Ie(e,t);if(!o)return null;let s=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",o);if(!s)return null;let a=Qp(e.config.projectRoot,s.relative_path),c;try{c=Jp(a,"utf-8")}catch{return null}let l=c.split(`
547
+ `);return{symbol:t.symbol,shortName:y(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:i?.language??ef(t.relativePath),source:l}}function PT(e,t,n,i,r){let o=Ie(e,t);if(!o)return null;let s=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",o);if(!s)return null;let a=Zp(e.config.projectRoot,s.relative_path),c;try{c=Yp(a,"utf-8")}catch{return null}let l=c.split(`
548
548
  `),u=Math.max(0,n-1-r),d=Math.min(l.length-1,i-1+r),m=l.slice(u,d+1).join(`
549
- `);return{symbol:`${s.relative_path}:${n}-${i}`,shortName:`${s.relative_path}:${n}-${i}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??Xp(s.relative_path),source:m}}function Xp(e){switch(ST(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function Ic(e,t={}){let{scope:n,limit:i}=t,r=new T(e),o=NT([...RT(e,n),...LT(e,r,n)]);return ET(o),i?o.slice(0,i):o}function RT(e,t){let n=[];for(let i of kT(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||ea(e,i.barrel_path)||M(e,i.barrel_path)&&io(e,i.barrel_path).length===0)continue;let r=wT(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:y(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...Zp(e,i.barrel_path)})}return n}function kT(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
549
+ `);return{symbol:`${s.relative_path}:${n}-${i}`,shortName:`${s.relative_path}:${n}-${i}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??ef(s.relative_path),source:m}}function ef(e){switch(LT(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function Ec(e,t={}){let{scope:n,limit:i}=t,r=new T(e),o=MT([...NT(e,n),..._T(e,r,n)]);return OT(o),i?o.slice(0,i):o}function NT(e,t){let n=[];for(let i of ET(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||ia(e,i.barrel_path)||M(e,i.barrel_path)&&ro(e,i.barrel_path).length===0)continue;let r=TT(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:y(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...nf(e,i.barrel_path)})}return n}function ET(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
550
550
  barrel_d.id AS barrel_doc_id,
551
551
  barrel_d.relative_path AS barrel_path,
552
552
  gs.id AS symbol_id,
@@ -576,7 +576,7 @@ ${n}`.toLowerCase(),r=Cn(i,["historical note","historical record","history note"
576
576
  -- Only function-level symbols (ending with ().), not module-level
577
577
  AND gs.symbol LIKE '%().'
578
578
  ${n}
579
- ORDER BY barrel_d.relative_path, gs.symbol`)}function wT(e,t){return e.get(`SELECT
579
+ ORDER BY barrel_d.relative_path, gs.symbol`)}function TT(e,t){return e.get(`SELECT
580
580
  SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
581
581
  SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
582
582
  FROM (
@@ -605,7 +605,7 @@ ${n}`.toLowerCase(),r=Cn(i,["historical note","historical record","history note"
605
605
  AND consumer_d.id != ?
606
606
  ${e.pathExclusionsFor("consumer_d")}
607
607
  GROUP BY consumer_d.id
608
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function LT(e,t,n){let i=[];for(let r of DT(e,n))ef(e,r,r)>0||i.push(...IT(e,t,r));return i}function DT(e,t){return j(e,{scope:t,includeIgnored:!1}).filter(n=>io(e,n).length>0||Mi(e,n).length>0)}function IT(e,t,n){let i=io(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>Yp(e,t,n,o.sourcePath)),r=Mi(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>Yp(e,t,n,o.sourcePath));return[...i,...r]}function Yp(e,t,n,i){let r=PT(t,i);return r?[{barrelFile:n,symbol:r.symbol,shortName:y(r.symbol),originalFile:i,barrelConsumers:0,directConsumers:ef(e,i,n),...Zp(e,n)}]:[]}function Zp(e,t){return ei(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function ef(e,t,n){let i=new Set;for(let r of j(e,{includeIgnored:!1}))if(r!==n)for(let o of fe(e,r))o.sourcePath===t&&i.add(r);return i.size}function PT(e,t){let n=e.definitionsForFile(t);return n.find(i=>Z(i.symbol)==="method")??n[0]??null}function NT(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function ET(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function Nc(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new T(e),s=TT(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!_T(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:tf(),callees:tf()},c=[],l=0,u=fo(e,s);for(let d of s){let m=Go(d,un(e,d).map(b=>b.file)),p=Go(d,(u.get(d.symbolId)??[]).map(b=>b.file));if(m.size===0&&p.size===0)continue;l+=1;let h=Go(d,dn(e,d).map(b=>b.file)),g=Go(d,(o.calleeMap([d],{semantic:!1}).get(d.symbolId)??[]).map(b=>b.file));nf(a.references,d,"references",h,m,c),nf(a.callees,d,"callees",g,p,c)}return c.sort((d,m)=>m.cheapOnly.length+m.oracleOnly.length-(d.cheapOnly.length+d.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Pc(l/s.length):0,scores:["references","callees"].map(d=>$T(d,a[d])),topDisagreements:c.slice(0,r)}}function tf(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function TT(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function _T(e,t){let n=t[0];if(!n)return!1;try{return ln(e,n.relativePath).availability().available}catch{return!1}}function Go(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function nf(e,t,n,i,r,o){if(i.size===0&&r.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let s=[],a=[];for(let c of i)r.has(c)?e.agreed+=1:s.push(c);for(let c of r)i.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:y(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var FT={references:!0,callees:!1};function $T(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:FT[e]&&t.cheapTotal>0?Pc(t.agreed/t.cheapTotal):null,recall:Pc(n),unverified:i}}function Pc(e){return Math.round(e*1e3)/1e3}function Ec(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o}=t,s=t.semantic!==!1,a=MT(e,AT(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:s}),c=jT(a);return r?c.slice(0,r):c}function AT(e,t){let n=ot(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>q(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>q(r)-q(i)||i.relativePath.localeCompare(r.relativePath)),Ue(n,t.scanLimit)}function MT(e,t,n){let i=new Map;for(let r of t){let o=BT(e,r,n);if(!o)continue;let s=i.get(o)??[];s.push(OT(r)),i.set(o,s)}return i}function OT(e){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e)}}function jT(e){let t=[];for(let[n,i]of e)i.length>=2&&t.push({signature:n,functions:i});return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,c)=>a+c.loc,0);return i.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function BT(e,t,n){if(n.semantic){let o=Ad(e,t);if(o)return o}let i=HT(t.documentation),r=i?UT(i):null;return r||WT(VT(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function HT(e){return Yt(Zt(e))}function VT(e,t,n,i,r){let o=M(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=zT(s,n,i,r);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,qT(u)))return u}if(u&&u.includes("("))return u}return null}function qT(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||$i(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function UT(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function WT(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${rf(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=GT(n.slice(i)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function GT(e){let t=0,n=0,i=0,r=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")i+=1;else if(c==="]")i=Math.max(0,i-1);else if(c==="<")r+=1;else if(c===">")r=Math.max(0,r-1);else if(c==="{"){if(t===0&&i===0&&r===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&i===0&&r===0)return e.slice(0,a)}return e}function zT(e,t,n,i){let r=rf(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}function rf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as mf}from"fs";import{join as d_}from"path";import KT from"better-sqlite3";var JT=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],pi=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new KT(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
608
+ )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function _T(e,t,n){let i=[];for(let r of $T(e,n))rf(e,r,r)>0||i.push(...FT(e,t,r));return i}function $T(e,t){return j(e,{scope:t,includeIgnored:!1}).filter(n=>ro(e,n).length>0||Mi(e,n).length>0)}function FT(e,t,n){let i=ro(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>tf(e,t,n,o.sourcePath)),r=Mi(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>tf(e,t,n,o.sourcePath));return[...i,...r]}function tf(e,t,n,i){let r=AT(t,i);return r?[{barrelFile:n,symbol:r.symbol,shortName:y(r.symbol),originalFile:i,barrelConsumers:0,directConsumers:rf(e,i,n),...nf(e,n)}]:[]}function nf(e,t){return ei(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function rf(e,t,n){let i=new Set;for(let r of j(e,{includeIgnored:!1}))if(r!==n)for(let o of fe(e,r))o.sourcePath===t&&i.add(r);return i.size}function AT(e,t){let n=e.definitionsForFile(t);return n.find(i=>Z(i.symbol)==="method")??n[0]??null}function MT(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function OT(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function _c(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new T(e),s=jT(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!BT(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:of(),callees:of()},c=[],l=0,u=go(e,s);for(let d of s){let m=zo(d,un(e,d).map(b=>b.file)),p=zo(d,(u.get(d.symbolId)??[]).map(b=>b.file));if(m.size===0&&p.size===0)continue;l+=1;let h=zo(d,dn(e,d).map(b=>b.file)),g=zo(d,(o.calleeMap([d],{semantic:!1}).get(d.symbolId)??[]).map(b=>b.file));sf(a.references,d,"references",h,m,c),sf(a.callees,d,"callees",g,p,c)}return c.sort((d,m)=>m.cheapOnly.length+m.oracleOnly.length-(d.cheapOnly.length+d.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Tc(l/s.length):0,scores:["references","callees"].map(d=>VT(d,a[d])),topDisagreements:c.slice(0,r)}}function of(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function jT(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function BT(e,t){let n=t[0];if(!n)return!1;try{return ln(e,n.relativePath).availability().available}catch{return!1}}function zo(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function sf(e,t,n,i,r,o){if(i.size===0&&r.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let s=[],a=[];for(let c of i)r.has(c)?e.agreed+=1:s.push(c);for(let c of r)i.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:y(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var HT={references:!0,callees:!1};function VT(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:HT[e]&&t.cheapTotal>0?Tc(t.agreed/t.cheapTotal):null,recall:Tc(n),unverified:i}}function Tc(e){return Math.round(e*1e3)/1e3}function $c(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o}=t,s=t.semantic!==!1,a=UT(e,qT(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:s}),c=GT(a);return r?c.slice(0,r):c}function qT(e,t){let n=rt(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>q(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>q(r)-q(i)||i.relativePath.localeCompare(r.relativePath)),Ue(n,t.scanLimit)}function UT(e,t,n){let i=new Map;for(let r of t){let o=zT(e,r,n);if(!o)continue;let s=i.get(o)??[];s.push(WT(r)),i.set(o,s)}return i}function WT(e){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e)}}function GT(e){let t=[];for(let[n,i]of e)i.length>=2&&t.push({signature:n,functions:i});return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,c)=>a+c.loc,0);return i.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function zT(e,t,n){if(n.semantic){let o=jd(e,t);if(o)return o}let i=KT(t.documentation),r=i?XT(i):null;return r||YT(JT(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function KT(e){return Yt(Zt(e))}function JT(e,t,n,i,r){let o=M(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=e_(s,n,i,r);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,QT(u)))return u}if(u&&u.includes("("))return u}return null}function QT(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Fi(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function XT(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function YT(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${af(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=ZT(n.slice(i)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function ZT(e){let t=0,n=0,i=0,r=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")i+=1;else if(c==="]")i=Math.max(0,i-1);else if(c==="<")r+=1;else if(c===">")r=Math.max(0,r-1);else if(c==="{"){if(t===0&&i===0&&r===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&i===0&&r===0)return e.slice(0,a)}return e}function e_(e,t,n,i){let r=af(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}function af(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as gf}from"fs";import{join as y_}from"path";import t_ from"better-sqlite3";var n_=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],pi=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new t_(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
609
609
  EXISTS (
610
610
  SELECT 1
611
611
  FROM defn_enclosing_ranges local_der
@@ -622,8 +622,8 @@ ${n}`.toLowerCase(),r=Cn(i,["historical note","historical record","history note"
622
622
  AND local_m.role = 1
623
623
  ${this.pathExclusionsFor("local_d").trimStart()}
624
624
  )
625
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>JT.flatMap(i=>[`AND ${n}.relative_path NOT LIKE '${i}/%'`,`AND ${n}.relative_path NOT LIKE '%/${i}/%'`])).join(`
626
- `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import QT from"ignore";import{readFileSync as XT,existsSync as Tc}from"fs";import{dirname as _c,isAbsolute as of,join as Fc,relative as YT,resolve as ZT}from"path";function Ut(e){let t=QT(),n=!1,i=e_(e);for(let r of i)try{let o=XT(r,"utf-8");t.add(o),n=!0}catch{}return n||t.add(t_),{isIgnored:r=>sf(t,e,r),filter:r=>r.filter(o=>!sf(t,e,o))}}function e_(e){let t=[],n=Fc(e,".gitignore");Tc(n)&&t.push(n);let i=_c(e),r=0;for(;i!==_c(i)&&r<5;){let o=Fc(i,".gitignore");if(Tc(o)&&t.push(o),Tc(Fc(i,".git")))break;i=_c(i),r++}return t}var t_=`
625
+ )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>n_.flatMap(i=>[`AND ${n}.relative_path NOT LIKE '${i}/%'`,`AND ${n}.relative_path NOT LIKE '%/${i}/%'`])).join(`
626
+ `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import i_ from"ignore";import{readFileSync as r_,existsSync as Fc}from"fs";import{dirname as Ac,isAbsolute as cf,join as Mc,relative as o_,resolve as s_}from"path";function Ut(e){let t=i_(),n=!1,i=a_(e);for(let r of i)try{let o=r_(r,"utf-8");t.add(o),n=!0}catch{}return n||t.add(c_),{isIgnored:r=>lf(t,e,r),filter:r=>r.filter(o=>!lf(t,e,o))}}function a_(e){let t=[],n=Mc(e,".gitignore");Fc(n)&&t.push(n);let i=Ac(e),r=0;for(;i!==Ac(i)&&r<5;){let o=Mc(i,".gitignore");if(Fc(o)&&t.push(o),Fc(Mc(i,".git")))break;i=Ac(i),r++}return t}var c_=`
627
627
  # Dependencies
628
628
  node_modules/
629
629
  vendor/
@@ -680,51 +680,52 @@ Thumbs.db
680
680
 
681
681
  # Type definitions (often noise in queries)
682
682
  *.d.ts
683
- `;function sf(e,t,n){let i=n_(t,n);if(!i)return!1;try{return e.ignores(i)}catch{return!1}}function n_(e,t){if(!t||t===".")return null;if(!of(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=of(t)?t:ZT(e,t),i=YT(e,n).replaceAll("\\","/");return!i||i==="."||i.startsWith("..")?null:i}import{readFileSync as i_,writeFileSync as cf,existsSync as zo,mkdirSync as r_}from"fs";import{join as mt,resolve as af}from"path";import{createHash as o_}from"crypto";import{homedir as s_}from"os";var br=".scipquery.json",a_={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]},c_=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"];function tt(e){let t=mt(e,br);if(!zo(t))return{};try{let n=i_(t,"utf-8");return JSON.parse(n)}catch(n){let i=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${br} at ${t}: ${i}`,{cause:n}):new Error(`unable to read ${br} at ${t}: ${i}`,{cause:n})}}function fi(e,t={}){let n=[],i=new Set(c_);for(let[o,s]of(e.languages??[]).entries())i.has(s)||n.push({level:"error",path:`languages[${o}]`,message:`Unsupported language: ${s}`});if(e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<=0&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be greater than 0."}),e.locality!==void 0)if(!u_(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let o=e.locality.architecturalBoundarySegments;if(o!==void 0)if(!Array.isArray(o))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[s,a]of o.entries()){let c=`locality.architecturalBoundarySegments[${s}]`;typeof a!="string"||a.trim()===""?n.push({level:"error",path:c,message:"Boundary segment must be a non-empty string."}):(a.includes("/")||a.includes("\\"))&&n.push({level:"error",path:c,message:"Boundary segment must be a single folder name, not a path."})}}if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[o,s]of(e.declaredCouplings??[]).entries()){let a=`declaredCouplings[${o}]`;if((!s.name||s.name.trim()==="")&&n.push({level:"error",path:`${a}.name`,message:"Declared coupling name is required."}),!Array.isArray(s.files)||s.files.length<2)n.push({level:"error",path:`${a}.files`,message:"Declared coupling needs at least two files."});else for(let[c,l]of s.files.entries())!l||l.trim()===""?n.push({level:"error",path:`${a}.files[${c}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!zo(mt(t.projectRoot,l))&&n.push({level:"warning",path:`${a}.files[${c}]`,message:`Declared coupling file does not exist: ${l}`});s.reason!==void 0&&s.reason.trim()===""&&n.push({level:"error",path:`${a}.reason`,message:"Declared coupling reason cannot be blank."})}let r=t.now??new Date;for(let[o,s]of(e.suppressions??[]).entries()){let a=`suppressions[${o}]`;if((!s.reason||s.reason.trim()==="")&&n.push({level:"error",path:`${a}.reason`,message:"Suppression reason is required."}),!s.id&&!s.check&&n.push({level:"error",path:a,message:"Suppression must include id or check."}),s.file!==void 0&&(s.file.trim()===""?n.push({level:"error",path:`${a}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!zo(mt(t.projectRoot,s.file))&&n.push({level:"warning",path:`${a}.file`,message:`Suppression file does not exist: ${s.file}`})),s.expiresAt){let c=Date.parse(s.expiresAt);Number.isNaN(c)?n.push({level:"error",path:`${a}.expiresAt`,message:"Must be an ISO date string."}):c<=r.getTime()&&n.push({level:"warning",path:`${a}.expiresAt`,message:"Suppression has expired."})}}return n}function lf(e){return{...a_,...e.watch}}function l_(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return $c(n);if(t?.dbPath)return $c(af(e,t.dbPath));let r=process.env.XDG_CACHE_HOME||mt(s_(),".cache"),o=o_("sha256").update(af(e)).digest("hex").slice(0,12),s=mt(r,"scip-query","projects",o);return $c(s)}function Wt(e,t){let n=l_(e,t);return{cacheDir:n,dbPath:mt(n,"index.db"),indexPath:mt(n,"index.scip"),metaPath:mt(n,"meta.json")}}function uf(e,t){let n=mt(e,br);return zo(n)||cf(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
684
- `),n}function df(e,t){let n=mt(e,br),i=tt(e),r={...i,suppressions:[...i.suppressions??[],t]},o=fi(r,{projectRoot:e}).filter(s=>s.level==="error");if(o.length>0){let s=o.map(a=>`${a.path}: ${a.message}`).join("; ");throw new Error(`invalid suppression: ${s}`)}return cf(n,JSON.stringify(r,null,2)+`
685
- `),{path:n,suppressionCount:r.suppressions?.length??0}}function $c(e){return r_(e,{recursive:!0}),e}function u_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function be(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function gi(e=be()){let t=tt(e),n=Wt(e,t),i=process.env.SCIP_QUERY_INDEX_DB??(mf(n.dbPath)?n.dbPath:d_(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:i}}function Ac(e){return gi(e).dbPath}function m_(){let{projectRoot:e,config:t,paths:n,dbPath:i}=gi();mf(i)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let r={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality},o=Ut(e);return new pi(r,o)}function pt(e){let t=m_();try{return e(t)}finally{t.close()}}function Mc(e,t){return t.concat([e])}function hi(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function pf(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;default:return p_(e)}}function p_(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as f_}from"child_process";function Oc(e){let t=f_(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,encoding:"utf8",maxBuffer:e.maxBuffer??10485760});if(t.status!==0){let n=t.stderr.trim();throw new Error(`${e.label} failed${n?`:
686
- ${n}`:""}`)}return JSON.parse(t.stdout)}function ff(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Me(e){return e+1}function ve(e,t){return`${Me(e)}-${Me(t)}`}function ye(e,t,n){return`${e}:${ve(t,n)}`}function Ko(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var P={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(o),i=o),console.log(t(r))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let i of n.rows)console.log(i)}},table(e,t,n){console.log(` ${e.join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(r)}};var h_=g_(import.meta.url),{version:Jo}=x_(),Qo="__health-phase",Xo="__diff-impact-batch",b_=10,y_=75e3,S_=5e3,gf=2500;function x_(){for(let e of["../package.json","../../package.json"])try{return h_(e)}catch{}return{version:"0.0.0"}}function bi(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
687
- `)}function Bc(e){let t=Oe(e);return t.symbols>=y_||t.documents>=S_}function bf(e,t,n,i={}){return Bc(e)?n?(i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(i.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${gf} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:gf,semantic:!1}):{semantic:!0}}function Yo(e){let t=hr.map(n=>C_(n,e));return Rc(t)}function C_(e,t){let n=process.argv[1]??hf(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Oc({cliPath:n,command:Qo,args:i,label:`Health phase "${e}"`})}function yf(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
683
+ `;function lf(e,t,n){let i=l_(t,n);if(!i)return!1;try{return e.ignores(i)}catch{return!1}}function l_(e,t){if(!t||t===".")return null;if(!cf(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=cf(t)?t:s_(e,t),i=o_(e,n).replaceAll("\\","/");return!i||i==="."||i.startsWith("..")?null:i}import{readFileSync as u_,writeFileSync as df,existsSync as Ko,mkdirSync as d_}from"fs";import{join as dt,resolve as uf}from"path";import{createHash as m_}from"crypto";import{homedir as p_}from"os";var br=".scipquery.json",f_={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]},g_=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"];function et(e){let t=dt(e,br);if(!Ko(t))return{};try{let n=u_(t,"utf-8");return JSON.parse(n)}catch(n){let i=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${br} at ${t}: ${i}`,{cause:n}):new Error(`unable to read ${br} at ${t}: ${i}`,{cause:n})}}function fi(e,t={}){let n=[],i=new Set(g_);for(let[o,s]of(e.languages??[]).entries())i.has(s)||n.push({level:"error",path:`languages[${o}]`,message:`Unsupported language: ${s}`});if(e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<=0&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be greater than 0."}),e.locality!==void 0)if(!b_(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let o=e.locality.architecturalBoundarySegments;if(o!==void 0)if(!Array.isArray(o))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[s,a]of o.entries()){let c=`locality.architecturalBoundarySegments[${s}]`;typeof a!="string"||a.trim()===""?n.push({level:"error",path:c,message:"Boundary segment must be a non-empty string."}):(a.includes("/")||a.includes("\\"))&&n.push({level:"error",path:c,message:"Boundary segment must be a single folder name, not a path."})}}if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[o,s]of(e.declaredCouplings??[]).entries()){let a=`declaredCouplings[${o}]`;if((!s.name||s.name.trim()==="")&&n.push({level:"error",path:`${a}.name`,message:"Declared coupling name is required."}),!Array.isArray(s.files)||s.files.length<2)n.push({level:"error",path:`${a}.files`,message:"Declared coupling needs at least two files."});else for(let[c,l]of s.files.entries())!l||l.trim()===""?n.push({level:"error",path:`${a}.files[${c}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Ko(dt(t.projectRoot,l))&&n.push({level:"warning",path:`${a}.files[${c}]`,message:`Declared coupling file does not exist: ${l}`});s.reason!==void 0&&s.reason.trim()===""&&n.push({level:"error",path:`${a}.reason`,message:"Declared coupling reason cannot be blank."})}let r=t.now??new Date;for(let[o,s]of(e.suppressions??[]).entries()){let a=`suppressions[${o}]`;if((!s.reason||s.reason.trim()==="")&&n.push({level:"error",path:`${a}.reason`,message:"Suppression reason is required."}),!s.id&&!s.check&&n.push({level:"error",path:a,message:"Suppression must include id or check."}),s.file!==void 0&&(s.file.trim()===""?n.push({level:"error",path:`${a}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Ko(dt(t.projectRoot,s.file))&&n.push({level:"warning",path:`${a}.file`,message:`Suppression file does not exist: ${s.file}`})),s.expiresAt){let c=Date.parse(s.expiresAt);Number.isNaN(c)?n.push({level:"error",path:`${a}.expiresAt`,message:"Must be an ISO date string."}):c<=r.getTime()&&n.push({level:"warning",path:`${a}.expiresAt`,message:"Suppression has expired."})}}return n}function mf(e){return{...f_,...e.watch}}function h_(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return Oc(n);if(t?.dbPath)return Oc(uf(e,t.dbPath));let r=process.env.XDG_CACHE_HOME||dt(p_(),".cache"),o=m_("sha256").update(uf(e)).digest("hex").slice(0,12),s=dt(r,"scip-query","projects",o);return Oc(s)}function Wt(e,t){let n=h_(e,t);return{cacheDir:n,dbPath:dt(n,"index.db"),indexPath:dt(n,"index.scip"),metaPath:dt(n,"meta.json")}}function pf(e,t){let n=dt(e,br);return Ko(n)||df(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
684
+ `),n}function ff(e,t){let n=dt(e,br),i=et(e),r={...i,suppressions:[...i.suppressions??[],t]},o=fi(r,{projectRoot:e}).filter(s=>s.level==="error");if(o.length>0){let s=o.map(a=>`${a.path}: ${a.message}`).join("; ");throw new Error(`invalid suppression: ${s}`)}return df(n,JSON.stringify(r,null,2)+`
685
+ `),{path:n,suppressionCount:r.suppressions?.length??0}}function Oc(e){return d_(e,{recursive:!0}),e}function b_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function be(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function gi(e=be()){let t=et(e),n=Wt(e,t),i=process.env.SCIP_QUERY_INDEX_DB??(gf(n.dbPath)?n.dbPath:y_(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:i}}function jc(e){return gi(e).dbPath}function S_(){let{projectRoot:e,config:t,paths:n,dbPath:i}=gi();gf(i)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let r={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality},o=Ut(e);return new pi(r,o)}function mt(e){let t=S_();try{return e(t)}finally{t.close()}}function Bc(e,t){return t.concat([e])}function hi(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function hf(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;default:return x_(e)}}function x_(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as C_}from"child_process";function Hc(e){let t=C_(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,encoding:"utf8",maxBuffer:e.maxBuffer??10485760});if(t.status!==0){let n=t.stderr.trim();throw new Error(`${e.label} failed${n?`:
686
+ ${n}`:""}`)}return JSON.parse(t.stdout)}function bf(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Me(e){return e+1}function ve(e,t){return`${Me(e)}-${Me(t)}`}function ye(e,t,n){return`${e}:${ve(t,n)}`}function Jo(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var P={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(o),i=o),console.log(t(r))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let i of n.rows)console.log(i)}},table(e,t,n){console.log(` ${e.join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(r)}};var R_=v_(import.meta.url),{version:Qo}=D_(),Xo="__health-phase",Yo="__diff-impact-batch",k_=10,w_=75e3,L_=5e3,yf=2500;function D_(){for(let e of["../package.json","../../package.json"])try{return R_(e)}catch{}return{version:"0.0.0"}}function bi(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
687
+ `)}function qc(e){let t=Oe(e);return t.symbols>=w_||t.documents>=L_}function xf(e,t,n,i={}){return qc(e)?n?(i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(i.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${yf} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:yf,semantic:!1}):{semantic:!0}}function Zo(e){let t=hr.map(n=>I_(n,e));return Lc(t)}function I_(e,t){let n=process.argv[1]??Sf(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Hc({cliPath:n,command:Xo,args:i,label:`Health phase "${e}"`})}function Cf(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
688
688
  Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (validated predictors: graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
689
689
  `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${hi(e.overview.indexSizeBytes)}
690
- `),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let i of e.warnings)console.log(` ${i}`);console.log("")}console.log(" Findings:");let n=e.findings;if(n.deadSymbols>0&&console.log(` Dead code: ${n.deadSymbols} symbols (${n.deadLoc} LOC)`),n.isolatedSymbols>0&&console.log(` Isolated symbols: ${n.isolatedSymbols} (${n.isolatedLoc} LOC)`),n.cycles>0&&console.log(` Circular deps: ${n.cycles}`),n.similarPairs>0&&console.log(` Similar pairs: ${n.similarPairs}`),n.reactComponentDuplicatePairs>0&&console.log(` React components: ${n.reactComponentDuplicatePairs} duplicate pair(s)`),n.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${jc(n.reactHookCandidatePairs,n.reactHookCandidateScoreCount)} candidate pair(s)`),n.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${n.reactLargeComponentPressureFiles} component(s)`),n.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${n.vueComponentDuplicatePairs} duplicate pair(s)`),n.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${jc(n.vueComposableCandidatePairs,n.vueComposableCandidateScoreCount)} candidate pair(s)`),n.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${n.vueLargeViewPressureFiles} file(s)`),n.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${jc(n.wrappers,n.wrapperScoreCount)}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
690
+ `),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let i of e.warnings)console.log(` ${i}`);console.log("")}console.log(" Findings:");let n=e.findings;if(n.deadSymbols>0&&console.log(` Dead code: ${n.deadSymbols} symbols (${n.deadLoc} LOC)`),n.isolatedSymbols>0&&console.log(` Isolated symbols: ${n.isolatedSymbols} (${n.isolatedLoc} LOC)`),n.cycles>0&&console.log(` Circular deps: ${n.cycles}`),n.similarPairs>0&&console.log(` Similar pairs: ${n.similarPairs}`),n.reactComponentDuplicatePairs>0&&console.log(` React components: ${n.reactComponentDuplicatePairs} duplicate pair(s)`),n.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${Vc(n.reactHookCandidatePairs,n.reactHookCandidateScoreCount)} candidate pair(s)`),n.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${n.reactLargeComponentPressureFiles} component(s)`),n.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${n.vueComponentDuplicatePairs} duplicate pair(s)`),n.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${Vc(n.vueComposableCandidatePairs,n.vueComposableCandidateScoreCount)} candidate pair(s)`),n.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${n.vueLargeViewPressureFiles} file(s)`),n.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${Vc(n.wrappers,n.wrapperScoreCount)}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
691
691
  Prioritized Actions (highest impact + lowest effort first):`);for(let i=0;i<e.actions.length;i++){let r=e.actions[i],o=r.locRecoverable>0?` (~${r.locRecoverable} LOC recoverable)`:"";console.log(` ${i+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
692
- Top Complexity Hotspots:`);for(let i of e.topComplexity)console.log(` ${i.score.toFixed(1).padStart(6)} ${i.symbol}`)}if(k_(e),R_(e),e.scoreBreakdown.length>0){console.log(`
692
+ Top Complexity Hotspots:`);for(let i of e.topComplexity)console.log(` ${i.score.toFixed(1).padStart(6)} ${i.symbol}`)}if(E_(e),N_(e),e.scoreBreakdown.length>0){console.log(`
693
693
  Score Breakdown (100 minus the following):`);for(let i of e.scoreBreakdown)console.log(` -${String(i.points).padStart(2)} ${i.axis}: ${i.detail}`)}e.actions.length===0&&console.log(`
694
- No issues found. Codebase is clean.`)}function jc(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${v_(t)} score-weighted)`}function v_(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function R_(e){if(e.pressure.length!==0){console.log(`
695
- Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function k_(e){let t=e.axes;if(console.log(`
696
- Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`)}}function Sf(e){return pt(t=>{let n=ut(t,{base:e.base});if(n.note)return ci(t,{base:e.base});if(n.changedFiles.length===0)return ci(t,{base:e.base});let i=[];for(let r of ff(n.changedFiles,b_))i.push(w_(r,e));return No(n.changedFiles,i)})}function w_(e,t){let n=process.argv[1]??hf(import.meta.url),i=[];return t.base&&i.push("--base",t.base),Oc({cliPath:n,command:Xo,args:i,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function xf(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),P.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
697
- Affected consumer files:`),P.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var Zo=Mc,v=(e=>parseInt(e,10)),es=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),nt=parseFloat,Hc=parseInt;function f(e,t,n,...i){return i.length>0?{flags:e,description:t,parser:n,defaultValue:i[0]}:{flags:e,description:t,parser:n}}function Vc(){return f("--json","Output as JSON for programmatic consumption")}function _(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,Vc()]}function w(e,t=[]){return{category:e,examples:t}}import{execFileSync as A0}from"child_process";import{existsSync as vr,mkdirSync as M0,readFileSync as O0,writeFileSync as eg}from"fs";import{homedir as j0}from"os";import{dirname as B0,join as Ci}from"path";import{existsSync as If,readFileSync as z_}from"fs";import{execFileSync as L_}from"child_process";import{existsSync as D_,readdirSync as vf}from"fs";import{extname as Rf,join as kf}from"path";var I_=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),P_=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Dt(e){let t=[],n=N_(e),i=F_(e);for(let r of P_){if(E_(e,r.files)){t.push(r.language);continue}if(T_(n,r.globs)){t.push(r.language);continue}A_(i,r.extensions)&&t.push(r.language)}return t.includes("typescript")&&Cf(t,"javascript"),t.includes("cpp")&&!i.has(".c")&&Cf(t,"c"),t}function N_(e){try{return vf(e)}catch{return[]}}function E_(e,t){return t?.length?t.some(n=>D_(kf(e,n))):!1}function T_(e,t){return t?.length?e.some(n=>t.some(i=>__(n,i))):!1}function __(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,i]=t.split("*");return e.startsWith(n??"")&&e.endsWith(i??"")}function F_(e){let t=$_(e);if(t)return t;let n=new Set,i=[e];for(;i.length>0;){let r=i.pop();if(!r)continue;let o;try{o=vf(r,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=kf(r,s.name);if(s.isDirectory()){I_.has(s.name)||i.push(a);continue}let c=Rf(s.name).toLowerCase();c&&n.add(c)}}return n}function $_(e){try{let t=L_("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let i of t.split(`
698
- `)){if(!i)continue;let r=Rf(i).toLowerCase();r&&n.add(r)}return n}catch{return null}}function A_(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Cf(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{execFileSync as M_}from"child_process";import{createHash as O_}from"crypto";import{readdirSync as j_,readFileSync as B_}from"fs";import{join as Lf}from"path";function wf(e){return(V_(e)??q_(e)).filter(t=>t&&!Df(t)).sort()}function In(e,t={}){return(t.language?wf(e).filter(i=>H_(i,t.language,t.markerFiles)):wf(e)).map(i=>{let r=Lf(e,i);try{let o=B_(r);return{path:i,size:o.byteLength,hash:O_("sha256").update(o).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function H_(e,t,n){let i=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(i)||W_.has(i))return!0;let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(G_[t]??[]).includes(r)}function V_(e){try{return M_("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
699
- `).filter(Boolean)}catch{return null}}function q_(e){let t=[],n=[""];for(;n.length>0;){let i=n.pop(),r=i?Lf(e,i):e,o;try{o=j_(r,{withFileTypes:!0})}catch{continue}for(let s of o){let a=i?`${i}/${s.name}`:s.name;if(s.isDirectory()){Df(a)||n.push(a);continue}t.push(a)}}return t}function Df(e){return e.split("/").some(n=>U_.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var U_=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),W_=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock"]),G_={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"]};function yi(e,t,n){let i=new Date().toISOString();if(!If(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!If(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let r=JSON.parse(z_(n.metaPath,"utf-8")),o=t.languages??Dt(e),s=K_(e,o,t),a=Array.isArray(r.indexedLanguages)?[...r.indexedLanguages].sort():[],c=(r.version===2||r.version===3)&&r.status==="complete"&&JSON.stringify(r.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages);return{state:c?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:r.updatedAt,reason:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:c?void 0:"Run: scip-query reindex"}}catch(r){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${r instanceof Error?r.message:String(r)}`,remedy:"Run: scip-query reindex"}}}function K_(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces===!0,files:In(e)}}import{execFileSync as D0}from"child_process";import{existsSync as Pf,readdirSync as J_}from"fs";import{join as qc}from"path";var Q_={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let i=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Nf(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Nf(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=qc(e,"vendor","bin","scip-php"),i=qc(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Pf(i)?i:Pf(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Pn(e){return Q_[e]}function Nf(e,t){let n;try{n=J_(e)}catch{return null}for(let i of n)if(t.some(r=>i.endsWith(r)))return qc(e,i);return null}import{execFileSync as Wc}from"child_process";import{existsSync as Uc,readFileSync as e0}from"fs";import{createRequire as t0}from"module";import{platform as n0}from"os";import{dirname as Ef,join as ts}from"path";import{execFileSync as X_}from"child_process";import{platform as Y_}from"os";var Z_=Y_()==="win32";function Ge(e){let t=Z_?"where":"which";try{return X_(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var i0=t0(import.meta.url);function Gc(e){return[e.indexerBinary,...e.binaryAliases??[]]}function ns(e){let t=Gc(e);return t.length===1?t[0]:t.join(" or ")}function Si(e){for(let t of Gc(e))if(Ge(t))return t;return o0(e)}function Tf(e){return Si(e)!==null||r0(e)}function r0(e){return _f(e)!==null}function o0(e){let t=_f(e);if(!t)return null;let i=JSON.parse(e0(t,"utf8")).bin;if(!i)return null;if(typeof i=="string")return ts(Ef(t),i);for(let r of Gc(e)){let o=i[r];if(o)return ts(Ef(t),o)}return null}function _f(e){if(!e.bundledNpmPackage)return null;try{return i0.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function zc(e,t){for(let n of e.projectLocalBinaries??[]){let i=ts(t,n);if(Uc(i))return i}return null}function s0(e,t){return zc(e,t)??Si(e)}function Ff(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Kc(n,t))return t;let i=$f(n,t);return i?{...t,DOTNET_ROOT:i}:t}function is(e,t){let n=ns(e),i=t?s0(e,t):Si(e);if(!i)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:i};let r=a0(i);return{language:e.language,binaryLabel:n,installed:!0,runnable:r.runnable,resolvedBinary:i,installUrl:e.installUrl,note:r.note}}function rs(e,t){let n=e.installMethods,i=ns(e);if(!n?.length)return t(`No auto-install method available for ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let r of n)if(Ge(r.prerequisite)){t(`Installing ${i} via ${r.label}...`);try{Wc(r.binary,r.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Si(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${i} via ${r.label}${s}`),!0}t(`${r.label} command completed but ${i} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${r.label} install failed: ${s}`)}}return t(`Could not auto-install ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function a0(e){if(Kc(e,process.env))return{runnable:!0};let t=$f(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Af(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function $f(e,t){for(let n of Af(t))if(Kc(e,{...t,DOTNET_ROOT:n}))return n;return null}function Af(e){let t=[],n=e.DOTNET_ROOT;if(n&&Uc(n)&&t.push(n),n0()==="darwin"&&Ge("brew"))try{let i=Wc("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),r=ts(i,"libexec");Uc(r)&&!t.includes(r)&&t.push(r)}catch{}return t}function Kc(e,t){try{return Wc(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import{createRequire as c0}from"module";var l0=c0(import.meta.url);function Mf(e,t=[]){let n=u0(),i=sa(e,t),r=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i,reason:"ts-morph is not installed"}}function u0(){try{return l0.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as xi,spawnSync as Hf}from"child_process";import{existsSync as It,mkdtempSync as Vf,readFileSync as d0,readdirSync as m0,rmSync as qf,symlinkSync as p0,writeFileSync as f0}from"fs";import{tmpdir as Uf}from"os";import{join as ze}from"path";var g0=3e5,h0=12;function Jc(e,t,n={}){let i=Qc(e);if(i.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let r=b0(t,i),o=n.timeoutMs??g0,s=x0(e,t),a=Vf(ze(Uf(),"scip-cleanup-verify-")),c=[],l=new Set;try{xi("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),C0(e,a);for(let u of i)for(let d of Bf(u,a,o).errorKeys)l.add(d);for(let u of t.batches){Gf(a,u);let d=[];for(let m of i){let p=Bf(m,a,o);d.push(...p.rawErrors.filter(h=>!l.has(Wf(h))))}if(d.length===0)c.push({depth:u.depth,status:"verified"});else{c.push({depth:u.depth,status:"failed",errors:d.slice(0,h0)});break}}}finally{try{xi("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{qf(a,{recursive:!0,force:!0})}}return{checkers:i.map(u=>u.label),uncoveredFiles:r,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function b0(e,t){let n=new Set(t.flatMap(r=>r.coversExtensions));return[...new Set(e.batches.flatMap(r=>r.entries.map(o=>o.file)))].filter(r=>{let o=r.slice(r.lastIndexOf("."));return!n.has(o)}).sort()}function Wf(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Of=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function Qc(e){let t=[];if(It(ze(e,"tsconfig.json"))){let n=ze(e,"node_modules",".bin","tsc");t.push(It(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Of}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Of})}if(It(ze(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>It(ze(e,n)))){let n=y0();n&&t.push(n)}for(let n of S0(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--manifest-path",n],coversExtensions:[".rs"],env:{...process.env,CARGO_TARGET_DIR:ze(e,n,"..","target")}});return t}function y0(){return jf("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:jf("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function jf(e){try{return Hf(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function S0(e){let t=[];if(It(ze(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=m0(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||It(ze(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function x0(e,t){let n;try{n=xi("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let i=new Set(n.split(`
700
- `).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>i.has(o)).sort()}function C0(e,t){for(let n of["node_modules"]){let i=ze(e,n),r=ze(t,n);if(It(i)&&!It(r))try{p0(i,r,"junction")}catch{}}}function Gf(e,t){let n=new Map;for(let i of t.entries){let r=n.get(i.file)??[];r.push({start:i.startLine,end:i.endLine}),n.set(i.file,r)}for(let[i,r]of n){let o=ze(e,i);It(o)&&f0(o,v0(d0(o,"utf-8"),r,{rust:i.endsWith(".rs")}))}}function Xc(e,t){for(let n of t)Gf(e,n)}function zf(e,t){let n=Vf(ze(Uf(),"scip-cleanup-patch-"));try{return xi("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),Xc(n,t),xi("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{xi("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{qf(n,{recursive:!0,force:!0})}}}function Yc(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(i=>i.depth===t.batch);return n?[n]:[]}return[...e.batches]}function Zc(e,t,n={}){let i=[];e.checkers.length===0&&i.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&i.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&i.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let r=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)r.has(o.depth)||i.push(`Batch ${o.depth} is not compiler-verified.`);return i}function v0(e,t,n={}){let i=e.split(`
701
- `),r=(n.rust===!0?R0(e):rn(e)).split(`
702
- `),o=new Set;for(let s of t){let a=k0(i,s.start),c=L0(r,a,Math.min(s.end,i.length-1));for(let l=a;l<=c&&l<i.length;l++)o.add(l)}return i.filter((s,a)=>!o.has(a)).join(`
703
- `)}function R0(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function k0(e,t){let n=t;for(;n>0;){let i=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(i))n-=1;else break}return n}var w0=200;function L0(e,t,n){let i=0;for(let r=t;r<e.length;r++){for(let o of e[r]??"")o==="("||o==="["||o==="{"?i+=1:(o===")"||o==="]"||o==="}")&&(i-=1);if(r>=n&&i<=0)return r;if(r-n>w0)break}return n}function Bf(e,t,n){let i=Hf(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(i.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${i.stdout??""}
694
+ No issues found. Codebase is clean.`)}function Vc(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${P_(t)} score-weighted)`}function P_(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function N_(e){if(e.pressure.length!==0){console.log(`
695
+ Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function E_(e){let t=e.axes;if(console.log(`
696
+ Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`)}}function vf(e){return mt(t=>{let n=lt(t,{base:e.base});if(n.note)return ci(t,{base:e.base});if(n.changedFiles.length===0)return ci(t,{base:e.base});let i=[];for(let r of bf(n.changedFiles,k_))i.push(T_(r,e));return Eo(n.changedFiles,i)})}function T_(e,t){let n=process.argv[1]??Sf(import.meta.url),i=[];return t.base&&i.push("--base",t.base),Hc({cliPath:n,command:Yo,args:i,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function Rf(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),P.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
697
+ Affected consumer files:`),P.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var es=Bc,v=(e=>parseInt(e,10)),ts=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),tt=parseFloat,Uc=parseInt;function f(e,t,n,...i){return i.length>0?{flags:e,description:t,parser:n,defaultValue:i[0]}:{flags:e,description:t,parser:n}}function Wc(){return f("--json","Output as JSON for programmatic consumption")}function _(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,Wc()]}function w(e,t=[]){return{category:e,examples:t}}import{execFileSync as q0}from"child_process";import{existsSync as vr,mkdirSync as U0,readFileSync as W0,writeFileSync as ig}from"fs";import{homedir as G0}from"os";import{dirname as z0,join as Ci}from"path";import{existsSync as Ef,readFileSync as e0}from"fs";import{execFileSync as __}from"child_process";import{existsSync as $_,readdirSync as wf}from"fs";import{extname as Lf,join as Df}from"path";var F_=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),A_=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Dt(e){let t=[],n=M_(e),i=H_(e);for(let r of A_){if(O_(e,r.files)){t.push(r.language);continue}if(j_(n,r.globs)){t.push(r.language);continue}q_(i,r.extensions)&&t.push(r.language)}return t.includes("typescript")&&kf(t,"javascript"),t.includes("cpp")&&!i.has(".c")&&kf(t,"c"),t}function M_(e){try{return wf(e)}catch{return[]}}function O_(e,t){return t?.length?t.some(n=>$_(Df(e,n))):!1}function j_(e,t){return t?.length?e.some(n=>t.some(i=>B_(n,i))):!1}function B_(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,i]=t.split("*");return e.startsWith(n??"")&&e.endsWith(i??"")}function H_(e){let t=V_(e);if(t)return t;let n=new Set,i=[e];for(;i.length>0;){let r=i.pop();if(!r)continue;let o;try{o=wf(r,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=Df(r,s.name);if(s.isDirectory()){F_.has(s.name)||i.push(a);continue}let c=Lf(s.name).toLowerCase();c&&n.add(c)}}return n}function V_(e){try{let t=__("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let i of t.split(`
698
+ `)){if(!i)continue;let r=Lf(i).toLowerCase();r&&n.add(r)}return n}catch{return null}}function q_(e,t){return t?.length?t.some(n=>e.has(n)):!1}function kf(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{execFileSync as U_}from"child_process";import{createHash as W_}from"crypto";import{readdirSync as G_,readFileSync as z_}from"fs";import{join as Pf}from"path";function If(e){return(J_(e)??Q_(e)).filter(t=>t&&!Nf(t)).sort()}function In(e,t={}){return(t.language?If(e).filter(i=>K_(i,t.language,t.markerFiles)):If(e)).map(i=>{let r=Pf(e,i);try{let o=z_(r);return{path:i,size:o.byteLength,hash:W_("sha256").update(o).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function K_(e,t,n){let i=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(i)||Y_.has(i))return!0;let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(Z_[t]??[]).includes(r)}function J_(e){try{return U_("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
699
+ `).filter(Boolean)}catch{return null}}function Q_(e){let t=[],n=[""];for(;n.length>0;){let i=n.pop(),r=i?Pf(e,i):e,o;try{o=G_(r,{withFileTypes:!0})}catch{continue}for(let s of o){let a=i?`${i}/${s.name}`:s.name;if(s.isDirectory()){Nf(a)||n.push(a);continue}t.push(a)}}return t}function Nf(e){return e.split("/").some(n=>X_.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var X_=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),Y_=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock"]),Z_={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"]};function yi(e,t,n){let i=new Date().toISOString();if(!Ef(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Ef(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let r=JSON.parse(e0(n.metaPath,"utf-8")),o=t.languages??Dt(e),s=t0(e,o,t),a=Array.isArray(r.indexedLanguages)?[...r.indexedLanguages].sort():[],c=(r.version===2||r.version===3)&&r.status==="complete"&&JSON.stringify(r.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages);return{state:c?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:r.updatedAt,reason:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:c?void 0:"Run: scip-query reindex"}}catch(r){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${r instanceof Error?r.message:String(r)}`,remedy:"Run: scip-query reindex"}}}function t0(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces===!0,files:In(e)}}import{execFileSync as $0}from"child_process";import{existsSync as Tf,readdirSync as n0}from"fs";import{join as Gc}from"path";var i0={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let i=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",_f(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",_f(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=Gc(e,"vendor","bin","scip-php"),i=Gc(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Tf(i)?i:Tf(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Pn(e){return i0[e]}function _f(e,t){let n;try{n=n0(e)}catch{return null}for(let i of n)if(t.some(r=>i.endsWith(r)))return Gc(e,i);return null}import{execFileSync as Kc}from"child_process";import{existsSync as zc,readFileSync as a0}from"fs";import{createRequire as c0}from"module";import{platform as l0}from"os";import{dirname as $f,join as ns}from"path";import{execFileSync as r0}from"child_process";import{platform as o0}from"os";var s0=o0()==="win32";function pt(e){let t=s0?"where":"which";try{return r0(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var u0=c0(import.meta.url);function Jc(e){return[e.indexerBinary,...e.binaryAliases??[]]}function is(e){let t=Jc(e);return t.length===1?t[0]:t.join(" or ")}function Si(e){for(let t of Jc(e))if(pt(t))return t;return m0(e)}function Ff(e){return Si(e)!==null||d0(e)}function d0(e){return Af(e)!==null}function m0(e){let t=Af(e);if(!t)return null;let i=JSON.parse(a0(t,"utf8")).bin;if(!i)return null;if(typeof i=="string")return ns($f(t),i);for(let r of Jc(e)){let o=i[r];if(o)return ns($f(t),o)}return null}function Af(e){if(!e.bundledNpmPackage)return null;try{return u0.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Qc(e,t){for(let n of e.projectLocalBinaries??[]){let i=ns(t,n);if(zc(i))return i}return null}function p0(e,t){return Qc(e,t)??Si(e)}function Mf(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Xc(n,t))return t;let i=Of(n,t);return i?{...t,DOTNET_ROOT:i}:t}function rs(e,t){let n=is(e),i=t?p0(e,t):Si(e);if(!i)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:i};let r=f0(i);return{language:e.language,binaryLabel:n,installed:!0,runnable:r.runnable,resolvedBinary:i,installUrl:e.installUrl,note:r.note}}function os(e,t){let n=e.installMethods,i=is(e);if(!n?.length)return t(`No auto-install method available for ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let r of n)if(pt(r.prerequisite)){t(`Installing ${i} via ${r.label}...`);try{Kc(r.binary,r.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Si(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${i} via ${r.label}${s}`),!0}t(`${r.label} command completed but ${i} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${r.label} install failed: ${s}`)}}return t(`Could not auto-install ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function f0(e){if(Xc(e,process.env))return{runnable:!0};let t=Of(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=jf(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function Of(e,t){for(let n of jf(t))if(Xc(e,{...t,DOTNET_ROOT:n}))return n;return null}function jf(e){let t=[],n=e.DOTNET_ROOT;if(n&&zc(n)&&t.push(n),l0()==="darwin"&&pt("brew"))try{let i=Kc("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),r=ns(i,"libexec");zc(r)&&!t.includes(r)&&t.push(r)}catch{}return t}function Xc(e,t){try{return Kc(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import{createRequire as g0}from"module";var h0=g0(import.meta.url);function Bf(e,t=[]){let n=b0(),i=la(e,t),r=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i,reason:"ts-morph is not installed"}}function b0(){try{return h0.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as xi,spawnSync as Uf}from"child_process";import{existsSync as It,mkdtempSync as Wf,readFileSync as y0,readdirSync as S0,rmSync as Gf,symlinkSync as x0,writeFileSync as C0}from"fs";import{tmpdir as zf}from"os";import{join as Ge}from"path";var v0=3e5,R0=12;function Yc(e,t,n={}){let i=Zc(e);if(i.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let r=k0(t,i),o=n.timeoutMs??v0,s=D0(e,t),a=Wf(Ge(zf(),"scip-cleanup-verify-")),c=[],l=new Set;try{xi("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),I0(e,a);for(let u of i)for(let d of qf(u,a,o).errorKeys)l.add(d);for(let u of t.batches){Jf(a,u);let d=[];for(let m of i){let p=qf(m,a,o);d.push(...p.rawErrors.filter(h=>!l.has(Kf(h))))}if(d.length===0)c.push({depth:u.depth,status:"verified"});else{c.push({depth:u.depth,status:"failed",errors:d.slice(0,R0)});break}}}finally{try{xi("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{Gf(a,{recursive:!0,force:!0})}}return{checkers:i.map(u=>u.label),uncoveredFiles:r,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function k0(e,t){let n=new Set(t.flatMap(r=>r.coversExtensions));return[...new Set(e.batches.flatMap(r=>r.entries.map(o=>o.file)))].filter(r=>{let o=r.slice(r.lastIndexOf("."));return!n.has(o)}).sort()}function Kf(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Hf=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function Zc(e){let t=[];if(It(Ge(e,"tsconfig.json"))){let n=Ge(e,"node_modules",".bin","tsc");t.push(It(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Hf}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Hf})}if(It(Ge(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>It(Ge(e,n)))){let n=w0();n&&t.push(n)}for(let n of L0(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--manifest-path",n],coversExtensions:[".rs"],env:{...process.env,CARGO_TARGET_DIR:Ge(e,n,"..","target")}});return t}function w0(){return Vf("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:Vf("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function Vf(e){try{return Uf(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function L0(e){let t=[];if(It(Ge(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=S0(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||It(Ge(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function D0(e,t){let n;try{n=xi("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let i=new Set(n.split(`
700
+ `).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>i.has(o)).sort()}function I0(e,t){for(let n of["node_modules"]){let i=Ge(e,n),r=Ge(t,n);if(It(i)&&!It(r))try{x0(i,r,"junction")}catch{}}}function Jf(e,t){let n=new Map;for(let i of t.entries){let r=n.get(i.file)??[];r.push({start:i.startLine,end:i.endLine}),n.set(i.file,r)}for(let[i,r]of n){let o=Ge(e,i);It(o)&&C0(o,P0(y0(o,"utf-8"),r,{rust:i.endsWith(".rs")}))}}function el(e,t){for(let n of t)Jf(e,n)}function Qf(e,t){let n=Wf(Ge(zf(),"scip-cleanup-patch-"));try{return xi("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),el(n,t),xi("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{xi("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Gf(n,{recursive:!0,force:!0})}}}function tl(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(i=>i.depth===t.batch);return n?[n]:[]}return[...e.batches]}function nl(e,t,n={}){let i=[];e.checkers.length===0&&i.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&i.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&i.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let r=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)r.has(o.depth)||i.push(`Batch ${o.depth} is not compiler-verified.`);return i}function P0(e,t,n={}){let i=e.split(`
701
+ `),r=(n.rust===!0?N0(e):rn(e)).split(`
702
+ `),o=new Set;for(let s of t){let a=E0(i,s.start),c=_0(r,a,Math.min(s.end,i.length-1));for(let l=a;l<=c&&l<i.length;l++)o.add(l)}return i.filter((s,a)=>!o.has(a)).join(`
703
+ `)}function N0(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function E0(e,t){let n=t;for(;n>0;){let i=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(i))n-=1;else break}return n}var T0=200;function _0(e,t,n){let i=0;for(let r=t;r<e.length;r++){for(let o of e[r]??"")o==="("||o==="["||o==="{"?i+=1:(o===")"||o==="]"||o==="}")&&(i-=1);if(r>=n&&i<=0)return r;if(r-n>T0)break}return n}function qf(e,t,n){let i=Uf(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(i.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${i.stdout??""}
704
704
  ${i.stderr??""}`.split(`
705
- `).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return i.error&&o.length===0&&o.push(String(i.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(Wf))}}var Kf={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"]},I0={typescript:{status:"available",reason:"AST/source fallback covers TypeScript imports, references, and source-backed evidence."},javascript:{status:"available",reason:"AST/source fallback covers JavaScript, JSX, and Vue script evidence."},java:{status:"available",reason:"AST-dispatched source fallback covers Java imports."},scala:{status:"available",reason:"AST-dispatched source fallback covers Scala imports."},kotlin:{status:"available",reason:"AST-dispatched source fallback covers Kotlin imports."},rust:{status:"available",reason:"AST/source fallback covers Rust imports and exports."},python:{status:"available",reason:"AST/source fallback covers Python imports."},ruby:{status:"available",reason:"AST/source fallback covers Ruby imports."},go:{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."},cpp:{status:"available",reason:"AST/source fallback covers C++ includes."},c:{status:"available",reason:"AST/source fallback covers C includes."},csharp:{status:"available",reason:"AST-dispatched source fallback covers C# imports."},vb:{status:"available",reason:"AST-dispatched source fallback covers Visual Basic imports."},dart:{status:"partial",reason:"Dart source fallback is regex-only for imports and exports."},php:{status:"available",reason:"AST/source fallback covers PHP imports."}};function ft(e,t){let n=t.languages??Dt(e),i=n.map(s=>{let a=is(Pn(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),r=n.includes("typescript")?{language:"typescript",...Mf(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=Qc(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:i,semantic:r,checkers:o,gitAvailable:T0(e)}}function Nn(e){let t=e.indexers.filter(r=>r.runnable).length,n=e.languages.length===0||t===0?"unavailable":t===e.indexers.length?"available":"partial",i=e.semantic?e.semantic.available?"available":"partial":"unavailable";return{languages:e.languages,matrix:e.languages.map(r=>P0(e,r)),capabilities:[{id:"indexing",label:"SCIP indexing",status:n,evidence:"graph-fact",reason:n==="available"?"All detected/configured language indexers are runnable.":`${t}/${e.indexers.length} detected/configured language indexers are runnable.`},{id:"semantic-typescript",label:"TypeScript semantic provider",status:i,evidence:"semantic",reason:e.semantic?e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks will fall back to SCIP/source evidence.":"TypeScript is not detected/configured for this project."},{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:n==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:n==="unavailable"?"Heuristic detectors need an indexed code graph.":"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index."},{id:"cleanup-verification",label:"Compiler cleanup verification",status:e.checkers.length>0?"available":"unavailable",evidence:"compiler",reason:e.checkers.length>0?e.checkers.map(r=>r.label).join(", "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&n!=="unavailable"?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function P0(e,t){let n=e.indexers.find(a=>a.language===t),i=n?.runnable?"available":"unavailable",r=I0[t],o=t==="typescript"?N0(e):{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`},s=E0(e,t);return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:n?.runnable?`${n.binaryLabel} is runnable${n.resolvedBinary?` at ${n.resolvedBinary}`:""}.`:n?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:i==="unavailable"?"unavailable":r.status,evidence:"heuristic",reason:i==="unavailable"?"Source fallback needs indexed documents before it can attach evidence.":r.reason},semantic:o,detectors:{id:"detectors",label:"Cleanup detectors",status:i==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:i==="unavailable"?"Cleanup detectors need an indexed graph for this language.":"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:s.length>0?"available":"unavailable",evidence:"compiler",reason:s.length>0?s.map(a=>a.label).join(", "):`No detected checker covers ${Kf[t].join(", ")} files.`}}}function N0(e){return e.semantic?{id:"semantic",label:"Semantic provider",status:e.semantic.available?"available":"partial",evidence:"semantic",reason:e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks fall back to SCIP/source evidence."}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:"TypeScript is not detected/configured for this project."}}function E0(e,t){let n=new Set(Kf[t]);return e.checkers.filter(i=>i.coversExtensions.some(r=>n.has(r)))}function T0(e){try{return D0("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as _0,existsSync as os,readFileSync as ss,writeFileSync as Xf}from"fs";import{join as Sr}from"path";var yr="<!-- scip-query:agent-setup:begin -->",el="<!-- scip-query:agent-setup:end -->",Jf="# scip-query:agent-setup";function xr(){if(process.stdin.isTTY)return"";try{return ss(0,"utf-8")}catch{return""}}function as(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Cr(e){let t=e.rootCauseGroups?.length??e.findings.length,n=[`scip-query diff-gate found ${e.findings.length} issue(s) in ${t} root-cause group(s) in this diff \u2014 fix or knowingly accept them before finishing:`],i=e.rootCauseGroups?.filter(r=>r.count>1)??[];for(let r of i)n.push(`- group [${r.check}] ${r.count} finding(s): ${r.message}`),n.push(` -> ${r.remediation}`);for(let r of e.findings)n.push(`- [${r.check}] ${r.message}`),n.push(` -> ${r.remediation}`);return n.join(`
706
- `)}function cs(e,t={}){let n={written:[],unchanged:[],skipped:[]};return F0(e,n),t.gitHook&&$0(e,n),n}function F0(e,t){let n=[yr,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- For non-trivial implementation requests: plan first (`concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.",el].join(`
707
- `);Qf(e,"AGENTS.md",n,t);let i=os(Sr(e,"CLAUDE.md"))?ss(Sr(e,"CLAUDE.md"),"utf-8"):"";if(i.includes("@AGENTS.md")&&!i.includes(yr)){t.unchanged.push("CLAUDE.md");return}let r=[yr,"@AGENTS.md",el].join(`
708
- `);Qf(e,"CLAUDE.md",r,t)}function Qf(e,t,n,i){let r=Sr(e,t),o=os(r)?ss(r,"utf-8"):"",s;if(o.includes(yr)){let a=new RegExp(`${yr}[\\s\\S]*?${el}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
705
+ `).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return i.error&&o.length===0&&o.push(String(i.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(Kf))}}var Xf={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"]},F0={typescript:{status:"available",reason:"AST/source fallback covers TypeScript imports, references, and source-backed evidence."},javascript:{status:"available",reason:"AST/source fallback covers JavaScript, JSX, and Vue script evidence."},java:{status:"available",reason:"AST-dispatched source fallback covers Java imports."},scala:{status:"available",reason:"AST-dispatched source fallback covers Scala imports."},kotlin:{status:"available",reason:"AST-dispatched source fallback covers Kotlin imports."},rust:{status:"available",reason:"AST/source fallback covers Rust imports and exports."},python:{status:"available",reason:"AST/source fallback covers Python imports."},ruby:{status:"available",reason:"AST/source fallback covers Ruby imports."},go:{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."},cpp:{status:"available",reason:"AST/source fallback covers C++ includes."},c:{status:"available",reason:"AST/source fallback covers C includes."},csharp:{status:"available",reason:"AST-dispatched source fallback covers C# imports."},vb:{status:"available",reason:"AST-dispatched source fallback covers Visual Basic imports."},dart:{status:"partial",reason:"Dart source fallback is regex-only for imports and exports."},php:{status:"available",reason:"AST/source fallback covers PHP imports."}};function ft(e,t){let n=t.languages??Dt(e),i=n.map(s=>{let a=rs(Pn(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),r=n.includes("typescript")?{language:"typescript",...Bf(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=Zc(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:i,semantic:r,checkers:o,gitAvailable:j0(e)}}function Nn(e){let t=e.indexers.filter(r=>r.runnable).length,n=e.languages.length===0||t===0?"unavailable":t===e.indexers.length?"available":"partial",i=e.semantic?e.semantic.available?"available":"partial":"unavailable";return{languages:e.languages,matrix:e.languages.map(r=>A0(e,r)),capabilities:[{id:"indexing",label:"SCIP indexing",status:n,evidence:"graph-fact",reason:n==="available"?"All detected/configured language indexers are runnable.":`${t}/${e.indexers.length} detected/configured language indexers are runnable.`},{id:"semantic-typescript",label:"TypeScript semantic provider",status:i,evidence:"semantic",reason:e.semantic?e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks will fall back to SCIP/source evidence.":"TypeScript is not detected/configured for this project."},{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:n==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:n==="unavailable"?"Heuristic detectors need an indexed code graph.":"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index."},{id:"cleanup-verification",label:"Compiler cleanup verification",status:e.checkers.length>0?"available":"unavailable",evidence:"compiler",reason:e.checkers.length>0?e.checkers.map(r=>r.label).join(", "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&n!=="unavailable"?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function A0(e,t){let n=e.indexers.find(a=>a.language===t),i=n?.runnable?"available":"unavailable",r=F0[t],o=t==="typescript"?M0(e):{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`},s=O0(e,t);return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:n?.runnable?`${n.binaryLabel} is runnable${n.resolvedBinary?` at ${n.resolvedBinary}`:""}.`:n?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:i==="unavailable"?"unavailable":r.status,evidence:"heuristic",reason:i==="unavailable"?"Source fallback needs indexed documents before it can attach evidence.":r.reason},semantic:o,detectors:{id:"detectors",label:"Cleanup detectors",status:i==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:i==="unavailable"?"Cleanup detectors need an indexed graph for this language.":"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:s.length>0?"available":"unavailable",evidence:"compiler",reason:s.length>0?s.map(a=>a.label).join(", "):`No detected checker covers ${Xf[t].join(", ")} files.`}}}function M0(e){return e.semantic?{id:"semantic",label:"Semantic provider",status:e.semantic.available?"available":"partial",evidence:"semantic",reason:e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks fall back to SCIP/source evidence."}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:"TypeScript is not detected/configured for this project."}}function O0(e,t){let n=new Set(Xf[t]);return e.checkers.filter(i=>i.coversExtensions.some(r=>n.has(r)))}function j0(e){try{return $0("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as B0,existsSync as ss,readFileSync as as,writeFileSync as eg}from"fs";import{join as Sr}from"path";var yr="<!-- scip-query:agent-setup:begin -->",il="<!-- scip-query:agent-setup:end -->",Yf="# scip-query:agent-setup";function xr(){if(process.stdin.isTTY)return"";try{return as(0,"utf-8")}catch{return""}}function cs(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Cr(e){let t=e.rootCauseGroups?.length??e.findings.length,n=[`scip-query diff-gate found ${e.findings.length} issue(s) in ${t} root-cause group(s) in this diff \u2014 fix or knowingly accept them before finishing:`],i=e.rootCauseGroups?.filter(r=>r.count>1)??[];for(let r of i)n.push(`- group [${r.check}] ${r.count} finding(s): ${r.message}`),n.push(` -> ${r.remediation}`);for(let r of e.findings)n.push(`- [${r.check}] ${r.message}`),n.push(` -> ${r.remediation}`);return n.join(`
706
+ `)}function ls(e,t={}){let n={written:[],unchanged:[],skipped:[]};return H0(e,n),t.gitHook&&V0(e,n),n}function H0(e,t){let n=[yr,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- For non-trivial implementation requests: plan first (`concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.",il].join(`
707
+ `);Zf(e,"AGENTS.md",n,t);let i=ss(Sr(e,"CLAUDE.md"))?as(Sr(e,"CLAUDE.md"),"utf-8"):"";if(i.includes("@AGENTS.md")&&!i.includes(yr)){t.unchanged.push("CLAUDE.md");return}let r=[yr,"@AGENTS.md",il].join(`
708
+ `);Zf(e,"CLAUDE.md",r,t)}function Zf(e,t,n,i){let r=Sr(e,t),o=ss(r)?as(r,"utf-8"):"",s;if(o.includes(yr)){let a=new RegExp(`${yr}[\\s\\S]*?${il}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
709
709
 
710
710
  `)}${n}
711
711
  `:`${n}
712
- `;s===o?i.unchanged.push(t):(Xf(r,s),i.written.push(t))}function $0(e,t){let n=Sr(e,".git","hooks");if(!os(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let i=Sr(n,"pre-commit"),r=["#!/bin/sh",Jf,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
713
- `);if(os(i)){let o=ss(i,"utf-8");if(o.includes(Jf)){if(o===r){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}Xf(i,r),_0(i,493),t.written.push(".git/hooks/pre-commit")}var tg="SCIP_QUERY_SKIP_HOOK_INSTALL",tl="SCIP_QUERY_STOP_HOOK_MODE",H0="scip-query hook-",V0="scip-query diff-gate --hook";function ls(e,t={}){let n=ng(),i=t.env??process.env;return U0(i)?(n.skipped.push({target:"project agent hooks",reason:`${tg}=1`}),n):(Yf({provider:"codex",rootDir:Ci(e,".codex"),configPath:Ci(e,".codex","hooks.json"),label:".codex/hooks.json",createRoot:!0,result:n}),Yf({provider:"claude",rootDir:Ci(e,".claude"),configPath:Ci(e,".claude","settings.json"),label:".claude/settings.json",createRoot:!0,result:n}),t.removeLegacyUserHooks!==!1&&q0({homeDir:t.homeDir,result:n}),n)}function q0(e={}){let t=e.result??ng(),n=e.homeDir??j0();return Zf({configPath:Ci(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),Zf({configPath:Ci(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function ng(){return{installed:[],updated:[],unchanged:[],removed:[],skipped:[]}}function U0(e=process.env){let t=e[tg];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function W0(e=process.env){let t=e[tl]?.toLowerCase();return t==="block"||t==="blocking"||t==="1"||t==="true"||t==="yes"?"block":t==="feedback"||t==="continue"?"feedback":"warn"}function Yf(e){if(!e.createRoot&&!vr(e.rootDir))return;let t=ig(e.configPath,e.label,e.result);if(!t)return;let n=G0(t,e.provider);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let i=vr(e.configPath);M0(B0(e.configPath),{recursive:!0}),eg(e.configPath,`${JSON.stringify(n,null,2)}
714
- `),e.result[i?"updated":"installed"].push(e.label)}function Zf(e){if(!vr(e.configPath))return;let t=ig(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},i={...n},r=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=rg(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(r=!0,c.length>0?i[s]=c:delete i[s])}if(!r)return;let o={...t};Object.keys(i).length>0?o.hooks=i:delete o.hooks,eg(e.configPath,`${JSON.stringify(o,null,2)}
715
- `),e.result.removed.push(e.label)}function ig(e,t,n){if(!vr(e))return{};try{let i=JSON.parse(O0(e,"utf-8"));if(!i||typeof i!="object"||Array.isArray(i)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return i}catch(i){n.skipped.push({target:t,reason:`could not parse existing hook config: ${i instanceof Error?i.message:String(i)}`});return}}function G0(e,t){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...n}};for(let r of["SessionStart","UserPromptSubmit","Stop"]){let o=Array.isArray(n[r])?n[r]:[];i.hooks[r]=[...rg(o),K0(t,r)]}return i}function rg(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!z0(n)):[]})).filter(t=>t.hooks.length>0)}function z0(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(H0)||t===V0)}function K0(e,t){return t==="SessionStart"?{matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:"scip-query hook-context",timeout:5,statusMessage:"Loading scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:"scip-query hook-context",timeout:5,statusMessage:"Routing scip-query skill"}]}:{hooks:[{type:"command",command:"scip-query hook-stop",timeout:30,statusMessage:"Running scip-query diff gate"}]}}function og(){let e=X0(xr());e&&console.log(JSON.stringify(e))}function sg(){let e=xr();if(as(e))return;let t=ag(e),n=cg(t);n&&nF(n,i=>{let r=dr(i,{minTogether:6,skip:[]});r.findings.length!==0&&console.log(JSON.stringify(J0(r,W0())))})}function J0(e,t="warn"){let n=Cr(e),i=Q0(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${i}
712
+ `;s===o?i.unchanged.push(t):(eg(r,s),i.written.push(t))}function V0(e,t){let n=Sr(e,".git","hooks");if(!ss(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let i=Sr(n,"pre-commit"),r=["#!/bin/sh",Yf,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
713
+ `);if(ss(i)){let o=as(i,"utf-8");if(o.includes(Yf)){if(o===r){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}eg(i,r),B0(i,493),t.written.push(".git/hooks/pre-commit")}var rg="SCIP_QUERY_SKIP_HOOK_INSTALL",rl="SCIP_QUERY_STOP_HOOK_MODE",K0="scip-query hook-",J0="scip-query diff-gate --hook";function us(e,t={}){let n=og(),i=t.env??process.env;return X0(i)?(n.skipped.push({target:"project agent hooks",reason:`${rg}=1`}),n):(tg({provider:"codex",rootDir:Ci(e,".codex"),configPath:Ci(e,".codex","hooks.json"),label:".codex/hooks.json",createRoot:!0,result:n}),tg({provider:"claude",rootDir:Ci(e,".claude"),configPath:Ci(e,".claude","settings.json"),label:".claude/settings.json",createRoot:!0,result:n}),t.removeLegacyUserHooks!==!1&&Q0({homeDir:t.homeDir,result:n}),n)}function Q0(e={}){let t=e.result??og(),n=e.homeDir??G0();return ng({configPath:Ci(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),ng({configPath:Ci(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function og(){return{installed:[],updated:[],unchanged:[],removed:[],skipped:[]}}function X0(e=process.env){let t=e[rg];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Y0(e=process.env){let t=e[rl]?.toLowerCase();return t==="block"||t==="blocking"||t==="1"||t==="true"||t==="yes"?"block":t==="feedback"||t==="continue"?"feedback":"warn"}function tg(e){if(!e.createRoot&&!vr(e.rootDir))return;let t=sg(e.configPath,e.label,e.result);if(!t)return;let n=Z0(t,e.provider);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let i=vr(e.configPath);U0(z0(e.configPath),{recursive:!0}),ig(e.configPath,`${JSON.stringify(n,null,2)}
714
+ `),e.result[i?"updated":"installed"].push(e.label)}function ng(e){if(!vr(e.configPath))return;let t=sg(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},i={...n},r=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=ag(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(r=!0,c.length>0?i[s]=c:delete i[s])}if(!r)return;let o={...t};Object.keys(i).length>0?o.hooks=i:delete o.hooks,ig(e.configPath,`${JSON.stringify(o,null,2)}
715
+ `),e.result.removed.push(e.label)}function sg(e,t,n){if(!vr(e))return{};try{let i=JSON.parse(W0(e,"utf-8"));if(!i||typeof i!="object"||Array.isArray(i)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return i}catch(i){n.skipped.push({target:t,reason:`could not parse existing hook config: ${i instanceof Error?i.message:String(i)}`});return}}function Z0(e,t){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...n}};for(let r of["SessionStart","UserPromptSubmit","Stop"]){let o=Array.isArray(n[r])?n[r]:[];i.hooks[r]=[...ag(o),t$(t,r)]}return i}function ag(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!e$(n)):[]})).filter(t=>t.hooks.length>0)}function e$(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(K0)||t===J0)}function t$(e,t){return t==="SessionStart"?{matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:"scip-query hook-context",timeout:5,statusMessage:"Loading scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:"scip-query hook-context",timeout:5,statusMessage:"Routing scip-query skill"}]}:{hooks:[{type:"command",command:"scip-query hook-stop",timeout:30,statusMessage:"Running scip-query diff gate"}]}}function cg(){let e=r$(xr());e&&console.log(JSON.stringify(e))}function lg(){let e=xr();if(cs(e))return;let t=ug(e),n=dg(t);n&&l$(n,i=>{let r=dr(i,{minTogether:6,skip:[]});r.findings.length!==0&&console.log(JSON.stringify(n$(r,Y0())))})}function n$(e,t="warn"){let n=Cr(e),i=i$(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${i}
716
716
 
717
717
  This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${i}
718
718
 
719
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${tl}=feedback to ask the agent to continue without a hook error, or ${tl}=block to enforce the gate.`}}function Q0(e){return Cr(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}function X0(e){let t=ag(e),n=eF(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let i=cg(t);if(!i)return;let r=n==="SessionStart"?Y0(i.projectRoot,i.config,i.paths):Z0(String(t.prompt??""));if(r.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:r}}}function Y0(e,t,n){let i=yi(e,t,n),r=ft(e,t),s=Nn(r).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=r.languages.length>0?r.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${i.state} (${i.reason})`,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].join(`
720
- `)}function Z0(e){let t=e.toLowerCase(),n=[];return En(t,["debug","bug","regression","failing","fails","error","wrong"])&&n.push("Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."),En(t,["explain","how does","walk me through","trace","understand"])&&n.push("Exploration request: use scip-explore before answering behavioral questions."),En(t,["diagram","visualize","visualise","flow map","architecture map"])&&n.push("Diagram request: use scip-diagram and back every node and edge with scip-query evidence."),En(t,["implement","build","change","refactor","fix","add ","update "])&&n.push("Implementation request: plan first with concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."),En(t,["review","maintainability","architecture","boundary"])&&n.push("Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."),En(t,["setup","adopt","install","bootstrap"])&&n.push("Setup request: use scip-adoption or scip-query-setup; keep CI setup out of the default path."),En(t,["health","score","dossier","cleanup","dead code","duplicate","debloat","perfect code","as high as","maximize","maximise"])&&n.push("Health or cleanup request: use scip-health-audit before editing; use scip-health-improve when the user wants the score raised as high as reasonably possible."),n.length===0?"":["scip-query routing reminder:",...n].join(`
721
- `)}function En(e,t){return t.some(n=>e.includes(n))}function ag(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function eF(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function cg(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=tF(t);if(n)try{let i=tt(n),r=Wt(n,i);return vr(r.dbPath)?{projectRoot:n,config:i,paths:r}:void 0}catch{return}}function tF(e){try{return A0("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function nF(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality},i=new pi(n,Ut(e.projectRoot));try{return t(i)}finally{i.close()}}import{existsSync as rl,mkdirSync as oF,symlinkSync as sF,readlinkSync as aF,unlinkSync as cF}from"fs";import{join as kr,dirname as mg,resolve as ol}from"path";import{homedir as sl,platform as lF}from"os";import{fileURLToPath as uF}from"url";import{execFileSync as lg}from"child_process";import{platform as nl,arch as iF}from"os";var ug="v0.7.0";function Rr(){return Ge("scip")}function rF(){let e=nl(),t=iF(),n,i,r;switch(e){case"darwin":n="darwin",r="tar.gz";break;case"linux":n="linux",r="tar.gz";break;case"win32":n="windows",r="zip";break;default:return null}switch(t){case"arm64":i="arm64";break;case"x64":i="amd64";break;default:return null}let o=`scip-${n}-${i}.${r}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${ug}/${o}`,filename:o}}function il(){let e=rF();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),nl()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
722
- `),console.log("Or download manually:")):console.log("Download from:"),console.log(e?` ${e.url}
723
- `:` https://github.com/sourcegraph/scip/releases/tag/${ug}
724
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function dg(e){if(nl()==="darwin"&&Ge("brew")){e("Installing scip CLI via Homebrew...");try{if(lg("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ge("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(Ge("go")){e("Installing scip CLI via go install...");try{if(lg("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ge("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e("Install manually from: https://github.com/sourcegraph/scip/releases"),!1}var dF=lF()==="win32",al=["scip-query","scip-query-setup","scip-adoption","scip-health-audit","scip-health-improve","scip-api-impact","concrete-plan","scip-ai-cleanup","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-debloat","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook"];function us(e={}){let t=e.quiet?()=>{}:console.log,n=uF(import.meta.url),i=ol(mg(n),"..","skills"),r=[kr(sl(),".claude","skills"),kr(sl(),".codex","skills"),kr(sl(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of r){let a=mg(s);if(!rl(a))continue;oF(s,{recursive:!0});let c=mF(s);for(let l of al){let u=kr(i,l),d=kr(s,l);if(!rl(u)){o.skipped.push(`${c}/${l}`);continue}if(rl(d)){try{let m=aF(d);if(ol(m)===ol(u)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}cF(d)}sF(u,d,dF?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function mF(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as dM}from"fs";import{execFileSync as Q$}from"child_process";import{closeSync as X$,copyFileSync as Y$,existsSync as fs,mkdirSync as yl,mkdtempSync as Z$,openSync as eA,readFileSync as Hg,renameSync as Sl,rmSync as xl,writeFileSync as Vg}from"fs";import{basename as ps,dirname as Pt,extname as tA,join as gt}from"path";import pF from"better-sqlite3";import{execFileSync as fF}from"child_process";import{existsSync as gF,readdirSync as hF,readFileSync as bF}from"fs";import{extname as ds,join as pg}from"path";function Gt(e){let t=new Set((e.extensions??ru).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!gF(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Ut(e.projectRoot),i=yF(e.projectRoot,t).filter(o=>!n.isIgnored(o)),r=new pF(e.dbPath);try{let o=xF(r,i),s=r.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
725
- VALUES (?, ?, NULL, ?)`),c=r.transaction(u=>{let d=0;for(let m of u){if(o.has(m))continue;let p=bF(pg(e.projectRoot,m),"utf-8"),h=s.run(CF(m),m,p);d+=Number(h.changes)}return d})(i),l={scanned:i.length,inserted:c,existing:i.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{r.close()}}function yF(e,t){let n=SF(e,t);if(n)return n;let i=[],r=o=>{let s=o?pg(e,o):e,a;try{a=hF(s,{withFileTypes:!0})}catch{return}for(let c of a){if(js.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){r(l);continue}t.has(ds(c.name).toLowerCase())&&i.push(l)}};return r(""),i.sort()}function SF(e,t){try{return fF("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
726
- `).filter(i=>i&&t.has(ds(i).toLowerCase())).sort()}catch{return null}}function xF(e,t){let n=new Set,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),s=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.add(a.relative_path)}return n}function CF(e){return ds(e).toLowerCase()===".vue"?"vue":ds(e).replace(/^\./,"").toLowerCase()||"source"}import{readFileSync as vF,writeFileSync as RF}from"fs";import{create as cl}from"@bufbuild/protobuf";import{deserializeSCIP as kF,serializeSCIP as wF,DocumentSchema as LF,IndexSchema as DF,SymbolInformationSchema as IF}from"@c4312/scip";function PF(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=NF(e),n=EF(e.flatMap(r=>r.documents??[])),i=gg(e.flatMap(r=>r.externalSymbols??[]));return cl(DF,{metadata:t,documents:n,externalSymbols:i})}function fg(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(r=>kF(vF(r))),i=PF(n);return RF(t,Buffer.from(wF(i))),{documentCount:i.documents.length,externalSymbolCount:i.externalSymbols.length,inputCount:e.length}}function NF(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let i of e.slice(1)){let r=i.metadata?.projectRoot;if(n&&r&&r!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${r}`)}return t}function EF(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);if(!i){t.set(n.relativePath,n);continue}t.set(n.relativePath,cl(LF,{language:i.language||n.language,relativePath:i.relativePath||n.relativePath,occurrences:[...i.occurrences,...n.occurrences],symbols:gg([...i.symbols,...n.symbols]),text:_F(i.text,n.text),positionEncoding:i.positionEncoding||n.positionEncoding}))}return[...t.values()]}function gg(e){let t=new Map;for(let n of e){let i=t.get(n.symbol);if(!i){t.set(n.symbol,n);continue}t.set(n.symbol,cl(IF,{symbol:i.symbol,documentation:FF([...i.documentation,...n.documentation]),relationships:TF([...i.relationships,...n.relationships]),kind:i.kind||n.kind,displayName:i.displayName||n.displayName,enclosingSymbol:i.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:i.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function TF(e){let t=new Set,n=[];for(let i of e){let r=[i.symbol,i.isReference?"1":"0",i.isImplementation?"1":"0",i.isTypeDefinition?"1":"0",i.isDefinition?"1":"0"].join("|");t.has(r)||(t.add(r),n.push(i))}return n}function _F(e,t){return e?t?e.length>=t.length?e:t:e:t}function FF(e){return[...new Set(e)]}import{readFileSync as $F,writeFileSync as AF}from"fs";import{create as hg}from"@bufbuild/protobuf";import{deserializeSCIP as MF,DocumentSchema as OF,IndexSchema as jF,serializeSCIP as BF,SymbolRole as HF}from"@c4312/scip";function bg(e){let t;try{t=MF($F(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=VF(t);return n.removedDefinitionOccurrences>0&&AF(e,Buffer.from(BF(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function VF(e){let t=new Set;for(let o of e.documents)for(let s of o.symbols)s.symbol&&t.add(s.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,i=0,r=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&HF.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){r.push(o);continue}i+=1,r.push(hg(OF,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:hg(jF,{metadata:e.metadata,documents:r,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:i}}import{execFile as qF}from"child_process";import{existsSync as ms,renameSync as ul,rmSync as dl}from"fs";import{cpus as UF}from"os";import{join as yg}from"path";function WF(e,t,n){if(!e.defaultOutputPath)return;let i=yg(t,e.defaultOutputPath);n!==i&&ms(i)&&ul(i,n)}function GF(e,t,n){if(!e.defaultOutputPath)return null;let i=yg(t,e.defaultOutputPath);if(i===n)return null;let r=`${n}.default-output-backup`;return dl(r,{force:!0}),ms(i)?(ul(i,r),{defaultOutputPath:i,backupPath:r}):{defaultOutputPath:i,backupPath:null}}function zF(e){e&&(dl(e.defaultOutputPath,{force:!0}),e.backupPath&&ms(e.backupPath)&&ul(e.backupPath,e.defaultOutputPath))}function KF(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),i=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,UF().length-1));return Math.max(1,Math.min(e,Math.floor(i)))}async function Sg(e,t,n,i){let r=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=KF(o.length,i),c=await QF(o,a,l=>ll(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(d=>d.skipped)){let d=o.find(m=>m.language===u.language);d&&(n(`Retrying ${d.language} indexer serially after parallel failure...`),l.set(d.language,await ll(d,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of r)s.push(await ll(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.language===l.language)-e.findIndex(d=>d.language===u.language))}async function ll(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),dl(e.scipPath,{force:!0});let i=GF(e.config,t,e.scipPath);try{await JF(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),WF(e.config,t,e.scipPath)}catch(r){let o=r instanceof Error?r.message:String(r),s=`${e.resolvedBinary} indexer failed: ${o.split(`
727
- `)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{zF(i)}if(!ms(e.scipPath)){let r=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${r}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:r}}}return{language:e.language,scipPath:e.scipPath}}function JF(e,t,n){return new Promise((i,r)=>{qF(e,[...t],n,o=>{o?r(o):i()})})}async function QF(e,t,n){if(e.length===0)return[];let i=new Array(e.length),r=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;r<e.length;){let a=r++;i[a]=await n(e[a])}});return await Promise.all(s),i}import N$ from"better-sqlite3";import{existsSync as E$,readFileSync as T$,writeFileSync as _$}from"fs";import{dirname as F$,join as $$,resolve as A$}from"path";import{readFileSync as XF,rmSync as YF,statSync as ZF,mkdtempSync as e$}from"fs";import{cpus as t$,tmpdir as n$}from"os";import{join as ml}from"path";import{Worker as i$}from"worker_threads";function xg(e){return e.length>=8&&vg(e.length)>1}function Cg(e){let t=vg(e.vueFiles.length),n=o$(e.vueFiles),i=a$(n,t),r=new URL("./augment-vue-worker.js",import.meta.url),o=e$(ml(n$(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=r$(),l=Date.now();try{for(let d=0;d<i.length;d++)new i$(r,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:i[d],resultPath:ml(o,`${d}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<i.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=i.map((d,m)=>{let p=JSON.parse(XF(ml(o,`${m}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{YF(o,{recursive:!0,force:!0})}}function vg(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,t$().length-1));return Math.max(1,Math.min(e,n))}function r$(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function o$(e){let t=s$(),n=[];for(let i of e){let r=Rg(i),o=Math.max(1,Math.ceil(r/t));for(let s=0;s<o;s++)n.push({fileName:i,startOffset:Math.floor(r*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(r*(s+1)/o),countFileSkip:s===0})}return n}function s$(){return Number.POSITIVE_INFINITY}function a$(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),i=e.map(r=>({task:r,weight:c$(r)})).sort((r,o)=>o.weight-r.weight);for(let r of i){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(r.task),o.weight+=r.weight}return n.map(r=>r.tasks).filter(r=>r.length>0)}function c$(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Rg(e.fileName)-e.startOffset)}function Rg(e){try{return ZF(e).size}catch{return 1}}import{createRequire as l$}from"module";import{existsSync as u$,readFileSync as fl}from"fs";import{dirname as kg,extname as d$,join as wg,relative as m$,resolve as p$}from"path";import{pathToFileURL as f$}from"url";function g$(e){e.transaction(()=>{e.prepare(`
719
+ Stop hook allowed this turn to finish. Review these findings when relevant. Set ${rl}=feedback to ask the agent to continue without a hook error, or ${rl}=block to enforce the gate.`}}function i$(e){return Cr(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}function r$(e){let t=ug(e),n=a$(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let i=dg(t);if(!i)return;let r=n==="SessionStart"?o$(i.projectRoot,i.config,i.paths):s$(String(t.prompt??""));if(r.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:r}}}function o$(e,t,n){let i=yi(e,t,n),r=ft(e,t),s=Nn(r).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=r.languages.length>0?r.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${i.state} (${i.reason})`,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].join(`
720
+ `)}function s$(e){let t=e.toLowerCase(),n=[];return En(t,["debug","bug","regression","failing","fails","error","wrong"])&&n.push("Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."),En(t,["explain","how does","walk me through","trace","understand"])&&n.push("Exploration request: use scip-explore before answering behavioral questions."),En(t,["diagram","visualize","visualise","flow map","architecture map"])&&n.push("Diagram request: use scip-diagram and back every node and edge with scip-query evidence."),En(t,["implement","build","change","refactor","fix","add ","update "])&&n.push("Implementation request: plan first with concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."),En(t,["review","maintainability","architecture","boundary"])&&n.push("Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."),En(t,["setup","adopt","install","bootstrap"])&&n.push("Setup request: use scip-adoption or scip-query-setup; keep CI setup out of the default path."),En(t,["health","score","dossier","cleanup","dead code","duplicate","debloat","perfect code","as high as","maximize","maximise"])&&n.push("Health or cleanup request: use scip-health-audit before editing; use scip-health-improve when the user wants the score raised as high as reasonably possible."),n.length===0?"":["scip-query routing reminder:",...n].join(`
721
+ `)}function En(e,t){return t.some(n=>e.includes(n))}function ug(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function a$(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function dg(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=c$(t);if(n)try{let i=et(n),r=Wt(n,i);return vr(r.dbPath)?{projectRoot:n,config:i,paths:r}:void 0}catch{return}}function c$(e){try{return q0("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function l$(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality},i=new pi(n,Ut(e.projectRoot));try{return t(i)}finally{i.close()}}import{existsSync as al,mkdirSync as g$,symlinkSync as h$,readlinkSync as b$,unlinkSync as y$}from"fs";import{join as wr,dirname as Sg,resolve as cl}from"path";import{homedir as ll,platform as S$}from"os";import{fileURLToPath as x$}from"url";import{execFileSync as mg}from"child_process";import{existsSync as fg,readFileSync as u$}from"fs";import{platform as Rr,arch as gg}from"os";import{dirname as pg,join as ds}from"path";import{fileURLToPath as d$}from"url";var hg="v0.8.1",ol="https://github.com/scip-code/scip",m$={win32:{x64:ds("vendor","scip","win32-x64","scip.exe"),arm64:ds("vendor","scip","win32-arm64","scip.exe")}};function p$(){let e=pg(d$(import.meta.url));for(;;){let t=ds(e,"package.json");if(fg(t))try{if(JSON.parse(u$(t,"utf-8")).name==="scip-query")return e}catch{}let n=pg(e);if(n===e)return null;e=n}}function bg(){let e=m$[Rr()]?.[gg()];if(!e)return null;let t=p$();if(!t)return null;let n=ds(t,e);return fg(n)?n:null}function ms(){return pt("scip")?"scip":bg()}function kr(){return ms()!==null}function f$(){let e=Rr(),t=gg(),n,i,r;switch(e){case"darwin":n="darwin",r="tar.gz";break;case"linux":n="linux",r="tar.gz";break;default:return null}switch(t){case"arm64":i="arm64";break;case"x64":i="amd64";break;default:return null}let o=`scip-${n}-${i}.${r}`;return{url:`${ol}/releases/download/${hg}/${o}`,filename:o}}function sl(){let e=f$();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Rr()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
722
+ `),console.log("Or download manually:")):Rr()==="win32"?(console.log("Windows installs should include a managed scip.exe in the scip-query package."),console.log("Reinstall scip-query, or build the managed binary from source with:"),console.log(` npm run build:scip-windows
723
+ `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
724
+ `:` ${ol}/releases/tag/${hg}
725
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function yg(e){let t=bg();if(t)return e(`Using bundled scip CLI at ${t}`),!0;if(Rr()==="darwin"&&pt("brew")){e("Installing scip CLI via Homebrew...");try{if(mg("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),pt("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(n){let i=n instanceof Error?n.message:String(n);e(`Homebrew install failed: ${i}`)}}if(pt("go")){e("Installing scip CLI via go install...");try{if(mg("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),pt("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(n){let i=n instanceof Error?n.message:String(n);e(`go install failed: ${i}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${ol}/releases`),!1}var C$=S$()==="win32",ul=["scip-query","scip-query-setup","scip-adoption","scip-health-audit","scip-health-improve","scip-api-impact","concrete-plan","scip-ai-cleanup","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-debloat","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook"];function ps(e={}){let t=e.quiet?()=>{}:console.log,n=x$(import.meta.url),i=cl(Sg(n),"..","skills"),r=[wr(ll(),".claude","skills"),wr(ll(),".codex","skills"),wr(ll(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of r){let a=Sg(s);if(!al(a))continue;g$(s,{recursive:!0});let c=v$(s);for(let l of ul){let u=wr(i,l),d=wr(s,l);if(!al(u)){o.skipped.push(`${c}/${l}`);continue}if(al(d)){try{let m=b$(d);if(cl(m)===cl(u)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}y$(d)}h$(u,d,C$?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function v$(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as CM}from"fs";import{execFileSync as sA}from"child_process";import{closeSync as aA,copyFileSync as cA,existsSync as bs,mkdirSync as Cl,mkdtempSync as lA,openSync as uA,readFileSync as Kg,renameSync as vl,rmSync as Rl,writeFileSync as Jg}from"fs";import{basename as hs,dirname as Pt,extname as dA,join as gt}from"path";import R$ from"better-sqlite3";import{execFileSync as k$}from"child_process";import{existsSync as w$,readdirSync as L$,readFileSync as D$}from"fs";import{extname as fs,join as xg}from"path";function Gt(e){let t=new Set((e.extensions??au).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!w$(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Ut(e.projectRoot),i=I$(e.projectRoot,t).filter(o=>!n.isIgnored(o)),r=new R$(e.dbPath);try{let o=N$(r,i),s=r.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
726
+ VALUES (?, ?, NULL, ?)`),c=r.transaction(u=>{let d=0;for(let m of u){if(o.has(m))continue;let p=D$(xg(e.projectRoot,m),"utf-8"),h=s.run(E$(m),m,p);d+=Number(h.changes)}return d})(i),l={scanned:i.length,inserted:c,existing:i.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{r.close()}}function I$(e,t){let n=P$(e,t);if(n)return n;let i=[],r=o=>{let s=o?xg(e,o):e,a;try{a=L$(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Vs.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){r(l);continue}t.has(fs(c.name).toLowerCase())&&i.push(l)}};return r(""),i.sort()}function P$(e,t){try{return k$("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
727
+ `).filter(i=>i&&t.has(fs(i).toLowerCase())).sort()}catch{return null}}function N$(e,t){let n=new Set,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),s=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.add(a.relative_path)}return n}function E$(e){return fs(e).toLowerCase()===".vue"?"vue":fs(e).replace(/^\./,"").toLowerCase()||"source"}import{readFileSync as T$,writeFileSync as _$}from"fs";import{create as dl}from"@bufbuild/protobuf";import{deserializeSCIP as $$,serializeSCIP as F$,DocumentSchema as A$,IndexSchema as M$,SymbolInformationSchema as O$}from"@c4312/scip";function j$(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=B$(e),n=H$(e.flatMap(r=>r.documents??[])),i=vg(e.flatMap(r=>r.externalSymbols??[]));return dl(M$,{metadata:t,documents:n,externalSymbols:i})}function Cg(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(r=>$$(T$(r))),i=j$(n);return _$(t,Buffer.from(F$(i))),{documentCount:i.documents.length,externalSymbolCount:i.externalSymbols.length,inputCount:e.length}}function B$(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let i of e.slice(1)){let r=i.metadata?.projectRoot;if(n&&r&&r!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${r}`)}return t}function H$(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);if(!i){t.set(n.relativePath,n);continue}t.set(n.relativePath,dl(A$,{language:i.language||n.language,relativePath:i.relativePath||n.relativePath,occurrences:[...i.occurrences,...n.occurrences],symbols:vg([...i.symbols,...n.symbols]),text:q$(i.text,n.text),positionEncoding:i.positionEncoding||n.positionEncoding}))}return[...t.values()]}function vg(e){let t=new Map;for(let n of e){let i=t.get(n.symbol);if(!i){t.set(n.symbol,n);continue}t.set(n.symbol,dl(O$,{symbol:i.symbol,documentation:U$([...i.documentation,...n.documentation]),relationships:V$([...i.relationships,...n.relationships]),kind:i.kind||n.kind,displayName:i.displayName||n.displayName,enclosingSymbol:i.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:i.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function V$(e){let t=new Set,n=[];for(let i of e){let r=[i.symbol,i.isReference?"1":"0",i.isImplementation?"1":"0",i.isTypeDefinition?"1":"0",i.isDefinition?"1":"0"].join("|");t.has(r)||(t.add(r),n.push(i))}return n}function q$(e,t){return e?t?e.length>=t.length?e:t:e:t}function U$(e){return[...new Set(e)]}import{readFileSync as W$,writeFileSync as G$}from"fs";import{create as Rg}from"@bufbuild/protobuf";import{deserializeSCIP as z$,DocumentSchema as K$,IndexSchema as J$,serializeSCIP as Q$,SymbolRole as X$}from"@c4312/scip";function kg(e){let t;try{t=z$(W$(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Y$(t);return n.removedDefinitionOccurrences>0&&G$(e,Buffer.from(Q$(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Y$(e){let t=new Set;for(let o of e.documents)for(let s of o.symbols)s.symbol&&t.add(s.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,i=0,r=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&X$.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){r.push(o);continue}i+=1,r.push(Rg(K$,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Rg(J$,{metadata:e.metadata,documents:r,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:i}}import{execFile as Z$}from"child_process";import{existsSync as gs,renameSync as pl,rmSync as fl}from"fs";import{cpus as eF}from"os";import{join as wg}from"path";function tF(e,t,n){if(!e.defaultOutputPath)return;let i=wg(t,e.defaultOutputPath);n!==i&&gs(i)&&pl(i,n)}function nF(e,t,n){if(!e.defaultOutputPath)return null;let i=wg(t,e.defaultOutputPath);if(i===n)return null;let r=`${n}.default-output-backup`;return fl(r,{force:!0}),gs(i)?(pl(i,r),{defaultOutputPath:i,backupPath:r}):{defaultOutputPath:i,backupPath:null}}function iF(e){e&&(fl(e.defaultOutputPath,{force:!0}),e.backupPath&&gs(e.backupPath)&&pl(e.backupPath,e.defaultOutputPath))}function rF(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),i=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,eF().length-1));return Math.max(1,Math.min(e,Math.floor(i)))}async function Lg(e,t,n,i){let r=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=rF(o.length,i),c=await sF(o,a,l=>ml(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(d=>d.skipped)){let d=o.find(m=>m.language===u.language);d&&(n(`Retrying ${d.language} indexer serially after parallel failure...`),l.set(d.language,await ml(d,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of r)s.push(await ml(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.language===l.language)-e.findIndex(d=>d.language===u.language))}async function ml(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),fl(e.scipPath,{force:!0});let i=nF(e.config,t,e.scipPath);try{await oF(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),tF(e.config,t,e.scipPath)}catch(r){let o=r instanceof Error?r.message:String(r),s=`${e.resolvedBinary} indexer failed: ${o.split(`
728
+ `)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{iF(i)}if(!gs(e.scipPath)){let r=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${r}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:r}}}return{language:e.language,scipPath:e.scipPath}}function oF(e,t,n){return new Promise((i,r)=>{Z$(e,[...t],n,o=>{o?r(o):i()})})}async function sF(e,t,n){if(e.length===0)return[];let i=new Array(e.length),r=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;r<e.length;){let a=r++;i[a]=await n(e[a])}});return await Promise.all(s),i}import BF from"better-sqlite3";import{existsSync as HF,readFileSync as VF,writeFileSync as qF}from"fs";import{dirname as UF,join as WF,resolve as GF}from"path";import{readFileSync as aF,rmSync as cF,statSync as lF,mkdtempSync as uF}from"fs";import{cpus as dF,tmpdir as mF}from"os";import{join as gl}from"path";import{Worker as pF}from"worker_threads";function Dg(e){return e.length>=8&&Pg(e.length)>1}function Ig(e){let t=Pg(e.vueFiles.length),n=gF(e.vueFiles),i=bF(n,t),r=new URL("./augment-vue-worker.js",import.meta.url),o=uF(gl(mF(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=fF(),l=Date.now();try{for(let d=0;d<i.length;d++)new pF(r,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:i[d],resultPath:gl(o,`${d}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<i.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=i.map((d,m)=>{let p=JSON.parse(aF(gl(o,`${m}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{cF(o,{recursive:!0,force:!0})}}function Pg(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,dF().length-1));return Math.max(1,Math.min(e,n))}function fF(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function gF(e){let t=hF(),n=[];for(let i of e){let r=Ng(i),o=Math.max(1,Math.ceil(r/t));for(let s=0;s<o;s++)n.push({fileName:i,startOffset:Math.floor(r*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(r*(s+1)/o),countFileSkip:s===0})}return n}function hF(){return Number.POSITIVE_INFINITY}function bF(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),i=e.map(r=>({task:r,weight:yF(r)})).sort((r,o)=>o.weight-r.weight);for(let r of i){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(r.task),o.weight+=r.weight}return n.map(r=>r.tasks).filter(r=>r.length>0)}function yF(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ng(e.fileName)-e.startOffset)}function Ng(e){try{return lF(e).size}catch{return 1}}import{createRequire as SF}from"module";import{existsSync as xF,readFileSync as bl}from"fs";import{dirname as Eg,extname as CF,join as Tg,relative as vF,resolve as RF}from"path";import{pathToFileURL as kF}from"url";function wF(e){e.transaction(()=>{e.prepare(`
728
729
  DELETE FROM mentions
729
730
  WHERE chunk_id IN (
730
731
  SELECT c.id
@@ -739,12 +740,12 @@ Stop hook allowed this turn to finish. Review these findings when relevant. Set
739
740
  FROM documents
740
741
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
741
742
  )
742
- `).run()})()}function Lg(e,t){return e.prepare(`
743
+ `).run()})()}function _g(e,t){return e.prepare(`
743
744
  SELECT relative_path AS relativePath
744
745
  FROM documents
745
746
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
746
747
  ORDER BY relative_path
747
- `).all().map(i=>p$(t,i.relativePath))}function Dg(e,t){let{vueCore:n,ts:i,volarTs:r}=h$(e),{parsed:o,vueOptions:s}=b$(n,i,t),a=kg(t),c=n.createVueLanguagePlugin(i,o.options,s,p=>p),l=y$(n,i,c),u=S$(a,o),{languageServiceHost:d}=r.createLanguageServiceHost(i,i.sys,l,p=>p,u),m=i.createLanguageService(d);return{ts:i,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function h$(e){let t=l$(f$(wg(e,"package.json")).href);return{vueCore:pl(t,"@vue/language-core",e),ts:pl(t,"typescript",e),volarTs:pl(t,"@volar/typescript",e)}}function b$(e,t,n){let i=t.readConfigFile(n,t.sys.readFile);if(i.error||!i.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(i.config,t.sys,kg(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function y$(e,t,n){let i={},r=e.createLanguage([n],new Map,o=>{if(!u$(o))return;let s=fl(o,"utf-8");i.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??w$(o))});return i.current=r,r}function S$(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function pl(e,t,n){try{return e(t)}catch(i){throw(typeof i=="object"&&i!==null&&"code"in i?i.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:i}):i}}function Ig(e,t,n){let i=x$(e);return r=>{let o=Tn(t,r.fileName),s=n.get(r.fileName);if(!s)return null;let a=n.positionAt(s,r.textSpan.start),c=i.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:C$(c.starts,a.line,2)}}function x$(e){let t=e.prepare(`
748
+ `).all().map(i=>RF(t,i.relativePath))}function $g(e,t){let{vueCore:n,ts:i,volarTs:r}=LF(e),{parsed:o,vueOptions:s}=DF(n,i,t),a=Eg(t),c=n.createVueLanguagePlugin(i,o.options,s,p=>p),l=IF(n,i,c),u=PF(a,o),{languageServiceHost:d}=r.createLanguageServiceHost(i,i.sys,l,p=>p,u),m=i.createLanguageService(d);return{ts:i,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function LF(e){let t=SF(kF(Tg(e,"package.json")).href);return{vueCore:hl(t,"@vue/language-core",e),ts:hl(t,"typescript",e),volarTs:hl(t,"@volar/typescript",e)}}function DF(e,t,n){let i=t.readConfigFile(n,t.sys.readFile);if(i.error||!i.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(i.config,t.sys,Eg(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function IF(e,t,n){let i={},r=e.createLanguage([n],new Map,o=>{if(!xF(o))return;let s=bl(o,"utf-8");i.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??FF(o))});return i.current=r,r}function PF(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function hl(e,t,n){try{return e(t)}catch(i){throw(typeof i=="object"&&i!==null&&"code"in i?i.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:i}):i}}function Fg(e,t,n){let i=NF(e);return r=>{let o=Tn(t,r.fileName),s=n.get(r.fileName);if(!s)return null;let a=n.positionAt(s,r.textSpan.start),c=i.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:EF(c.starts,a.line,2)}}function NF(e){let t=e.prepare(`
748
749
  SELECT
749
750
  d.relative_path AS relativePath,
750
751
  der.start_line AS startLine,
@@ -753,23 +754,23 @@ Stop hook allowed this turn to finish. Review these findings when relevant. Set
753
754
  FROM defn_enclosing_ranges der
754
755
  JOIN documents d ON d.id = der.document_id
755
756
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
756
- `).all(),n=new Map;for(let i of t){let r=n.get(i.relativePath);r||(r={containingByLine:new Map,starts:[]},n.set(i.relativePath,r)),r.starts.push({line:i.startLine,symbolId:i.symbolId});for(let o=i.startLine;o<=i.endLine;o++)r.containingByLine.set(o,i.symbolId)}for(let i of n.values())i.starts.sort((r,o)=>r.line-o.line);return n}function C$(e,t,n){let i=0,r=e.length-1;for(;i<=r;){let s=Math.floor((i+r)/2);e[s].line<t?i=s+1:r=s-1}let o=null;for(let s of[r,i]){let a=e[s];if(!a)continue;let c=Math.abs(a.line-t);c>n||(!o||c<o.distance)&&(o={distance:c,symbolId:a.symbolId})}return o?.symbolId??null}function Pg(e,t,n){let i=I$(t),r=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
757
+ `).all(),n=new Map;for(let i of t){let r=n.get(i.relativePath);r||(r={containingByLine:new Map,starts:[]},n.set(i.relativePath,r)),r.starts.push({line:i.startLine,symbolId:i.symbolId});for(let o=i.startLine;o<=i.endLine;o++)r.containingByLine.set(o,i.symbolId)}for(let i of n.values())i.starts.sort((r,o)=>r.line-o.line);return n}function EF(e,t,n){let i=0,r=e.length-1;for(;i<=r;){let s=Math.floor((i+r)/2);e[s].line<t?i=s+1:r=s-1}let o=null;for(let s of[r,i]){let a=e[s];if(!a)continue;let c=Math.abs(a.line-t);c>n||(!o||c<o.distance)&&(o={distance:c,symbolId:a.symbolId})}return o?.symbolId??null}function Ag(e,t,n){let i=OF(t),r=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
757
758
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
758
759
  VALUES (?, ?, ?, ?)
759
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Tn(t,l),d=Og(i.name,i.version,u);o.run(d,"default",7,`Vue component|${u}`);let m=P$(r,i,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Ng(e,t,n,i,r){return e.transaction(()=>(g$(e),v$(e,t,n,i),R$(e,r)))()}function v$(e,t,n,i){let r=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
760
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Tn(t,l),d=Wg(i.name,i.version,u);o.run(d,"default",7,`Vue component|${u}`);let m=jF(r,i,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Mg(e,t,n,i,r){return e.transaction(()=>(wF(e),TF(e,t,n,i),_F(e,r)))()}function TF(e,t,n,i){let r=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
760
761
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
761
762
  VALUES (?, ?, ?, ?, X'00')
762
763
  `),s=e.prepare(`
763
764
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
764
765
  VALUES (?, ?, 1)
765
- `);for(let a of n){let c=i.get(a);if(!c)continue;let l=Tn(t,a),u=r.get(l);if(!u)continue;let d=o.run(u.id,-1,0,0);s.run(Number(d.lastInsertRowid),c)}}function Eg(e,t,n,i,r){if(e.fileName.endsWith(".vue")){let o=i.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=i.language.maps.get(s,o);if(gl(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(r)?n.get(e.fileName):null}return t(e)}function Tg(e){let t=new Set,n=[];for(let i of e){let r=_g(i);t.has(r)||(t.add(r),n.push(i))}return n}function _g(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function R$(e,t){let n=D$(e,[...new Set(t.map(c=>c.sourceFile))]),i=e.prepare(`
766
+ `);for(let a of n){let c=i.get(a);if(!c)continue;let l=Tn(t,a),u=r.get(l);if(!u)continue;let d=o.run(u.id,-1,0,0);s.run(Number(d.lastInsertRowid),c)}}function Og(e,t,n,i,r){if(e.fileName.endsWith(".vue")){let o=i.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=i.language.maps.get(s,o);if(yl(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(r)?n.get(e.fileName):null}return t(e)}function jg(e){let t=new Set,n=[];for(let i of e){let r=Bg(i);t.has(r)||(t.add(r),n.push(i))}return n}function Bg(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function _F(e,t){let n=MF(e,[...new Set(t.map(c=>c.sourceFile))]),i=e.prepare(`
766
767
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
767
768
  VALUES (?, ?, ?, ?, X'00')
768
769
  `),r=e.prepare(`
769
770
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
770
771
  VALUES (?, ?, 0)
771
- `),o=new Set,s=0,a=0;for(let c of t){let l=_g(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let d=i.run(u,a++,c.sourceLine,c.sourceLine),m=r.run(Number(d.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Fg(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),i;for(;i=t.exec(e);){let r=i[0];n.has(r)||(yield{text:r,start:i.index,end:i.index+r.length})}}function $g(e,t){for(let[n]of e.toGeneratedLocation(t,i=>!!i.navigation))return n;return null}function gl(e,t){let n=e;for(let[i]of n.toSourceLocation(t,r=>!!r.navigation))return i;return null}function k$(e,t){let n=0,i=e.lineStarts.length-1;for(;n<=i;){let o=Math.floor((n+i)/2);e.lineStarts[o]<=t?n=o+1:i=o-1}let r=Math.max(0,i);return{line:r,character:t-e.lineStarts[r]}}function Ag(e,t){return Tn(e,t).startsWith("node_modules/")}function Tn(e,t){return m$(e,t).replaceAll("\\","/")}function w$(e){switch(d$(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Mg(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=fl(t,"utf-8"),i={text:n,lineStarts:L$(n)};return e.set(t,i),i}catch{return e.set(t,null),null}},positionAt:k$}}function L$(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function D$(e,t){let n=new Map,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function I$(e){try{let t=JSON.parse(fl(wg(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function P$(e,t,n,i){let r=Tn(n,i),o=Og(t.name,t.version,r);return e.get(o)?.id??null}function Og(e,t,n){let i=n.split("/").map(r=>`\`${r.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${i}/default.`}function hl(e){Gt({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=A$(e.projectRoot,e.tsconfig);if(!E$(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new N$(e.dbPath);try{let i=Lg(n,e.projectRoot),r=$$(F$(e.dbPath),"augment-vue-meta.json"),o=jg(n,e.projectRoot,e.tsconfig),s=M$(r,o,e.onStatus);if(s)return s;let a=O$({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:i,onStatus:e.onStatus});return H$(r,jg(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function M$(e,t,n){let i=B$(e,t);return i&&n?.(`Vue references unchanged; reused ${i.resolvedReferences} cached resolved references.`),i}function O$(e){let t=Pg(e.db,e.projectRoot,e.vueFiles),n=j$(e,t),i=Tg(n.occurrences),r=Ng(e.db,e.projectRoot,e.vueFiles,t,i),o={vueFiles:e.vueFiles.length,resolvedReferences:i.length,insertedMentions:r,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function j$(e,t){if(xg(e.vueFiles))return Cg({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=V$({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return q$({...n,vueFiles:n.context.fileNames.filter(i=>i.endsWith(".vue"))})}function B$(e,t){try{let n=JSON.parse(T$(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function H$(e,t,n){_$(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
772
- `)}function jg(e,t,n){let i=e.prepare(`
772
+ `),o=new Set,s=0,a=0;for(let c of t){let l=Bg(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let d=i.run(u,a++,c.sourceLine,c.sourceLine),m=r.run(Number(d.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Hg(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),i;for(;i=t.exec(e);){let r=i[0];n.has(r)||(yield{text:r,start:i.index,end:i.index+r.length})}}function Vg(e,t){for(let[n]of e.toGeneratedLocation(t,i=>!!i.navigation))return n;return null}function yl(e,t){let n=e;for(let[i]of n.toSourceLocation(t,r=>!!r.navigation))return i;return null}function $F(e,t){let n=0,i=e.lineStarts.length-1;for(;n<=i;){let o=Math.floor((n+i)/2);e.lineStarts[o]<=t?n=o+1:i=o-1}let r=Math.max(0,i);return{line:r,character:t-e.lineStarts[r]}}function qg(e,t){return Tn(e,t).startsWith("node_modules/")}function Tn(e,t){return vF(e,t).replaceAll("\\","/")}function FF(e){switch(CF(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Ug(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=bl(t,"utf-8"),i={text:n,lineStarts:AF(n)};return e.set(t,i),i}catch{return e.set(t,null),null}},positionAt:$F}}function AF(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function MF(e,t){let n=new Map,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function OF(e){try{let t=JSON.parse(bl(Tg(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function jF(e,t,n,i){let r=Tn(n,i),o=Wg(t.name,t.version,r);return e.get(o)?.id??null}function Wg(e,t,n){let i=n.split("/").map(r=>`\`${r.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${i}/default.`}function Sl(e){Gt({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=GF(e.projectRoot,e.tsconfig);if(!HF(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new BF(e.dbPath);try{let i=_g(n,e.projectRoot),r=WF(UF(e.dbPath),"augment-vue-meta.json"),o=Gg(n,e.projectRoot,e.tsconfig),s=zF(r,o,e.onStatus);if(s)return s;let a=KF({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:i,onStatus:e.onStatus});return XF(r,Gg(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function zF(e,t,n){let i=QF(e,t);return i&&n?.(`Vue references unchanged; reused ${i.resolvedReferences} cached resolved references.`),i}function KF(e){let t=Ag(e.db,e.projectRoot,e.vueFiles),n=JF(e,t),i=jg(n.occurrences),r=Mg(e.db,e.projectRoot,e.vueFiles,t,i),o={vueFiles:e.vueFiles.length,resolvedReferences:i.length,insertedMentions:r,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function JF(e,t){if(Dg(e.vueFiles))return Ig({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=YF({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return ZF({...n,vueFiles:n.context.fileNames.filter(i=>i.endsWith(".vue"))})}function QF(e,t){try{let n=JSON.parse(VF(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function XF(e,t,n){qF(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
773
+ `)}function Gg(e,t,n){let i=e.prepare(`
773
774
  SELECT
774
775
  (SELECT COUNT(*) FROM documents) AS documents,
775
776
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -778,17 +779,17 @@ Stop hook allowed this turn to finish. Review these findings when relevant. Set
778
779
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
779
780
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
780
781
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
781
- `).get();return{version:2,tsconfig:n,files:In(t),db:i}}function V$(e){let t=Mg();return{projectRoot:e.projectRoot,context:Dg(e.projectRoot,e.configPath),symbolLookup:Ig(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function q$(e){let t=[],n=0,i=e.tasks??e.vueFiles.map(r=>({fileName:r,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let r of i){let o=U$(e,r);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function U$(e,t){let n=e.context.language.scripts.get(t.fileName),i=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let r=e.sourceReader.get(t.fileName);if(!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(i,n),s=Tn(e.projectRoot,t.fileName),a=[...Fg(r.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:z$(a),processedStarts:new Set};return W$({...e,fileName:t.fileName,sourceInfo:r,sourceFile:s,map:o,tokenContext:c})}function W$(e){let t=[],n=0;for(let i of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(i.start))continue;let r=$g(e.map,i.start);if(r===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,r+1)??[]).find(c=>!Ag(e.projectRoot,c.fileName));if(!s){n++;continue}let a=Eg(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}Bg(t,e.sourceReader,e.sourceInfo,e.sourceFile,i,a),e.tokenContext.processedStarts.add(i.start),G$(t,e,i,r,a)}return{occurrences:t,skippedReferences:n}}function G$(e,t,n,i,r){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of K$(t.context.languageService,t.fileName,i+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(Bg(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,r),t.tokenContext.processedStarts.add(o))}}function Bg(e,t,n,i,r,o){let s=t.positionAt(n,r.start);e.push({sourceFile:i,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,symbolId:o})}function z$(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function K$(e,t,n,i,r,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let c of s)if(c.fileName===t)for(let l of c.highlightSpans){let u=J$(i,l.textSpan.start,o,r.text);u!==null&&a.push(u)}return a}function J$(e,t,n,i){let r=n.get(t);if(r?.text===i)return r.start;let o=gl(e,t);if(o===null)return null;let s=n.get(o);return s?.text===i?s.start:null}async function gs(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:i=console.log,skipAutoInstall:r=!1}=e,o=nA(e),s=Date.now();yl(Pt(o.outputScip),{recursive:!0}),yl(Pt(o.outputDb),{recursive:!0});let a=e.languages??Dt(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");i(`Detected languages: ${a.join(", ")}`);let c=xA(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=yA(gt(Pt(o.outputDb),"index.lock")),u=null;try{let d=iA({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:i});if(d)return d;uA(r,i);let m=rA(o);return u=m.runDir,await oA({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:r,onStatus:i})}finally{u&&xl(u,{recursive:!0,force:!0}),l()}}function nA(e){let t=e.outputScip??gt(e.projectRoot,"index.scip"),n=e.outputDb??gt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:gt(Pt(n),"meta.json")}}function iA(e){if(e.opts.skipIfUnchanged===!1||!fs(e.paths.outputScip)||!fs(e.paths.outputDb)||!CA(e.paths.metaPath,e.fingerprint))return null;Gt({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[]}}function rA(e){let t=Z$(gt(Pt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:gt(t,ps(e.outputScip)),tempOutputDb:gt(t,ps(e.outputDb)),tempMetaPath:gt(t,ps(e.metaPath))}}async function oA(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:i,reusedLanguages:r}=await sA(e,t);r.length>0&&e.onStatus(`Reused ${r.length} cached language shard(s): ${r.join(", ")}`),aA(e,t,n,i);let o=Date.now()-e.start;return e.onStatus(`Done in ${(o/1e3).toFixed(1)}s`),{languages:n.map(s=>s.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:o,reused:!1,skipped:i}}async function sA(e,t){let n=cA(e),i=new Set(n.map(l=>l.language));for(let l of i)e.onStatus(`Reusing cached ${l} SCIP shard (language inputs unchanged).`);let{preparedRuns:r,skippedLanguages:o}=dA({languages:e.languages.filter(l=>!i.has(l)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),s=await Sg(r,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=pA(s,o),c=[...n,...a];return fA(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...i]}}function aA(e,t,n,i){lA(e.paths.outputDb,n),gA(n,e.tempPaths.tempOutputScip,e.onStatus),hA(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),Gt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),vA(e.tempPaths.tempMetaPath,{version:3,status:i.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:qg(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces}),requestedLanguages:e.languages,indexedLanguages:n.map(r=>r.language),skipped:[...i]}),SA({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function cA(e){let t;try{t=JSON.parse(Hg(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],i=qg(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces});for(let r of e.languages){let o=Ug(e.paths.outputDb,r);fs(o)&&vi(t.languageFingerprints[r])===vi(i[r])&&n.push({language:r,scipPath:o})}return n}function lA(e,t){for(let n of t){let i=Ug(e,n.language);yl(Pt(i),{recursive:!0}),n.scipPath!==i&&Y$(n.scipPath,i)}}function uA(e,t){if(!Ge("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
782
- Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!dg(t))throw new Error(`The scip CLI is required but could not be installed.
783
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function dA(e){let t=[],n=[],i=e.languages.map((r,o)=>({language:r,scipPath:e.languages.length>1?bA(e.tempOutputScip,r,o):e.tempOutputScip}));for(let{language:r,scipPath:o}of i){let s=mA({...e,language:r,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function mA(e){let t=Pn(e.language),n=ns(t),i=zc(t,e.projectRoot);if(!i&&!Tf(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!rs(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let r=i??Si(t);if(!r){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:o,args:s}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:r});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:r,binary:o,args:s,env:Ff(t,e.env,r)}}}function pA(e,t){let n=[];for(let i of e)i.skipped?t.push(i.skipped):n.push({language:i.language,scipPath:i.scipPath});return{indexedOutputs:n}}function fA(e,t,n,i,r){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
782
+ `).get();return{version:2,tsconfig:n,files:In(t),db:i}}function YF(e){let t=Ug();return{projectRoot:e.projectRoot,context:$g(e.projectRoot,e.configPath),symbolLookup:Fg(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function ZF(e){let t=[],n=0,i=e.tasks??e.vueFiles.map(r=>({fileName:r,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let r of i){let o=eA(e,r);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function eA(e,t){let n=e.context.language.scripts.get(t.fileName),i=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let r=e.sourceReader.get(t.fileName);if(!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(i,n),s=Tn(e.projectRoot,t.fileName),a=[...Hg(r.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:iA(a),processedStarts:new Set};return tA({...e,fileName:t.fileName,sourceInfo:r,sourceFile:s,map:o,tokenContext:c})}function tA(e){let t=[],n=0;for(let i of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(i.start))continue;let r=Vg(e.map,i.start);if(r===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,r+1)??[]).find(c=>!qg(e.projectRoot,c.fileName));if(!s){n++;continue}let a=Og(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}zg(t,e.sourceReader,e.sourceInfo,e.sourceFile,i,a),e.tokenContext.processedStarts.add(i.start),nA(t,e,i,r,a)}return{occurrences:t,skippedReferences:n}}function nA(e,t,n,i,r){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of rA(t.context.languageService,t.fileName,i+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(zg(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,r),t.tokenContext.processedStarts.add(o))}}function zg(e,t,n,i,r,o){let s=t.positionAt(n,r.start);e.push({sourceFile:i,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,symbolId:o})}function iA(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function rA(e,t,n,i,r,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let c of s)if(c.fileName===t)for(let l of c.highlightSpans){let u=oA(i,l.textSpan.start,o,r.text);u!==null&&a.push(u)}return a}function oA(e,t,n,i){let r=n.get(t);if(r?.text===i)return r.start;let o=yl(e,t);if(o===null)return null;let s=n.get(o);return s?.text===i?s.start:null}async function ys(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:i=console.log,skipAutoInstall:r=!1}=e,o=mA(e),s=Date.now();Cl(Pt(o.outputScip),{recursive:!0}),Cl(Pt(o.outputDb),{recursive:!0});let a=e.languages??Dt(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");i(`Detected languages: ${a.join(", ")}`);let c=NA(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=IA(gt(Pt(o.outputDb),"index.lock")),u=null;try{let d=pA({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:i});if(d)return d;xA(r,i);let m=fA(o);return u=m.runDir,await gA({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:r,onStatus:i})}finally{u&&Rl(u,{recursive:!0,force:!0}),l()}}function mA(e){let t=e.outputScip??gt(e.projectRoot,"index.scip"),n=e.outputDb??gt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:gt(Pt(n),"meta.json")}}function pA(e){if(e.opts.skipIfUnchanged===!1||!bs(e.paths.outputScip)||!bs(e.paths.outputDb)||!EA(e.paths.metaPath,e.fingerprint))return null;Gt({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[]}}function fA(e){let t=lA(gt(Pt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:gt(t,hs(e.outputScip)),tempOutputDb:gt(t,hs(e.outputDb)),tempMetaPath:gt(t,hs(e.metaPath))}}async function gA(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:i,reusedLanguages:r}=await hA(e,t);r.length>0&&e.onStatus(`Reused ${r.length} cached language shard(s): ${r.join(", ")}`),bA(e,t,n,i);let o=Date.now()-e.start;return e.onStatus(`Done in ${(o/1e3).toFixed(1)}s`),{languages:n.map(s=>s.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:o,reused:!1,skipped:i}}async function hA(e,t){let n=yA(e),i=new Set(n.map(l=>l.language));for(let l of i)e.onStatus(`Reusing cached ${l} SCIP shard (language inputs unchanged).`);let{preparedRuns:r,skippedLanguages:o}=CA({languages:e.languages.filter(l=>!i.has(l)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),s=await Lg(r,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=RA(s,o),c=[...n,...a];return kA(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...i]}}function bA(e,t,n,i){SA(e.paths.outputDb,n),wA(n,e.tempPaths.tempOutputScip,e.onStatus),LA(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),Gt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),TA(e.tempPaths.tempMetaPath,{version:3,status:i.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:Qg(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces}),requestedLanguages:e.languages,indexedLanguages:n.map(r=>r.language),skipped:[...i]}),PA({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function yA(e){let t;try{t=JSON.parse(Kg(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],i=Qg(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces});for(let r of e.languages){let o=Xg(e.paths.outputDb,r);bs(o)&&vi(t.languageFingerprints[r])===vi(i[r])&&n.push({language:r,scipPath:o})}return n}function SA(e,t){for(let n of t){let i=Xg(e,n.language);Cl(Pt(i),{recursive:!0}),n.scipPath!==i&&cA(n.scipPath,i)}}function xA(e,t){if(!ms()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
783
+ Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!yg(t))throw new Error(`The scip CLI is required but could not be installed.
784
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function CA(e){let t=[],n=[],i=e.languages.map((r,o)=>({language:r,scipPath:e.languages.length>1?DA(e.tempOutputScip,r,o):e.tempOutputScip}));for(let{language:r,scipPath:o}of i){let s=vA({...e,language:r,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function vA(e){let t=Pn(e.language),n=is(t),i=Qc(t,e.projectRoot);if(!i&&!Ff(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!os(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let r=i??Si(t);if(!r){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:o,args:s}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:r});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:r,binary:o,args:s,env:Mf(t,e.env,r)}}}function RA(e,t){let n=[];for(let i of e)i.skipped?t.push(i.skipped):n.push({language:i.language,scipPath:i.scipPath});return{indexedOutputs:n}}function kA(e,t,n,i,r){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
784
785
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
785
786
  `+o)}if(t.length!==0&&(r(`Indexed ${e.length} of ${n.length} languages; skipped ${t.map(o=>o.language).join(", ")}.`),!i))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
786
787
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
787
- `))}function gA(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),fg(e.map(i=>i.scipPath),t)):e[0].scipPath!==t&&Sl(e[0].scipPath,t)}function hA(e,t,n,i){if(i("Converting to SQLite..."),!fs(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let r=bg(e);r.removedDefinitionOccurrences>0&&i(`Sanitized ${r.removedDefinitionOccurrences} invalid definition occurrences across ${r.touchedDocuments} documents before SQLite conversion.`),Q$("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:r})}}function bA(e,t,n){let i=tA(e)||".scip",r=ps(e,i);return gt(Pt(e),`${r}.${n+1}.${t}${i}`)}function yA(e){let t;try{t=eA(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${Pt(e)}.`,{cause:n}):n}return Vg(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
788
- `),()=>{try{X$(t)}finally{xl(e,{force:!0})}}}function SA(e){bl(e.tempOutputScip,e.outputScip),bl(e.tempOutputDb,e.outputDb),bl(e.tempMetaPath,e.metaPath)}function bl(e,t){xl(`${t}.tmp-replace`,{force:!0}),Sl(e,`${t}.tmp-replace`),Sl(`${t}.tmp-replace`,t)}function xA(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:In(e)}}function qg(e,t,n){return Object.fromEntries(t.map(i=>{let r=Pn(i).markerFiles;return[i,{version:1,languages:[i],pnpmWorkspaces:i==="typescript"&&n.pnpmWorkspaces===!0,files:In(e,{language:i,markerFiles:r})}]}))}function Ug(e,t){return gt(Pt(e),"language-indexes",`${t}.scip`)}function CA(e,t){try{let n=JSON.parse(Hg(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&vi(n.fingerprint)===vi(t)&&vi([...n.indexedLanguages??[]].sort())===vi(t.languages)}catch{return!1}}function vA(e,t){Vg(e,`${JSON.stringify(t,null,2)}
789
- `)}function vi(e){return JSON.stringify(e)}import{watch as RA}from"fs";import{existsSync as Wg,renameSync as Gg}from"fs";import{join as kA,relative as wA}from"path";import{fork as LA}from"child_process";import DA from"ignore";var hs=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=lf(t.config),this.indexPaths=Wt(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Ut(t.projectRoot),this.extraIgnore=DA(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=RA(this.projectRoot,{recursive:!0},(n,i)=>{i&&!this.stopped&&this.handleFileChange(i)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=wA(this.projectRoot,kA(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let i=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:i}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-t;this.dirty=!0;let r=Date.now()+i;this.setStatus({state:"cooldown",until:r,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let r=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:r,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let i=Date.now(),r=this.indexPaths.dbPath+".tmp",o=IA(this.indexPaths.indexPath),s=LA(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:o,SCIP_REINDEX_OUTPUT_DB:r,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{Wg(r)&&Gg(r,this.indexPaths.dbPath),Wg(o)&&Gg(o,this.indexPaths.indexPath),t(Date.now()-i)}catch(c){n(new Error(`Atomic swap failed: ${c}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),s.on("error",n)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}};function IA(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{existsSync as BA}from"fs";import{existsSync as PA,mkdirSync as NA,readFileSync as EA,writeFileSync as TA}from"fs";import{dirname as _A,join as zg}from"path";function Jg(e){let t={markdownPath:zg(e.projectRoot,"docs","scip-query","health-dossier.md"),jsonPath:zg(e.projectRoot,"docs","scip-query","health-dossier.json"),status:"written",written:[],unchanged:[]},n={...e,healthDossier:t};try{return Kg(t.markdownPath,FA(n),t),Kg(t.jsonPath,`${JSON.stringify(n,null,2)}
790
- `,t),t}catch(i){return{...t,status:"failed",error:i instanceof Error?i.message:String(i)}}}function FA(e){return`${["# scip-query Health Dossier","",`Generated: ${new Date().toISOString()}`,`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${OA(e)}`,"","## Items That Need Attention","",...$A(e),"","## Blocked Or Unavailable Checks","",...AA(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...MA(e),"","## JSON","",`Machine-readable report: \`${jA(e)}\``,""].join(`
791
- `)}`}function $A(e){return e.health.issuesNeedAttention.length===0?["No prioritized health actions were reported."]:e.health.issuesNeedAttention.map(t=>`- ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort}, evidence ${t.evidence}; confirmation ${t.confirmationStatus}; safe to start ${t.safeForAgentToStart?"yes":"no"}). ${t.recommendedNextStep}`)}function AA(e){let t=[...e.smokeTests.filter(n=>n.status!=="pass").map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),...e.indexerRemediation.filter(n=>!n.after.runnable).map(n=>`- BLOCKED ${n.language}: ${n.recovery??`Install ${n.binaryLabel}.`}`)];return t.length>0?t:["No blocked or unavailable setup checks were reported."]}function MA(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",i=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${i})`})}function OA(e){return e.health.score===null?`unavailable (${e.health.unavailableReason??"not checked"})`:`${e.health.score} (risk ${e.health.riskScore}, hygiene ${e.health.hygieneScore})`}function jA(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Kg(e,t,n){if(NA(_A(e),{recursive:!0}),(PA(e)?EA(e,"utf-8"):null)===t){n.unchanged.push(e);return}TA(e,t),n.written.push(e)}async function eh(e={}){let t=[],{projectRoot:n,config:i,paths:r,dbPath:o}=gi(),s=Rr();Q(t,{id:"scip-cli",label:"scip CLI",status:s?"ok":"warn",message:s?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let a=us({quiet:!0});Q(t,{id:"skills",label:"Agent skills",status:a.skipped.length>0?"warn":"ok",message:`${a.installed.length} installed, ${a.alreadyLinked.length} already linked, ${a.skipped.length} skipped.`,details:a.skipped.map(k=>`Skipped ${k}`)});let c=fi(i,{projectRoot:n}),l=c.filter(k=>k.level==="error");Q(t,{id:"config",label:"Project config",status:l.length>0?"failed":c.length>0?"warn":"ok",message:c.length===0?"Config OK.":`${c.length} diagnostic(s), ${l.length} error(s).`,details:c.map(k=>`${k.level.toUpperCase()} ${k.path}: ${k.message}`)});let u=ft(n,i);Q(t,{id:"readiness",label:"Indexer readiness",status:u.languages.length===0?"failed":u.indexers.some(k=>!k.runnable)?"warn":"ok",message:u.languages.length===0?"No supported project languages detected.":`Detected languages: ${u.languages.join(", ")}`,details:u.indexers.map(k=>`${k.runnable?"OK":k.installed?"WARN":"MISSING"} ${k.language}: ${k.binaryLabel}${k.note?` - ${k.note}`:""}`)});let d=JA(n,u,t),m=ft(n,i),p=null;if(m.languages.length===0||l.length>0)Q(t,{id:"reindex",label:"Index refresh",status:"skipped",message:m.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."});else{let k=[];try{p=await gs({projectRoot:n,languages:m.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:i.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!0,allowPartial:!0,onStatus:A=>k.push(A)}),Q(t,{id:"reindex",label:"Index refresh",status:p.skipped.length>0?"warn":"ok",message:`${p.reused?"Reused":"Indexed"} ${p.languages.join(", ")} in ${(p.durationMs/1e3).toFixed(1)}s.`,details:[...k,...p.skipped.map(A=>`Skipped ${A.language}: ${A.reason}`)]})}catch(A){Q(t,{id:"reindex",label:"Index refresh",status:"failed",message:bs(A),details:k})}}let h=ft(n,i),g=Nn(h),b=yi(n,i,r);Q(t,{id:"capabilities",label:"Capability matrix",status:eM(g),message:tM(g)});let S=XA(r.dbPath,t),x=null;try{x=ls(n),Q(t,{id:"project-hooks",label:"Project agent hooks",status:x.skipped.length>0?"warn":"ok",message:`${x.installed.length} installed, ${x.updated.length} updated, ${x.unchanged.length} already configured, ${x.removed.length} legacy user hook config(s) cleaned up, ${x.skipped.length} skipped.`,details:[...x.removed.map(k=>`Removed legacy user-level ${k}`),...x.skipped.map(k=>`Skipped ${k.target}: ${k.reason}`)]})}catch(k){Q(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:bs(k)})}let I=null;try{I=cs(n,{gitHook:e.gitHook}),Q(t,{id:"agent-guidance",label:"Project agent guidance",status:I.skipped.length>0?"warn":"ok",message:`${I.written.length} written, ${I.unchanged.length} already wired, ${I.skipped.length} skipped.`,details:I.skipped.map(k=>`Skipped ${k.target}: ${k.reason}`)})}catch(k){Q(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:bs(k)})}let L=HA({reindexResult:p,readiness:h,capabilities:g,freshness:b,health:S,hooksResult:x,agentResult:I,steps:t});Q(t,{id:"smoke-tests",label:"Setup smoke tests",status:VA(L),message:qA(L),details:L.map(k=>`${k.command}: ${k.status} - ${k.evidence}`)});let C={projectRoot:n,dbPath:o,configuredDbPath:r.dbPath,scipCliInstalled:s,languages:h.languages,steps:t,skills:a,initialReadiness:u,indexerRemediation:d,readiness:h,capabilities:g,freshness:b,reindex:p,health:S,smokeTests:L,healthDossier:null,hooks:x,setupAgent:I,filesWritten:I?.written??[],verdict:Zg(t,h)},D=Jg(C);return C.healthDossier=D,C.filesWritten=[...C.filesWritten,...D.written],Q(t,{id:"health-dossier",label:"Health dossier",status:D.status==="failed"?"failed":"ok",message:D.status==="failed"?D.error:`${D.written.length} written, ${D.unchanged.length} unchanged.`,details:[D.markdownPath,D.jsonPath]}),C.verdict=Zg(t,h),C}function th(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${nM(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function HA(e){let t=e.steps.find(r=>r.id==="reindex"),n=e.steps.find(r=>r.id==="project-hooks"),i=e.steps.find(r=>r.id==="agent-guidance");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="missing"?"fail":"pass",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:UA(e.steps),evidence:WA(e.steps)},{id:"capabilities",command:"scip-query capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"scip-query capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?GA(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"scip-query diff-impact --json",status:Qg(e.readiness,e.freshness),evidence:Xg(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Qg(e.readiness,e.freshness),evidence:Xg(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:zA(e.capabilities),evidence:KA(e.capabilities)},{id:"setup-hooks",command:"scip-query setup-hooks",status:e.hooksResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.hooksResult?`${e.hooksResult.installed.length} installed, ${e.hooksResult.updated.length} updated, ${e.hooksResult.unchanged.length} already configured.`:n?.message??"Project agent hooks were not configured."},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":i?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:i?.message??"Project agent guidance was not written."}]}function VA(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function qA(e){let t=e.filter(r=>r.status==="pass").length,n=e.filter(r=>r.status==="unavailable").length,i=e.filter(r=>r.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function UA(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function WA(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function GA(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(i=>i.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function Qg(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Xg(e,t){return e.gitAvailable?`Git is available and index freshness is ${t.state}: ${t.reason}`:"Git is not available for this project."}function zA(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function KA(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(r=>r.cleanupVerification.status==="available").length,n=e.matrix.filter(r=>r.cleanupVerification.status==="partial").length,i=e.matrix.filter(r=>r.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function JA(e,t,n){let i=[];if(t.languages.length===0)return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=Pn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=rs(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let d=QA(is(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:d,messages:c,recovery:d.runnable?void 0:d.note??d.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let r=i.filter(s=>!s.after.runnable),o=i.filter(s=>s.attempted);return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:r.length>0?"warn":"ok",message:r.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${r.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function QA(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}function XA(e,t){if(!BA(e)){let n="Skipped because no SQLite index database exists yet.";return Q(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Yg(n)}try{let n=Yo({full:!0,json:!0});return Q(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),YA(n)}catch(n){let i=bs(n);return Q(t,{id:"health",label:"Health audit",status:"failed",message:i}),Yg(i)}}function YA(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(ZA),warnings:e.warnings??[]}}function ZA(e){return{category:e.category,description:e.description,count:e.count,impact:e.impact,effort:e.effort,evidence:e.evidence,locRecoverable:e.locRecoverable,confirmationStatus:"unconfirmed",safeForAgentToStart:!1,recommendedNextStep:"Run scip-health-audit to confirm this signal; use scip-health-improve when the user wants confirmed issues fixed autonomously."}}function Yg(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Zg(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function eM(e){let t=e.matrix.flatMap(n=>[n.indexing.status,n.sourceFacts.status,n.semantic.status,n.cleanupVerification.status]);return t.some(n=>n==="unavailable")||t.some(n=>n==="partial")?"warn":"ok"}function tM(e){return e.matrix.length===0?"No language capability rows.":`${e.matrix.filter(n=>n.indexing.status==="available").length}/${e.matrix.length} language(s) have available indexing.`}function nM(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Q(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function bs(e){return e instanceof Error?e.message:String(e)}import{existsSync as iM,mkdirSync as rM,writeFileSync as oM}from"fs";import{dirname as sM,join as aM}from"path";function nh(e,t={}){let n=aM(e,".github","workflows","scip-query.yml"),i=cM();return iM(n)&&!t.force?{path:n,written:!1,skipped:!0,content:i,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(rM(sM(n),{recursive:!0}),oM(n,i)),{path:n,written:!t.dryRun,skipped:!1,content:i})}function cM(){return`name: scip-query
788
+ `))}function wA(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Cg(e.map(i=>i.scipPath),t)):e[0].scipPath!==t&&vl(e[0].scipPath,t)}function LA(e,t,n,i){if(i("Converting to SQLite..."),!bs(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let r=kg(e);r.removedDefinitionOccurrences>0&&i(`Sanitized ${r.removedDefinitionOccurrences} invalid definition occurrences across ${r.touchedDocuments} documents before SQLite conversion.`);let o=ms();if(!o)throw new Error("scip CLI is not available");sA(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:r})}}function DA(e,t,n){let i=dA(e)||".scip",r=hs(e,i);return gt(Pt(e),`${r}.${n+1}.${t}${i}`)}function IA(e){let t;try{t=uA(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${Pt(e)}.`,{cause:n}):n}return Jg(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
789
+ `),()=>{try{aA(t)}finally{Rl(e,{force:!0})}}}function PA(e){xl(e.tempOutputScip,e.outputScip),xl(e.tempOutputDb,e.outputDb),xl(e.tempMetaPath,e.metaPath)}function xl(e,t){Rl(`${t}.tmp-replace`,{force:!0}),vl(e,`${t}.tmp-replace`),vl(`${t}.tmp-replace`,t)}function NA(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:In(e)}}function Qg(e,t,n){return Object.fromEntries(t.map(i=>{let r=Pn(i).markerFiles;return[i,{version:1,languages:[i],pnpmWorkspaces:i==="typescript"&&n.pnpmWorkspaces===!0,files:In(e,{language:i,markerFiles:r})}]}))}function Xg(e,t){return gt(Pt(e),"language-indexes",`${t}.scip`)}function EA(e,t){try{let n=JSON.parse(Kg(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&vi(n.fingerprint)===vi(t)&&vi([...n.indexedLanguages??[]].sort())===vi(t.languages)}catch{return!1}}function TA(e,t){Jg(e,`${JSON.stringify(t,null,2)}
790
+ `)}function vi(e){return JSON.stringify(e)}import{watch as _A}from"fs";import{existsSync as Yg,renameSync as Zg}from"fs";import{join as $A,relative as FA}from"path";import{fork as AA}from"child_process";import MA from"ignore";var Ss=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=mf(t.config),this.indexPaths=Wt(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Ut(t.projectRoot),this.extraIgnore=MA(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=_A(this.projectRoot,{recursive:!0},(n,i)=>{i&&!this.stopped&&this.handleFileChange(i)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=FA(this.projectRoot,$A(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let i=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:i}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-t;this.dirty=!0;let r=Date.now()+i;this.setStatus({state:"cooldown",until:r,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let r=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:r,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let i=Date.now(),r=this.indexPaths.dbPath+".tmp",o=OA(this.indexPaths.indexPath),s=AA(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:o,SCIP_REINDEX_OUTPUT_DB:r,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{Yg(r)&&Zg(r,this.indexPaths.dbPath),Yg(o)&&Zg(o,this.indexPaths.indexPath),t(Date.now()-i)}catch(c){n(new Error(`Atomic swap failed: ${c}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),s.on("error",n)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}};function OA(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{existsSync as QA}from"fs";import{existsSync as jA,mkdirSync as BA,readFileSync as HA,writeFileSync as VA}from"fs";import{dirname as qA,join as eh}from"path";function nh(e){let t={markdownPath:eh(e.projectRoot,"docs","scip-query","health-dossier.md"),jsonPath:eh(e.projectRoot,"docs","scip-query","health-dossier.json"),status:"written",written:[],unchanged:[]},n={...e,healthDossier:t};try{return th(t.markdownPath,UA(n),t),th(t.jsonPath,`${JSON.stringify(n,null,2)}
791
+ `,t),t}catch(i){return{...t,status:"failed",error:i instanceof Error?i.message:String(i)}}}function UA(e){return`${["# scip-query Health Dossier","",`Generated: ${new Date().toISOString()}`,`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${KA(e)}`,"","## Items That Need Attention","",...WA(e),"","## Blocked Or Unavailable Checks","",...GA(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...zA(e),"","## JSON","",`Machine-readable report: \`${JA(e)}\``,""].join(`
792
+ `)}`}function WA(e){return e.health.issuesNeedAttention.length===0?["No prioritized health actions were reported."]:e.health.issuesNeedAttention.map(t=>`- ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort}, evidence ${t.evidence}; confirmation ${t.confirmationStatus}; safe to start ${t.safeForAgentToStart?"yes":"no"}). ${t.recommendedNextStep}`)}function GA(e){let t=[...e.smokeTests.filter(n=>n.status!=="pass").map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),...e.indexerRemediation.filter(n=>!n.after.runnable).map(n=>`- BLOCKED ${n.language}: ${n.recovery??`Install ${n.binaryLabel}.`}`)];return t.length>0?t:["No blocked or unavailable setup checks were reported."]}function zA(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",i=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${i})`})}function KA(e){return e.health.score===null?`unavailable (${e.health.unavailableReason??"not checked"})`:`${e.health.score} (risk ${e.health.riskScore}, hygiene ${e.health.hygieneScore})`}function JA(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function th(e,t,n){if(BA(qA(e),{recursive:!0}),(jA(e)?HA(e,"utf-8"):null)===t){n.unchanged.push(e);return}VA(e,t),n.written.push(e)}async function ah(e={}){let t=[],{projectRoot:n,config:i,paths:r,dbPath:o}=gi(),s=kr();Q(t,{id:"scip-cli",label:"scip CLI",status:s?"ok":"warn",message:s?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let a=ps({quiet:!0});Q(t,{id:"skills",label:"Agent skills",status:a.skipped.length>0?"warn":"ok",message:`${a.installed.length} installed, ${a.alreadyLinked.length} already linked, ${a.skipped.length} skipped.`,details:a.skipped.map(k=>`Skipped ${k}`)});let c=fi(i,{projectRoot:n}),l=c.filter(k=>k.level==="error");Q(t,{id:"config",label:"Project config",status:l.length>0?"failed":c.length>0?"warn":"ok",message:c.length===0?"Config OK.":`${c.length} diagnostic(s), ${l.length} error(s).`,details:c.map(k=>`${k.level.toUpperCase()} ${k.path}: ${k.message}`)});let u=ft(n,i);Q(t,{id:"readiness",label:"Indexer readiness",status:u.languages.length===0?"failed":u.indexers.some(k=>!k.runnable)?"warn":"ok",message:u.languages.length===0?"No supported project languages detected.":`Detected languages: ${u.languages.join(", ")}`,details:u.indexers.map(k=>`${k.runnable?"OK":k.installed?"WARN":"MISSING"} ${k.language}: ${k.binaryLabel}${k.note?` - ${k.note}`:""}`)});let d=oM(n,u,t),m=ft(n,i),p=null;if(m.languages.length===0||l.length>0)Q(t,{id:"reindex",label:"Index refresh",status:"skipped",message:m.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."});else{let k=[];try{p=await ys({projectRoot:n,languages:m.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:i.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!0,allowPartial:!0,onStatus:A=>k.push(A)}),Q(t,{id:"reindex",label:"Index refresh",status:p.skipped.length>0?"warn":"ok",message:`${p.reused?"Reused":"Indexed"} ${p.languages.join(", ")} in ${(p.durationMs/1e3).toFixed(1)}s.`,details:[...k,...p.skipped.map(A=>`Skipped ${A.language}: ${A.reason}`)]})}catch(A){Q(t,{id:"reindex",label:"Index refresh",status:"failed",message:xs(A),details:k})}}let h=ft(n,i),g=Nn(h),b=yi(n,i,r);Q(t,{id:"capabilities",label:"Capability matrix",status:uM(g),message:dM(g)});let S=aM(r.dbPath,t),x=null;try{x=us(n),Q(t,{id:"project-hooks",label:"Project agent hooks",status:x.skipped.length>0?"warn":"ok",message:`${x.installed.length} installed, ${x.updated.length} updated, ${x.unchanged.length} already configured, ${x.removed.length} legacy user hook config(s) cleaned up, ${x.skipped.length} skipped.`,details:[...x.removed.map(k=>`Removed legacy user-level ${k}`),...x.skipped.map(k=>`Skipped ${k.target}: ${k.reason}`)]})}catch(k){Q(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:xs(k)})}let I=null;try{I=ls(n,{gitHook:e.gitHook}),Q(t,{id:"agent-guidance",label:"Project agent guidance",status:I.skipped.length>0?"warn":"ok",message:`${I.written.length} written, ${I.unchanged.length} already wired, ${I.skipped.length} skipped.`,details:I.skipped.map(k=>`Skipped ${k.target}: ${k.reason}`)})}catch(k){Q(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:xs(k)})}let L=XA({reindexResult:p,readiness:h,capabilities:g,freshness:b,health:S,hooksResult:x,agentResult:I,steps:t});Q(t,{id:"smoke-tests",label:"Setup smoke tests",status:YA(L),message:ZA(L),details:L.map(k=>`${k.command}: ${k.status} - ${k.evidence}`)});let C={projectRoot:n,dbPath:o,configuredDbPath:r.dbPath,scipCliInstalled:s,languages:h.languages,steps:t,skills:a,initialReadiness:u,indexerRemediation:d,readiness:h,capabilities:g,freshness:b,reindex:p,health:S,smokeTests:L,healthDossier:null,hooks:x,setupAgent:I,filesWritten:I?.written??[],verdict:sh(t,h)},D=nh(C);return C.healthDossier=D,C.filesWritten=[...C.filesWritten,...D.written],Q(t,{id:"health-dossier",label:"Health dossier",status:D.status==="failed"?"failed":"ok",message:D.status==="failed"?D.error:`${D.written.length} written, ${D.unchanged.length} unchanged.`,details:[D.markdownPath,D.jsonPath]}),C.verdict=sh(t,h),C}function ch(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${mM(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function XA(e){let t=e.steps.find(r=>r.id==="reindex"),n=e.steps.find(r=>r.id==="project-hooks"),i=e.steps.find(r=>r.id==="agent-guidance");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="missing"?"fail":"pass",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:eM(e.steps),evidence:tM(e.steps)},{id:"capabilities",command:"scip-query capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"scip-query capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?nM(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"scip-query diff-impact --json",status:ih(e.readiness,e.freshness),evidence:rh(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:ih(e.readiness,e.freshness),evidence:rh(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:iM(e.capabilities),evidence:rM(e.capabilities)},{id:"setup-hooks",command:"scip-query setup-hooks",status:e.hooksResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.hooksResult?`${e.hooksResult.installed.length} installed, ${e.hooksResult.updated.length} updated, ${e.hooksResult.unchanged.length} already configured.`:n?.message??"Project agent hooks were not configured."},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":i?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:i?.message??"Project agent guidance was not written."}]}function YA(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function ZA(e){let t=e.filter(r=>r.status==="pass").length,n=e.filter(r=>r.status==="unavailable").length,i=e.filter(r=>r.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function eM(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function tM(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function nM(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(i=>i.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function ih(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function rh(e,t){return e.gitAvailable?`Git is available and index freshness is ${t.state}: ${t.reason}`:"Git is not available for this project."}function iM(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function rM(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(r=>r.cleanupVerification.status==="available").length,n=e.matrix.filter(r=>r.cleanupVerification.status==="partial").length,i=e.matrix.filter(r=>r.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function oM(e,t,n){let i=[];if(t.languages.length===0)return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=Pn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=os(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let d=sM(rs(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:d,messages:c,recovery:d.runnable?void 0:d.note??d.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let r=i.filter(s=>!s.after.runnable),o=i.filter(s=>s.attempted);return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:r.length>0?"warn":"ok",message:r.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${r.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function sM(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}function aM(e,t){if(!QA(e)){let n="Skipped because no SQLite index database exists yet.";return Q(t,{id:"health",label:"Health audit",status:"skipped",message:n}),oh(n)}try{let n=Zo({full:!0,json:!0});return Q(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),cM(n)}catch(n){let i=xs(n);return Q(t,{id:"health",label:"Health audit",status:"failed",message:i}),oh(i)}}function cM(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(lM),warnings:e.warnings??[]}}function lM(e){return{category:e.category,description:e.description,count:e.count,impact:e.impact,effort:e.effort,evidence:e.evidence,locRecoverable:e.locRecoverable,confirmationStatus:"unconfirmed",safeForAgentToStart:!1,recommendedNextStep:"Run scip-health-audit to confirm this signal; use scip-health-improve when the user wants confirmed issues fixed autonomously."}}function oh(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function sh(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function uM(e){let t=e.matrix.flatMap(n=>[n.indexing.status,n.sourceFacts.status,n.semantic.status,n.cleanupVerification.status]);return t.some(n=>n==="unavailable")||t.some(n=>n==="partial")?"warn":"ok"}function dM(e){return e.matrix.length===0?"No language capability rows.":`${e.matrix.filter(n=>n.indexing.status==="available").length}/${e.matrix.length} language(s) have available indexing.`}function mM(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Q(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function xs(e){return e instanceof Error?e.message:String(e)}import{existsSync as pM,mkdirSync as fM,writeFileSync as gM}from"fs";import{dirname as hM,join as bM}from"path";function lh(e,t={}){let n=bM(e,".github","workflows","scip-query.yml"),i=yM();return pM(n)&&!t.force?{path:n,written:!1,skipped:!0,content:i,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(fM(hM(n),{recursive:!0}),gM(n,i)),{path:n,written:!t.dryRun,skipped:!1,content:i})}function yM(){return`name: scip-query
792
793
 
793
794
  on:
794
795
  pull_request:
@@ -806,44 +807,44 @@ jobs:
806
807
  - run: npm ci
807
808
  - run: npx scip-query reindex
808
809
  - run: npx scip-query diff-gate --base "origin/\${{ github.base_ref }}"
809
- `}var ih=Symbol("option-value-source");function z(e){return(...t)=>{let{args:n,opts:i}=uM(t);pt(r=>e({db:r,args:n,opts:i}))}}function X(e,t){return z(n=>{let i=bf(n.db,e,R(n.opts,"full"),{quiet:R(n.opts,"json")});t({...n,budget:i})})}function rh(e){return z(t=>Ri(t,e,{kind:"list"}))}function oh(e){return z(t=>Ri(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function sh(e){return z(t=>Ri(t,e,{kind:"grouped",key:e.key}))}function _n(e){return z(t=>vl(t,e))}function ah(e){return _n({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>P.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function Ke(e,t){return X(e,n=>vl(n,{...t,commandName:t.commandName??e}))}function ch(e,t){return Ke(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,i)=>P.sectionedReport(t.sections(n,i)),toJson:t.toJson,after:t.after})}function Nt(e,t){return X(e,n=>Ri(n,{...t,commandName:e},{kind:"list"}))}function ys(e,t){return X(e,n=>Ri(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Ss(e,t){return X(e,n=>Ri(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function H(e,t){return String(e[t])}function le(e,t){let n=e[t];return typeof n=="string"?n:void 0}function E(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Ee(e,t){let n=e[t];return typeof n=="number"?n:void 0}function R(e,t){return!!e[t]}function lh(e,t){let n=e[t];return Array.isArray(n)&&n.every(i=>typeof i=="string")?n:[]}function N(e,t,n){return Ee(e,t)??n}function O(e,t,n){let i=Ee(e,t),r=i!==void 0&&Cl(e,t)!=="default";if(R(e,"full")){if(r)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.POSITIVE_INFINITY}return i??n}function Cl(e,t){return e[ih]?.(t)}function Ri(e,t,n){vl(e,{commandName:t.commandName,query:t.query,emptyMessage:(i,r)=>i.length===0&&t.emptyMessage?t.emptyMessage(r):void 0,heuristicLabel:t.heuristicLabel,render:(i,r)=>{n.kind==="list"?P.list(i,o=>t.format(o,r)):n.kind==="table"?P.table(n.headers,i.map(o=>t.format(o,r)),n.dashWidths):P.groupedByFile(i,o=>t.format(o,r),n.key?o=>n.key(o,r):void 0)},toJson:t.toJson,after:t.after})}function vl(e,t){let n=t.query(e);if(R(e.opts,"json")){$(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let i=t.emptyMessage?.(n,e);if(i){P.empty(i);return}t.heuristicLabel&&bi(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function $(e,t,n,i){console.log(JSON.stringify({command:e,args:lM(t),options:n,result:i},null,2))}function lM(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function uM(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:ue(t)}}function ue(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,ih,{value:i=>t.getOptionValueSource(i),enumerable:!1}),n)}return e}var mM=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function pM(e){return e.filter(t=>mM.has(t))}async function uh(e){let t=ue(e),n=be(),i=tt(n),r=Wt(n,i);try{let o=pM(lh(t,"language")),s=await gs({projectRoot:n,languages:o.length>0?o:i.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:R(t,"pnpmWorkspaces")||i.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!R(t,"force"),allowPartial:R(t,"allowPartial"),indexerConcurrency:Ee(t,"indexerConcurrency")});console.log(`${s.reused?"Reused":"Indexed"} ${s.languages.join(", ")} in ${(s.durationMs/1e3).toFixed(1)}s`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function dh(){let e=be(),t=Ac(e);try{let n=Gt({projectRoot:e,dbPath:t,onStatus:i=>console.log(i)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function mh(e){let t=ue(e),n=be(),i=Ac(n);try{let r=hl({projectRoot:n,dbPath:i,tsconfig:E(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${r.vueFiles}; resolved references: ${r.resolvedReferences}; inserted mentions: ${r.insertedMentions}.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}}function ph(e){let t=ue(e);pt(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=ut(n,{base:E(t,"base")}),o=Po(n,i,r.changedFiles,r.changedRanges);console.log(JSON.stringify(o))})}function fh(e){let t=ue(e);try{let n=Sf({base:E(t,"base")});if(R(t,"json")){$("diff-impact",[],t,n);return}xf(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function gh(e,t){let n=ue(t);pt(i=>{hr.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let r=vc(i,e,{scope:E(n,"scope"),full:R(n,"full")});console.log(JSON.stringify(r))})}function hh(e){let t=ue(e);if(R(t,"writeBaseline")||R(t,"baseline")){fM(t);return}try{let n=Yo({scope:E(t,"scope"),full:!0,json:R(t,"json")});if(R(t,"json")){$("health",[],t,n);return}yf(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function fM(e){let t=E(e,"scope");pt(n=>{if(R(e,"writeBaseline")){let r=hc(n,{scope:t});console.log(`Baseline written to ${r.path} (${r.findingCount} finding(s)).`);return}let i=cr(n,{scope:t});if(i.fixedFindings.length>0&&console.log(`${i.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),i.newFindings.length===0){console.log(`OK: no new findings vs baseline (${i.baselineCount} baselined, ${i.current.length} current).`);return}console.log(`FAIL: ${i.newFindings.length} new finding(s) vs ${i.baselinePath}:`);for(let r of i.newFindings)console.log(` + ${r}`);process.exitCode=1})}function bh(){let e=us(),t=e.installed.length+e.alreadyLinked.length;console.log(`
810
- ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function yh(e){let t=ue(e),n=be(),i=ls(n);if(R(t,"json")){$("setup-hooks",[],t,i);return}for(let o of i.installed)console.log(` done: ${o}`);for(let o of i.updated)console.log(` update: ${o}`);for(let o of i.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of i.removed)console.log(` remove: legacy user-level ${o}`);for(let o of i.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);i.installed.length+i.updated.length+i.unchanged.length>0?(console.log(`
810
+ `}var uh=Symbol("option-value-source");function z(e){return(...t)=>{let{args:n,opts:i}=xM(t);mt(r=>e({db:r,args:n,opts:i}))}}function X(e,t){return z(n=>{let i=xf(n.db,e,R(n.opts,"full"),{quiet:R(n.opts,"json")});t({...n,budget:i})})}function dh(e){return z(t=>Ri(t,e,{kind:"list"}))}function mh(e){return z(t=>Ri(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function ph(e){return z(t=>Ri(t,e,{kind:"grouped",key:e.key}))}function _n(e){return z(t=>wl(t,e))}function fh(e){return _n({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>P.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function ze(e,t){return X(e,n=>wl(n,{...t,commandName:t.commandName??e}))}function gh(e,t){return ze(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,i)=>P.sectionedReport(t.sections(n,i)),toJson:t.toJson,after:t.after})}function Nt(e,t){return X(e,n=>Ri(n,{...t,commandName:e},{kind:"list"}))}function Cs(e,t){return X(e,n=>Ri(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function vs(e,t){return X(e,n=>Ri(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function H(e,t){return String(e[t])}function le(e,t){let n=e[t];return typeof n=="string"?n:void 0}function E(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Ee(e,t){let n=e[t];return typeof n=="number"?n:void 0}function R(e,t){return!!e[t]}function hh(e,t){let n=e[t];return Array.isArray(n)&&n.every(i=>typeof i=="string")?n:[]}function N(e,t,n){return Ee(e,t)??n}function O(e,t,n){let i=Ee(e,t),r=i!==void 0&&kl(e,t)!=="default";if(R(e,"full")){if(r)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.POSITIVE_INFINITY}return i??n}function kl(e,t){return e[uh]?.(t)}function Ri(e,t,n){wl(e,{commandName:t.commandName,query:t.query,emptyMessage:(i,r)=>i.length===0&&t.emptyMessage?t.emptyMessage(r):void 0,heuristicLabel:t.heuristicLabel,render:(i,r)=>{n.kind==="list"?P.list(i,o=>t.format(o,r)):n.kind==="table"?P.table(n.headers,i.map(o=>t.format(o,r)),n.dashWidths):P.groupedByFile(i,o=>t.format(o,r),n.key?o=>n.key(o,r):void 0)},toJson:t.toJson,after:t.after})}function wl(e,t){let n=t.query(e);if(R(e.opts,"json")){F(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let i=t.emptyMessage?.(n,e);if(i){P.empty(i);return}t.heuristicLabel&&bi(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function F(e,t,n,i){console.log(JSON.stringify({command:e,args:SM(t),options:n,result:i},null,2))}function SM(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function xM(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:ue(t)}}function ue(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,uh,{value:i=>t.getOptionValueSource(i),enumerable:!1}),n)}return e}var vM=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function RM(e){return e.filter(t=>vM.has(t))}async function bh(e){let t=ue(e),n=be(),i=et(n),r=Wt(n,i);try{let o=RM(hh(t,"language")),s=await ys({projectRoot:n,languages:o.length>0?o:i.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:R(t,"pnpmWorkspaces")||i.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!R(t,"force"),allowPartial:R(t,"allowPartial"),indexerConcurrency:Ee(t,"indexerConcurrency")});console.log(`${s.reused?"Reused":"Indexed"} ${s.languages.join(", ")} in ${(s.durationMs/1e3).toFixed(1)}s`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function yh(){let e=be(),t=jc(e);try{let n=Gt({projectRoot:e,dbPath:t,onStatus:i=>console.log(i)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Sh(e){let t=ue(e),n=be(),i=jc(n);try{let r=Sl({projectRoot:n,dbPath:i,tsconfig:E(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${r.vueFiles}; resolved references: ${r.resolvedReferences}; inserted mentions: ${r.insertedMentions}.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}}function xh(e){let t=ue(e);mt(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=lt(n,{base:E(t,"base")}),o=No(n,i,r.changedFiles,r.changedRanges);console.log(JSON.stringify(o))})}function Ch(e){let t=ue(e);try{let n=vf({base:E(t,"base")});if(R(t,"json")){F("diff-impact",[],t,n);return}Rf(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function vh(e,t){let n=ue(t);mt(i=>{hr.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let r=wc(i,e,{scope:E(n,"scope"),full:R(n,"full")});console.log(JSON.stringify(r))})}function Rh(e){let t=ue(e);if(R(t,"writeBaseline")||R(t,"baseline")){kM(t);return}try{let n=Zo({scope:E(t,"scope"),full:!0,json:R(t,"json")});if(R(t,"json")){F("health",[],t,n);return}Cf(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function kM(e){let t=E(e,"scope");mt(n=>{if(R(e,"writeBaseline")){let r=Sc(n,{scope:t});console.log(`Baseline written to ${r.path} (${r.findingCount} finding(s)).`);return}let i=cr(n,{scope:t});if(i.fixedFindings.length>0&&console.log(`${i.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),i.newFindings.length===0){console.log(`OK: no new findings vs baseline (${i.baselineCount} baselined, ${i.current.length} current).`);return}console.log(`FAIL: ${i.newFindings.length} new finding(s) vs ${i.baselinePath}:`);for(let r of i.newFindings)console.log(` + ${r}`);process.exitCode=1})}function kh(){let e=ps(),t=e.installed.length+e.alreadyLinked.length;console.log(`
811
+ ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function wh(e){let t=ue(e),n=be(),i=us(n);if(R(t,"json")){F("setup-hooks",[],t,i);return}for(let o of i.installed)console.log(` done: ${o}`);for(let o of i.updated)console.log(` update: ${o}`);for(let o of i.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of i.removed)console.log(` remove: legacy user-level ${o}`);for(let o of i.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);i.installed.length+i.updated.length+i.unchanged.length>0?(console.log(`
811
812
  Project-local scip-query hooks are configured for this repository.`),console.log("Review new or changed hooks in Codex/Claude Code with /hooks before they run.")):console.log(`
812
- No project-local hook config was written.`)}function Sh(){let e=!1;Rr()?console.log("scip CLI: installed"):(il(),e=!0);let t=be(),n=tt(t),i=ft(t,n);if(i.languages.length===0){console.log(`
813
+ No project-local hook config was written.`)}function Lh(){let e=!1;kr()?console.log("scip CLI: installed"):(sl(),e=!0);let t=be(),n=et(t),i=ft(t,n);if(i.languages.length===0){console.log(`
813
814
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
814
815
  Detected languages: ${i.languages.join(", ")}`),console.log(`
815
816
  Indexer readiness:`);for(let r of i.indexers){let o=r.runnable?" OK":r.installed?" WARN":" MISSING",s=r.resolvedBinary?` (${r.resolvedBinary})`:"";console.log(`${o} ${r.language}: ${r.binaryLabel}${s}`),r.note&&console.log(` ${r.note}`),!r.installed&&r.installUrl&&console.log(` install: ${r.installUrl}`),r.runnable||(e=!0)}if(i.semantic){let r=i.semantic,o=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING",s=r.tsconfigPaths&&r.tsconfigPaths.length>1?` (${r.tsconfigPaths.length} tsconfigs)`:r.tsconfigPath?` (${r.tsconfigPath})`:"";console.log(`
816
- Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),r.reason&&console.log(` ${r.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function xh(e){vh(e,"capabilities")}function Ch(e){vh(e,"capability-matrix")}function vh(e,t){let n=ue(e),i=be(),r=tt(i),o=ft(i,r),s=Nn(o);if(R(n,"json")){$(t,[],n,s);return}Rl(s)}function Rh(){let e=be(),t=Dt(e),n=uf(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function kh(e){let t=ue(e),n=be(),i=tt(n),r=fi(i,{projectRoot:n});if(R(t,"json"))$("config-validate",[],t,{diagnostics:r});else if(r.length===0)console.log("Config OK.");else for(let o of r)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);r.some(o=>o.level==="error")&&(process.exitCode=1)}function wh(e,t){let n=ue(t),i=E(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let r=df(be(),{id:String(e),check:E(n,"check"),file:E(n,"file"),reason:i,expiresAt:E(n,"expiresAt")});if(R(n,"json")){$("suppress",[String(e)],n,r);return}console.log(`Suppression added to ${r.path} (${r.suppressionCount} total).`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exitCode=1}}function Lh(e){let t=ue(e),{report:n,hasIndexerProblems:i,hasErrors:r}=Dh("doctor");R(t,"json")?$("doctor",[],t,n):gM(n,i),process.exitCode=r?1:0}function Dh(e){let{projectRoot:t,config:n,paths:i,dbPath:r}=gi(),o=fi(n,{projectRoot:t}),s=ft(t,n),a=Nn(s),c=yi(t,n,i),l=s.indexers.some(d=>!d.runnable),u=o.some(d=>d.level==="error")||l||c.state==="missing"||c.state==="stale";return{report:{command:e,projectRoot:t,dbPath:r,configuredDbPath:i.dbPath,exists:dM(r),configDiagnostics:o,readiness:s,freshness:c,capabilities:a,ok:!u},hasIndexerProblems:l,hasErrors:u}}function Ih(e){let t=ue(e),n=be(),i=cs(n,{gitHook:R(t,"gitHook")});for(let r of i.written)console.log(` done: ${r}`);for(let r of i.unchanged)console.log(` ok: ${r} (already wired)`);for(let r of i.skipped)console.log(` skip: ${r.target} \u2014 ${r.reason}`);console.log(`
817
- Agents reading this project now know to route through the scip-query skills and gate their diffs.`),console.log("Keep the index fresh (`scip-query reindex` or `scip-query watch`) so the gate sees current code.")}async function Ph(e){let t=ue(e);try{let n=await eh({gitHook:R(t,"gitHook")});R(t,"json")?$("setup",[],t,n):th(n),process.exitCode=n.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Nh(e){let t=ue(e),n=be(),i=nh(n,{force:R(t,"force"),dryRun:R(t,"dryRun")});if(R(t,"dryRun")){console.log(i.content);return}if(i.skipped){console.log(`skip: ${i.path} \u2014 ${i.reason}`);return}console.log(`done: ${i.path}`)}function Eh(e){let t=ue(e),n=be(),i=tt(n),r=Ee(t,"debounce"),o=Ee(t,"cooldown");r&&((i.watch??={}).debounceMs=r),o&&((i.watch??={}).cooldownMs=o);let s=new hs({projectRoot:n,config:i,languages:i.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${pf(a)}`)},onReindexComplete:a=>{console.log(`
817
+ Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),r.reason&&console.log(` ${r.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function Dh(e){Ph(e,"capabilities")}function Ih(e){Ph(e,"capability-matrix")}function Ph(e,t){let n=ue(e),i=be(),r=et(i),o=ft(i,r),s=Nn(o);if(R(n,"json")){F(t,[],n,s);return}Ll(s)}function Nh(){let e=be(),t=Dt(e),n=pf(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Eh(e){let t=ue(e),n=be(),i=et(n),r=fi(i,{projectRoot:n});if(R(t,"json"))F("config-validate",[],t,{diagnostics:r});else if(r.length===0)console.log("Config OK.");else for(let o of r)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);r.some(o=>o.level==="error")&&(process.exitCode=1)}function Th(e,t){let n=ue(t),i=E(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let r=ff(be(),{id:String(e),check:E(n,"check"),file:E(n,"file"),reason:i,expiresAt:E(n,"expiresAt")});if(R(n,"json")){F("suppress",[String(e)],n,r);return}console.log(`Suppression added to ${r.path} (${r.suppressionCount} total).`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exitCode=1}}function _h(e){let t=ue(e),{report:n,hasIndexerProblems:i,hasErrors:r}=$h("doctor");R(t,"json")?F("doctor",[],t,n):wM(n,i),process.exitCode=r?1:0}function $h(e){let{projectRoot:t,config:n,paths:i,dbPath:r}=gi(),o=fi(n,{projectRoot:t}),s=ft(t,n),a=Nn(s),c=yi(t,n,i),l=s.indexers.some(d=>!d.runnable),u=o.some(d=>d.level==="error")||l||c.state==="missing"||c.state==="stale";return{report:{command:e,projectRoot:t,dbPath:r,configuredDbPath:i.dbPath,exists:CM(r),configDiagnostics:o,readiness:s,freshness:c,capabilities:a,ok:!u},hasIndexerProblems:l,hasErrors:u}}function Fh(e){let t=ue(e),n=be(),i=ls(n,{gitHook:R(t,"gitHook")});for(let r of i.written)console.log(` done: ${r}`);for(let r of i.unchanged)console.log(` ok: ${r} (already wired)`);for(let r of i.skipped)console.log(` skip: ${r.target} \u2014 ${r.reason}`);console.log(`
818
+ Agents reading this project now know to route through the scip-query skills and gate their diffs.`),console.log("Keep the index fresh (`scip-query reindex` or `scip-query watch`) so the gate sees current code.")}async function Ah(e){let t=ue(e);try{let n=await ah({gitHook:R(t,"gitHook")});R(t,"json")?F("setup",[],t,n):ch(n),process.exitCode=n.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Mh(e){let t=ue(e),n=be(),i=lh(n,{force:R(t,"force"),dryRun:R(t,"dryRun")});if(R(t,"dryRun")){console.log(i.content);return}if(i.skipped){console.log(`skip: ${i.path} \u2014 ${i.reason}`);return}console.log(`done: ${i.path}`)}function Oh(e){let t=ue(e),n=be(),i=et(n),r=Ee(t,"debounce"),o=Ee(t,"cooldown");r&&((i.watch??={}).debounceMs=r),o&&((i.watch??={}).cooldownMs=o);let s=new Ss({projectRoot:n,config:i,languages:i.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${hf(a)}`)},onReindexComplete:a=>{console.log(`
818
819
  Reindex complete in ${(a/1e3).toFixed(1)}s`)},onError:a=>{console.error(`
819
820
  Watch error: ${a.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${i.watch?.debounceMs??3e4}ms | Cooldown: ${i.watch?.cooldownMs??6e4}ms`),console.log(`Press Ctrl+C to stop.
820
821
  `),s.start(),process.on("SIGINT",()=>{s.stop(),console.log(`
821
- Stopped.`),process.exit(0)})}function Th(e){let t=ue(e),{report:n}=Dh("status");if(R(t,"json")){$("status",[],t,{...n,stats:bM(n.exists)});return}hM(n,{capabilities:R(t,"capabilities")})}function gM(e,t){console.log(`Doctor: ${e.ok?"OK":"needs attention"}`);for(let n of e.configDiagnostics)console.log(` ${n.level.toUpperCase()} ${n.path}: ${n.message}`);if(t)for(let n of e.readiness.indexers.filter(i=>!i.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),Rl(e.capabilities)}function hM(e,t){if(console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`),e.readiness.semantic){let n=e.readiness.semantic.available?"available":"fallback",i=e.readiness.semantic.tsconfigPaths&&e.readiness.semantic.tsconfigPaths.length>1?` (${e.readiness.semantic.tsconfigPaths.length} tsconfigs)`:e.readiness.semantic.tsconfigPath?` (${e.readiness.semantic.tsconfigPath})`:"";console.log(`TS sem: ${n}${i}`),e.readiness.semantic.reason&&console.log(`TS note: ${e.readiness.semantic.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),yM(e.exists),t.capabilities&&(console.log(""),Rl(e.capabilities))}function bM(e){if(e)return pt(t=>{let n=Oe(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function yM(e){e&&pt(t=>{let n=Oe(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${hi(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function Rl(e){console.log(`Capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);if(e.matrix.length!==0){console.log(`
822
- Language matrix:`);for(let t of e.matrix){console.log(` ${t.language}`);for(let n of[t.indexing,t.sourceFacts,t.semantic,t.detectors,t.cleanupVerification])console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.label}`),console.log(` ${n.reason}`)}}}function wr(e){return{...e,options:_(e.options)}}function ht({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,...o}){let s=wr(o);return{...s,renderShape:"list",handler:rh({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r})}}function xs({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s,...a}){let c=wr(a);return{...c,renderShape:"table",handler:oh({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s})}}function _h({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o,...s}){let a=wr(s);return{...a,renderShape:"grouped-by-file",handler:sh({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o})}}function Fh({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=wr(s);return{...a,renderShape:"sectioned-report",handler:ah({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function Cs({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=wr(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:ch(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function kl(e,t,n,i){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${i} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let r=new Map;for(let a of e){let c=r.get(a.relativePath)??[];c.push(a),r.set(a.relativePath,c)}let o=[...r.entries()].map(([a,c])=>({file:a,bucket:c,totalLoc:c.reduce((l,u)=>l+u.loc,0)})).sort((a,c)=>c.totalLoc-a.totalLoc||a.file.localeCompare(c.file)),s=!0;for(let{file:a,bucket:c}of o){s||console.log(""),s=!1,console.log(` ${a}`),c.sort((l,u)=>l.startLine-u.startLine);for(let l of c)console.log(` ${ve(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var $h=X("dead",({db:e,args:t,opts:n,budget:i})=>{let r={scope:le(t,0)||void 0,minLoc:N(n,"minLoc",1),includeTests:R(n,"includeTests"),skipBarrels:R(n,"skipBarrels"),includeMembers:R(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},o=Rt(e,r),s=o.symbols.filter(b=>b.kind==="dead-code"),a=o.symbols.filter(b=>b.kind!=="dead-code"),c=!R(n,"onlyInternal"),l=!R(n,"onlyDead"),u=c?s:[],d=l?a:[],m=u.reduce((b,S)=>b+S.loc,0),p=d.reduce((b,S)=>b+S.loc,0),h={total:u.length+d.length,deadCode:u.length,fileInternal:d.length,loc:m+p};if(R(n,"json")){$("dead",t,n,{...o,shown:{deadCode:u,fileInternal:d},shownCounts:h,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,loc:o.counts.loc}});return}if(u.length===0&&d.length===0){P.empty("No matching dead-code symbols found.");return}u.length>0&&kl(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
823
- Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),kl(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
822
+ Stopped.`),process.exit(0)})}function jh(e){let t=ue(e),{report:n}=$h("status");if(R(t,"json")){F("status",[],t,{...n,stats:DM(n.exists)});return}LM(n,{capabilities:R(t,"capabilities")})}function wM(e,t){console.log(`Doctor: ${e.ok?"OK":"needs attention"}`);for(let n of e.configDiagnostics)console.log(` ${n.level.toUpperCase()} ${n.path}: ${n.message}`);if(t)for(let n of e.readiness.indexers.filter(i=>!i.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),Ll(e.capabilities)}function LM(e,t){if(console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`),e.readiness.semantic){let n=e.readiness.semantic.available?"available":"fallback",i=e.readiness.semantic.tsconfigPaths&&e.readiness.semantic.tsconfigPaths.length>1?` (${e.readiness.semantic.tsconfigPaths.length} tsconfigs)`:e.readiness.semantic.tsconfigPath?` (${e.readiness.semantic.tsconfigPath})`:"";console.log(`TS sem: ${n}${i}`),e.readiness.semantic.reason&&console.log(`TS note: ${e.readiness.semantic.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),IM(e.exists),t.capabilities&&(console.log(""),Ll(e.capabilities))}function DM(e){if(e)return mt(t=>{let n=Oe(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function IM(e){e&&mt(t=>{let n=Oe(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${hi(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function Ll(e){console.log(`Capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);if(e.matrix.length!==0){console.log(`
823
+ Language matrix:`);for(let t of e.matrix){console.log(` ${t.language}`);for(let n of[t.indexing,t.sourceFacts,t.semantic,t.detectors,t.cleanupVerification])console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.label}`),console.log(` ${n.reason}`)}}}function Lr(e){return{...e,options:_(e.options)}}function ht({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,...o}){let s=Lr(o);return{...s,renderShape:"list",handler:dh({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r})}}function Rs({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s,...a}){let c=Lr(a);return{...c,renderShape:"table",handler:mh({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s})}}function Bh({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o,...s}){let a=Lr(s);return{...a,renderShape:"grouped-by-file",handler:ph({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o})}}function Hh({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=Lr(s);return{...a,renderShape:"sectioned-report",handler:fh({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function ks({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=Lr(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:gh(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function Dl(e,t,n,i){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${i} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let r=new Map;for(let a of e){let c=r.get(a.relativePath)??[];c.push(a),r.set(a.relativePath,c)}let o=[...r.entries()].map(([a,c])=>({file:a,bucket:c,totalLoc:c.reduce((l,u)=>l+u.loc,0)})).sort((a,c)=>c.totalLoc-a.totalLoc||a.file.localeCompare(c.file)),s=!0;for(let{file:a,bucket:c}of o){s||console.log(""),s=!1,console.log(` ${a}`),c.sort((l,u)=>l.startLine-u.startLine);for(let l of c)console.log(` ${ve(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var Vh=X("dead",({db:e,args:t,opts:n,budget:i})=>{let r={scope:le(t,0)||void 0,minLoc:N(n,"minLoc",1),includeTests:R(n,"includeTests"),skipBarrels:R(n,"skipBarrels"),includeMembers:R(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},o=Rt(e,r),s=o.symbols.filter(b=>b.kind==="dead-code"),a=o.symbols.filter(b=>b.kind!=="dead-code"),c=!R(n,"onlyInternal"),l=!R(n,"onlyDead"),u=c?s:[],d=l?a:[],m=u.reduce((b,S)=>b+S.loc,0),p=d.reduce((b,S)=>b+S.loc,0),h={total:u.length+d.length,deadCode:u.length,fileInternal:d.length,loc:m+p};if(R(n,"json")){F("dead",t,n,{...o,shown:{deadCode:u,fileInternal:d},shownCounts:h,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,loc:o.counts.loc}});return}if(u.length===0&&d.length===0){P.empty("No matching dead-code symbols found.");return}u.length>0&&Dl(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
824
+ Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),Dl(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
824
825
  single-use helper, an abstraction-in-progress, or a callback registered
825
826
  through a framework path that static analysis cannot trace (signal
826
827
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
827
828
  review case by case.`,p));let g=[];c&&g.push(`${u.length} dead code (${m} LOC)`),l&&g.push(`${d.length} file-internal (${p} LOC)`),console.log(`
828
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${u.length+d.length} symbols \u2014 ${g.join(" + ")}`)}),Ah=Nt("unused-imports",{query:({db:e,args:t,budget:n})=>Ra(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
829
- ${e.length} unused import(s)`)}),Mh=Ss("isolated",{query:({db:e,opts:t,budget:n})=>pn(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ve(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
830
- ${e.length} isolated symbol(s)`)}),Oh=X("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=yn(e,{scope:E(n,"scope"),minLoc:N(n,"minLoc",10),minCallees:N(n,"minCallees",6),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(R(n,"json")){$("extract-candidates",t,n,r);return}if(r.length===0)return P.empty("No extraction candidates found.");bi("extraction candidates");for(let o of r){console.log(`
829
+ \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${u.length+d.length} symbols \u2014 ${g.join(" + ")}`)}),qh=Nt("unused-imports",{query:({db:e,args:t,budget:n})=>La(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
830
+ ${e.length} unused import(s)`)}),Uh=vs("isolated",{query:({db:e,opts:t,budget:n})=>pn(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ve(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
831
+ ${e.length} isolated symbol(s)`)}),Wh=X("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=yn(e,{scope:E(n,"scope"),minLoc:N(n,"minLoc",10),minCallees:N(n,"minCallees",6),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(R(n,"json")){F("extract-candidates",t,n,r);return}if(r.length===0)return P.empty("No extraction candidates found.");bi("extraction candidates");for(let o of r){console.log(`
831
832
  ${ye(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<o.clusters.length;s++){let a=o.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
832
- ${r.length} extraction candidate(s) found.`)}),jh=X("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=Ja(e,{target:le(t,0)||void 0,scope:E(n,"scope"),minConsumers:N(n,"minConsumers",1),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(R(n,"json")){$("locality-candidates",t,n,r);return}if(r.length===0)return P.empty("No locality candidates found.");bi("locality candidates");for(let o of r){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?ye(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
833
+ ${r.length} extraction candidate(s) found.`)}),Gh=X("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=Ya(e,{target:le(t,0)||void 0,scope:E(n,"scope"),minConsumers:N(n,"minConsumers",1),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(R(n,"json")){F("locality-candidates",t,n,r);return}if(r.length===0)return P.empty("No locality candidates found.");bi("locality candidates");for(let o of r){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?ye(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
833
834
  ${s} ${o.sourceUnit.shortName}`),console.log(` Current directory: ${o.currentDirectory}; tier: ${o.recommendedTier}; action: ${o.actionTier}`),console.log(` Consumer coverage: ${o.consumerCoverage}; consumers: ${o.consumerFiles.length}`),o.nearestCommonOwner&&console.log(` Nearest common owner: ${o.nearestCommonOwner}`),o.suggestedHome&&console.log(` Suggested home: ${o.suggestedHome}`),o.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${o.whyNoSuggestedHome}`),o.boundaryMarkers.length>0&&console.log(` Boundary markers: ${o.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${o.recommendation}`),o.consumerFiles.length>0){for(let a of o.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);o.consumerFiles.length>8&&console.log(` - ... ${o.consumerFiles.length-8} more consumer(s)`)}for(let a of o.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
834
- ${r.length} locality candidate(s) found.`)}),Bh=Nt("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Ln(e,{scope:E(t,"scope"),maxLoc:N(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
835
+ ${r.length} locality candidate(s) found.`)}),zh=Nt("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Ln(e,{scope:E(t,"scope"),maxLoc:N(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
835
836
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
836
837
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
837
- ${e.length} wrapper candidate(s).`)}),Hh=Nt("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>kn(e,{scope:E(t,"scope"),maxLoc:N(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
838
+ ${e.length} wrapper candidate(s).`)}),Kh=Nt("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>kn(e,{scope:E(t,"scope"),maxLoc:N(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
838
839
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
839
840
  Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
840
841
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
841
842
  Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
842
- ${e.length} passthrough candidate(s).`)}),Vh=Nt("stale-abstractions",{query:({db:e,opts:t,budget:n})=>wn(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",3),limit:O(t,"limit",30),includeLowConfidence:R(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
843
+ ${e.length} passthrough candidate(s).`)}),Jh=Nt("stale-abstractions",{query:({db:e,opts:t,budget:n})=>wn(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",3),limit:O(t,"limit",30),includeLowConfidence:R(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${ye(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
843
844
  ${e.reason}
844
845
  Kind: ${e.stalenessKind}; tier: ${e.actionTier}
845
846
  Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
846
- ${e.length} stale abstraction(s).`)}),qh=ys("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>fr(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",10),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),Uh=Ke("similar",{query:({db:e,args:t,opts:n,budget:i})=>{let r=le(t,0);return r?{mode:"target",rows:Zi(e,r,{minSimilarity:N(n,"minSimilarity",.4),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:kt(e,{minSimilarity:N(n,"minSimilarity",.4),limit:O(n,"limit",20),scope:E(n,"scope"),minCallees:N(n,"minCallees",4),crossFileOnly:R(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.semantic})}},emptyMessage:e=>{if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="target"){P.list(e.rows,t=>{let n=t.similarityBasis??"callees",i=n==="source-tokens"?"Shared source tokens":"Shared callees",r=n==="source-tokens"?"Only tokens in":"Only in",o=[`
847
+ ${e.length} stale abstraction(s).`)}),Qh=Cs("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>fr(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",10),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),Xh=ze("similar",{query:({db:e,args:t,opts:n,budget:i})=>{let r=le(t,0);return r?{mode:"target",rows:Zi(e,r,{minSimilarity:N(n,"minSimilarity",.4),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:kt(e,{minSimilarity:N(n,"minSimilarity",.4),limit:O(n,"limit",20),scope:E(n,"scope"),minCallees:N(n,"minCallees",4),crossFileOnly:R(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.semantic})}},emptyMessage:e=>{if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="target"){P.list(e.rows,t=>{let n=t.similarityBasis??"callees",i=n==="source-tokens"?"Shared source tokens":"Shared callees",r=n==="source-tokens"?"Only tokens in":"Only in",o=[`
847
848
  ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${i}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${r} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${r} B: ${t.uniqueToB.join(", ")}`),o.join(`
848
849
  `)});return}P.list(e.rows,t=>`
849
850
  ${Math.round(t.similarity*100)}% similar:
@@ -853,85 +854,85 @@ ${Math.round(t.similarity*100)}% similar:
853
854
  Recommendation: ${t.recommendation}
854
855
  `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
855
856
  `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
856
- ${e.rows.length} similar pair(s) found.`)}}),Wh=_n({commandName:"similar-files",query:({db:e,args:t,opts:n})=>qa(e,{minSimilarity:N(n,"minSimilarity",.5),limit:O(n,"limit",20),scope:E(n,"scope"),minDeps:Ee(n,"minDeps"),filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{P.list(e,t=>{let n=[`
857
+ ${e.rows.length} similar pair(s) found.`)}}),Yh=_n({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Ga(e,{minSimilarity:N(n,"minSimilarity",.5),limit:O(n,"limit",20),scope:E(n,"scope"),minDeps:Ee(n,"minDeps"),filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{P.list(e,t=>{let n=[`
857
858
  ${Math.round(t.similarity*100)}% similar:`,` ${t.fileA}`,` ${t.fileB}`,` Shared deps (${t.sharedDeps.length}): ${t.sharedDeps.join(", ")}`];return t.uniqueToA.length&&n.push(` Only in first: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&n.push(` Only in second: ${t.uniqueToB.join(", ")}`),n.join(`
858
859
  `)}),console.log(`
859
- ${e.length} similar pair(s) found.`)}}),Gh=_n({commandName:"similar-chains",query:({db:e,opts:t})=>Ua(e,{minSimilarity:N(t,"minSimilarity",.5),limit:O(t,"limit",15),scope:E(t,"scope"),minChainLength:N(t,"minLength",3),maxChainLength:N(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
860
+ ${e.length} similar pair(s) found.`)}}),Zh=_n({commandName:"similar-chains",query:({db:e,opts:t})=>za(e,{minSimilarity:N(t,"minSimilarity",.5),limit:O(t,"limit",15),scope:E(t,"scope"),minChainLength:N(t,"minLength",3),maxChainLength:N(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
860
861
  \u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let i of n.divergencePoints)console.log(` [${i.index}] ${i.nodeA} \u2194 ${i.nodeB}`)}console.log(`
861
- ${e.length} similar chain pair(s) found.`)}}),zh=Ke("drift",{query:({db:e,args:t,opts:n,budget:i})=>Rn(e,{scope:le(t,0),minDeviation:N(n,"minDeviation",5),semantic:i.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),P.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE",i=t.policyBasis?`, policy: ${t.policyBasis}`:"",r=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&r.push(` ${t.detail}`),r.join(`
862
+ ${e.length} similar chain pair(s) found.`)}}),eb=ze("drift",{query:({db:e,args:t,opts:n,budget:i})=>Rn(e,{scope:le(t,0),minDeviation:N(n,"minDeviation",5),semantic:i.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),P.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE",i=t.policyBasis?`, policy: ${t.policyBasis}`:"",r=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&r.push(` ${t.detail}`),r.join(`
862
863
  `)},t=>t.file),console.log(`
863
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),Kh=Ke("convergence",{query:({db:e,args:t,budget:n})=>Lc(e,H(t,0),H(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
864
+ ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),tb=ze("convergence",{query:({db:e,args:t,budget:n})=>Pc(e,H(t,0),H(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
864
865
  ${Math.round(e.similarity*100)}% callee overlap
865
866
  `),console.log(` A: ${e.symbolA.shortName} (${e.symbolA.file}, ${e.symbolA.loc} LOC)`),console.log(` B: ${e.symbolB.shortName} (${e.symbolB.file}, ${e.symbolB.loc} LOC)
866
867
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
867
868
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
868
869
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
869
- Strategy: ${e.consolidationStrategy}`)}}}),Jh=Nt("similar-signatures",{query:({db:e,opts:t,budget:n})=>Ec(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",3),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
870
+ Strategy: ${e.consolidationStrategy}`)}}}),nb=Nt("similar-signatures",{query:({db:e,opts:t,budget:n})=>$c(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",3),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
870
871
  Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(i=>` ${ye(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
871
872
  `);return`${t}
872
873
  ${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
873
- ${e.length} group(s) found.`)}),Qh=X("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let r=wo(e,{scope:E(n,"scope"),minLoc:N(n,"minLoc",1),maxDepth:N(n,"maxDepth",5),scanLimit:i.scanLimit}),o=be(),s=R(n,"patch"),a=R(n,"json"),c=R(n,"verify")||s;if(s&&!R(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(r.batches.length===0){if(a){$("cleanup-plan",t,n,r);return}return P.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Yc(r),u=c?Jc(o,r):void 0;if(a){$("cleanup-plan",t,n,{result:r,verification:u});return}if(s){let d=Zc(u,l);if(d.length>0){for(let p of d)console.error(`error: ${p}`);process.exitCode=1;return}let m=zf(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} compiler-verified batch(es), ${r.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${r.totalSymbols} symbol(s), ${r.totalLoc} LOC across ${r.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
874
+ ${e.length} group(s) found.`)}),ib=X("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let r=Lo(e,{scope:E(n,"scope"),minLoc:N(n,"minLoc",1),maxDepth:N(n,"maxDepth",5),scanLimit:i.scanLimit}),o=be(),s=R(n,"patch"),a=R(n,"json"),c=R(n,"verify")||s;if(s&&!R(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(r.batches.length===0){if(a){F("cleanup-plan",t,n,r);return}return P.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=tl(r),u=c?Yc(o,r):void 0;if(a){F("cleanup-plan",t,n,{result:r,verification:u});return}if(s){let d=nl(u,l);if(d.length>0){for(let p of d)console.error(`error: ${p}`);process.exitCode=1;return}let m=Qf(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} compiler-verified batch(es), ${r.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${r.totalSymbols} symbol(s), ${r.totalLoc} LOC across ${r.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
874
875
  `);for(let d of r.batches){let m=d.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${d.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${d.depth}: dead once batch ${d.depth-1} lands (cascade, ${d.loc} LOC) \u2500\u2500`;console.log(m);for(let p of d.entries)console.log(` ${p.file}:${p.startLine+1}-${p.endLine+1} ${p.shortName} (${p.loc} LOC)`);d.filesEmptied.length>0&&console.log(` -> empties: ${d.filesEmptied.join(", ")}`),console.log("")}if(r.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let d of r.blocked)console.log(` ${d.shortName} (${d.file}) blocked by ${d.blockingFiles.join(", ")}`)}if(u){if(console.log(`
875
- Verifying batches against the project checker (throwaway worktree at HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let d of u.checkers)console.log(` Checker: ${d}`);u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`);for(let d of u.batches)if(d.status==="verified")console.log(` Batch ${d.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${d.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let m of d.errors??[])console.log(` ${m}`)}}}),Xh=X("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!R(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let i=R(t,"all"),r=Ee(t,"batch");if(i===(r!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=wo(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",1),maxDepth:N(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){P.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Yc(o,{all:i,batch:r});if(s.length===0){console.error(`error: No cleanup batch ${r} exists.`),process.exitCode=1;return}let a=be(),c=Jc(a,o),l=Zc(c,s,{allowDirty:R(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}Xc(a,s);let u=s.reduce((m,p)=>m+p.entries.length,0),d=s.reduce((m,p)=>m+p.loc,0);console.log(`Applied ${s.length} compiler-verified cleanup batch(es): ${u} symbol(s), ${d} LOC.`)}),Yh=X("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let r=Sc(e,{windowCommits:N(n,"window",100),minSimilarity:Ee(n,"minSimilarity"),limit:O(n,"limit",30),scope:E(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic});if(R(n,"json")){$("recent-duplicates",t,n,r);return}if(!r.available)return P.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return P.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
876
+ Verifying batches against the project checker (throwaway worktree at HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let d of u.checkers)console.log(` Checker: ${d}`);u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`);for(let d of u.batches)if(d.status==="verified")console.log(` Batch ${d.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${d.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let m of d.errors??[])console.log(` ${m}`)}}}),rb=X("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!R(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let i=R(t,"all"),r=Ee(t,"batch");if(i===(r!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Lo(e,{scope:E(t,"scope"),minLoc:N(t,"minLoc",1),maxDepth:N(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){P.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=tl(o,{all:i,batch:r});if(s.length===0){console.error(`error: No cleanup batch ${r} exists.`),process.exitCode=1;return}let a=be(),c=Yc(a,o),l=nl(c,s,{allowDirty:R(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}el(a,s);let u=s.reduce((m,p)=>m+p.entries.length,0),d=s.reduce((m,p)=>m+p.loc,0);console.log(`Applied ${s.length} compiler-verified cleanup batch(es): ${u} symbol(s), ${d} LOC.`)}),ob=X("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let r=vc(e,{windowCommits:N(n,"window",100),minSimilarity:Ee(n,"minSimilarity"),limit:O(n,"limit",30),scope:E(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic});if(R(n,"json")){F("recent-duplicates",t,n,r);return}if(!r.available)return P.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return P.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
876
877
  `);let o=r.rootCauseGroups?.filter(s=>s.count>1)??[];if(o.length>0){console.log(`Root-cause groups (${o.length}):`);for(let s of o)console.log(` ${s.count} pair(s) ${s.kind.toUpperCase()} ${s.domain} ${Math.round(s.maxSimilarity*100)}% max`),s.establishedFile&&s.establishedSymbol&&console.log(` established: ${s.establishedFile} ${s.establishedSymbol}`),console.log(` files: ${s.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${s.recommendation}`);console.log("")}for(let s of r.findings){let a=s.sharedEvidence.slice(0,16).join(", ");s.kind==="echo"?(console.log(` ${Math.round(s.similarity*100)}% ECHO ${s.domain} ${s.echoFile} ${s.echoSymbol} (added ${s.echoAgeCommits} commits ago)`),console.log(` duplicates established ${s.establishedFile} ${s.establishedSymbol}`)):(console.log(` ${Math.round(s.similarity*100)}% TWIN ${s.domain} ${s.echoFile} ${s.echoSymbol}`),console.log(` and ${s.establishedFile} ${s.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${s.basis}`),a.length>0&&console.log(` shared: ${a}`)}console.log(`
877
- ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Zh=z(({db:e,args:t,opts:n})=>{let i=mc(e,{doc:t[0]===void 0?void 0:H(t,0),limit:O(n,"limit",20),minCoupling:N(n,"minCoupling",3)});if(R(n,"json")){$("doc-drift",t,n,i);return}if(!i.available)return P.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return P.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
878
- `);for(let r of i.findings){console.log(` staleness ${r.staleness} ${r.doc}`);for(let o of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${o} \u2014 that file no longer exists`);for(let o of r.subjects.slice(0,4)){let s=o.evidence==="both"?`referenced by doc + coupled ${o.coChanges}x`:o.evidence==="reference"?"referenced by doc":`coupled ${o.coChanges}x historically`;console.log(` ${o.changesSinceDocUpdate} change(s) since doc update ${o.file} (${s}; ${o.actionTier}/${o.docIntent})`);let a=o.docIntentReasons[0];a&&console.log(` intent: ${a}`);let c=o.citationContexts?.[0];c&&console.log(` cited claim: ${Ko(c)}`)}}console.log(`
879
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),eb=Nt("unused-params",{query:({db:e,opts:t,budget:n})=>ur(e,{scope:E(t,"scope"),limit:O(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName}
878
+ ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),sb=z(({db:e,args:t,opts:n})=>{let i=gc(e,{doc:t[0]===void 0?void 0:H(t,0),limit:O(n,"limit",20),minCoupling:N(n,"minCoupling",3)});if(R(n,"json")){F("doc-drift",t,n,i);return}if(!i.available)return P.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return P.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
879
+ `);for(let r of i.findings){console.log(` staleness ${r.staleness} ${r.doc}`);for(let o of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${o} \u2014 that file no longer exists`);for(let o of r.subjects.slice(0,4)){let s=o.evidence==="both"?`referenced by doc + coupled ${o.coChanges}x`:o.evidence==="reference"?"referenced by doc":`coupled ${o.coChanges}x historically`;console.log(` ${o.changesSinceDocUpdate} change(s) since doc update ${o.file} (${s}; ${o.actionTier}/${o.docIntent})`);let a=o.docIntentReasons[0];a&&console.log(` intent: ${a}`);let c=o.citationContexts?.[0];c&&console.log(` cited claim: ${Jo(c)}`)}}console.log(`
880
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),ab=Nt("unused-params",{query:({db:e,opts:t,budget:n})=>ur(e,{scope:E(t,"scope"),limit:O(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${ye(e.file,e.startLine,e.endLine)} ${e.shortName}
880
881
  trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params \u2014 safe to drop)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
881
- ${e.length} function(s) with trailing unused parameters.`)});var tb=Ke("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>fn(e,{minSimilarity:N(n,"minSimilarity",.62),minTokens:N(n,"minTokens",8),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{P.list(e,t=>{let n=[`
882
+ ${e.length} function(s) with trailing unused parameters.`)});var cb=ze("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>fn(e,{minSimilarity:N(n,"minSimilarity",.62),minTokens:N(n,"minTokens",8),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{P.list(e,t=>{let n=[`
882
883
  ${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`];return t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedNativeTags.length&&n.push(` Shared native tags: ${t.sharedNativeTags.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),n.join(`
883
884
  `)}),console.log(`
884
- ${e.length} duplicated React component pair(s) found.`)}}),nb=Ke("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>gn(e,{minSimilarity:N(n,"minSimilarity",.45),minSharedBehaviors:N(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{P.list(e,t=>{let n=[`
885
+ ${e.length} duplicated React component pair(s) found.`)}}),lb=ze("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>gn(e,{minSimilarity:N(n,"minSimilarity",.45),minSharedBehaviors:N(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{P.list(e,t=>{let n=[`
885
886
  ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedHooks.length&&n.push(` Shared hooks: ${t.sharedHooks.join(", ")}`),t.sharedReactHooks.length&&n.push(` Shared React hooks: ${t.sharedReactHooks.join(", ")}`),t.sharedEffects.length&&n.push(` Shared effects: ${t.sharedEffects.join(", ")}`),t.sharedState.length&&n.push(` Shared state: ${t.sharedState.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedHandlers.length&&n.push(` Shared handlers: ${t.sharedHandlers.slice(0,12).join(", ")}`),t.sharedHandlerVerbs.length&&n.push(` Shared action verbs: ${t.sharedHandlerVerbs.slice(0,12).join(", ")}`),n.join(`
886
887
  `)}),console.log(`
887
- ${e.length} React hook candidate pair(s) found.`)}}),ib=Ke("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>er(e,{minComponentLines:N(n,"minComponentLines",300),minFileLines:N(n,"minFileLines",800),minJsxTokens:N(n,"minJsxTokens",80),minBehaviorTokens:N(n,"minBehaviorTokens",40),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{P.list(e,t=>[`
888
+ ${e.length} React hook candidate pair(s) found.`)}}),ub=ze("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>er(e,{minComponentLines:N(n,"minComponentLines",300),minFileLines:N(n,"minFileLines",800),minJsxTokens:N(n,"minJsxTokens",80),minBehaviorTokens:N(n,"minBehaviorTokens",40),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{P.list(e,t=>[`
888
889
  ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`,` Reasons: ${t.reasons.join("; ")}`].join(`
889
890
  `)),console.log(`
890
- ${e.length} large React component(s) found.`)}}),rb=Ke("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>hn(e,{minSimilarity:N(n,"minSimilarity",.62),minTokens:N(n,"minTokens",8),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{P.list(e,t=>{let n=[`
891
+ ${e.length} large React component(s) found.`)}}),db=ze("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>hn(e,{minSimilarity:N(n,"minSimilarity",.62),minTokens:N(n,"minTokens",8),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{P.list(e,t=>{let n=[`
891
892
  ${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`];return t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedDirectives.length&&n.push(` Shared directives: ${t.sharedDirectives.join(", ")}`),t.sharedSlots.length&&n.push(` Shared slots: ${t.sharedSlots.join(", ")}`),t.sharedIdentifiers.length&&n.push(` Shared identifiers: ${t.sharedIdentifiers.slice(0,20).join(", ")}`),n.join(`
892
893
  `)}),console.log(`
893
- ${e.length} duplicated Vue component pair(s) found.`)}}),ob=Ke("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>bn(e,{minSimilarity:N(n,"minSimilarity",.45),minSharedBehaviors:N(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{P.list(e,t=>{let n=[`
894
+ ${e.length} duplicated Vue component pair(s) found.`)}}),mb=ze("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>bn(e,{minSimilarity:N(n,"minSimilarity",.45),minSharedBehaviors:N(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{P.list(e,t=>{let n=[`
894
895
  ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComposables.length&&n.push(` Shared composables: ${t.sharedComposables.join(", ")}`),t.sharedStores.length&&n.push(` Shared stores: ${t.sharedStores.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedLifecycle.length&&n.push(` Shared lifecycle: ${t.sharedLifecycle.join(", ")}`),t.sharedFunctions.length&&n.push(` Shared functions: ${t.sharedFunctions.slice(0,12).join(", ")}`),t.sharedFunctionVerbs.length&&n.push(` Shared action verbs: ${t.sharedFunctionVerbs.slice(0,12).join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),t.sharedTemplateEvents.length&&n.push(` Shared template events: ${t.sharedTemplateEvents.slice(0,20).join(", ")}`),n.join(`
895
896
  `)}),console.log(`
896
- ${e.length} Vue composable candidate pair(s) found.`)}}),sb=Ke("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>tr(e,{minTotalLines:R(n,"reviewThresholds")&&Cl(n,"minTotalLines")==="default"?300:N(n,"minTotalLines",800),minTemplateLines:N(n,"minTemplateLines",300),minScriptLines:N(n,"minScriptLines",300),minStyleLines:N(n,"minStyleLines",500),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{P.list(e,t=>{let n=[`
897
+ ${e.length} Vue composable candidate pair(s) found.`)}}),pb=ze("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>tr(e,{minTotalLines:R(n,"reviewThresholds")&&kl(n,"minTotalLines")==="default"?300:N(n,"minTotalLines",800),minTemplateLines:N(n,"minTemplateLines",300),minScriptLines:N(n,"minScriptLines",300),minStyleLines:N(n,"minStyleLines",500),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:i.scanLimit,filePattern:le(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{P.list(e,t=>{let n=[`
897
898
  ${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
898
899
  `)}),console.log(`
899
- ${e.length} large Vue view pressure file(s) found.`)}});function it(e){return{docs:w("Cleanup"),...e}}function Re({heuristicLabel:e,...t}){return it({...t,heuristic:{label:e}})}var vs=[it({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:_([f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Maximum findings",v,30),f("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:w("Cleanup",["scip-query unused-params -s src/services"]),handler:eb}),it({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",v,1),f("--max-depth <n>","Maximum cascade depth",v,5),f("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),f("--patch","With --verify, print the compiler-verified deletion patch to stdout"),f("--json","Output as JSON for programmatic consumption"),f("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Qh}),it({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",v,1),f("--max-depth <n>","Maximum cascade depth",v,5),f("--verified","Required: verify the selected cleanup batch before applying it"),f("--batch <n>","Apply one batch depth",v),f("--all","Apply every compiler-verified batch in the plan"),f("--force-dirty","Allow applying when plan files already have working-tree edits"),f("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:Xh}),it({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:_([f("--window <n>",'How many commits back counts as "recent"',v,100),f("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",nt),f("-n, --limit <n>","Maximum findings",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:w("Cleanup",["scip-query recent-duplicates --window 50"]),handler:Yh}),it({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:_([f("-n, --limit <n>","Maximum docs to report",v,20),f("--min-coupling <n>","Minimum historical co-changes to track a subject",v,3),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:w("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Zh}),it({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:_([f("--min-loc <n>","Only show symbols >= N lines",v,1),f("--include-tests","Include test files"),f("--skip-barrels","Ignore refs from barrel re-export files"),f("--include-members","Include class members"),f("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),f("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query dead --min-loc 10"]),handler:$h}),it({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Ah}),it({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum lines of code",v,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Mh}),Re({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:_([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",nt,.4),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-callees <n>","Minimum callees to consider",v,4),f("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Uh}),Re({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:_([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",nt,.5),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-deps <n>","Minimum dependencies to consider",v),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Wh}),Re({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:_([f("--min-similarity <n>","Minimum JSX structure similarity (0-1)",nt,.62),f("--min-tokens <n>","Minimum structural tokens to consider",v,8),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:tb}),Re({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:_([f("--min-similarity <n>","Minimum behavior similarity (0-1)",nt,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:nb}),Re({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:_([f("--min-component-lines <n>","Minimum component lines",v,300),f("--min-file-lines <n>","Minimum file lines",v,800),f("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),f("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:ib}),Re({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:_([f("--min-similarity <n>","Minimum template similarity (0-1)",nt,.62),f("--min-tokens <n>","Minimum structural tokens to consider",v,8),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:rb}),Re({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:_([f("--min-similarity <n>","Minimum behavior similarity (0-1)",nt,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:ob}),Re({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:_([f("--min-total-lines <n>","Minimum total component lines",v,800),f("--min-template-lines <n>","Minimum template lines",v,300),f("--min-script-lines <n>","Minimum script lines",v,300),f("--min-style-lines <n>","Minimum style lines",v,500),f("--review-thresholds","Use lower review thresholds without changing health scoring"),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:sb}),Re({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:_([f("--min-similarity <n>","Minimum chain similarity (0-1)",nt,.5),f("-n, --limit <n>","Number of results",v,15),f("-s, --scope <path>","Limit to files matching path"),f("--min-length <n>","Minimum chain length",v,3),f("--max-length <n>","Maximum chain length",v,8),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Gh}),Re({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum function LOC",v,10),f("--min-callees <n>","Minimum callees to analyze",v,6),f("-n, --limit <n>","Number of results",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Oh}),Re({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:_([f("-s, --scope <path>","Limit scan mode to files matching path"),f("--min-consumers <n>","Minimum consumers in scan mode",v,1),f("-n, --limit <n>","Number of results",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:jh}),Re({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:_([f("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",es,5),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:zh}),Re({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",v,15),f("-n, --limit <n>","Number of results",v,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Bh}),Re({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",v,15),f("-n, --limit <n>","Number of results",v,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Hh}),Re({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",v,3),f("-n, --limit <n>","Number of results",v,30),f("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Vh}),Re({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",v,10),f("-n, --limit <n>","Number of results",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:qh}),it({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Kh}),_h({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",v,30),f("--full","Run unbounded analysis on large indexes")],docs:w("Cleanup"),query:({db:e,opts:t})=>Ic(e,{scope:E(t,"scope"),limit:O(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
900
+ ${e.length} large Vue view pressure file(s) found.`)}});function nt(e){return{docs:w("Cleanup"),...e}}function Re({heuristicLabel:e,...t}){return nt({...t,heuristic:{label:e}})}var ws=[nt({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:_([f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Maximum findings",v,30),f("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:w("Cleanup",["scip-query unused-params -s src/services"]),handler:ab}),nt({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",v,1),f("--max-depth <n>","Maximum cascade depth",v,5),f("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),f("--patch","With --verify, print the compiler-verified deletion patch to stdout"),f("--json","Output as JSON for programmatic consumption"),f("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:ib}),nt({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",v,1),f("--max-depth <n>","Maximum cascade depth",v,5),f("--verified","Required: verify the selected cleanup batch before applying it"),f("--batch <n>","Apply one batch depth",v),f("--all","Apply every compiler-verified batch in the plan"),f("--force-dirty","Allow applying when plan files already have working-tree edits"),f("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:rb}),nt({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:_([f("--window <n>",'How many commits back counts as "recent"',v,100),f("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",tt),f("-n, --limit <n>","Maximum findings",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:w("Cleanup",["scip-query recent-duplicates --window 50"]),handler:ob}),nt({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:_([f("-n, --limit <n>","Maximum docs to report",v,20),f("--min-coupling <n>","Minimum historical co-changes to track a subject",v,3),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:w("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:sb}),nt({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:_([f("--min-loc <n>","Only show symbols >= N lines",v,1),f("--include-tests","Include test files"),f("--skip-barrels","Ignore refs from barrel re-export files"),f("--include-members","Include class members"),f("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),f("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query dead --min-loc 10"]),handler:Vh}),nt({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:qh}),nt({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum lines of code",v,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Uh}),Re({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:_([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",tt,.4),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-callees <n>","Minimum callees to consider",v,4),f("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Xh}),Re({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:_([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",tt,.5),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-deps <n>","Minimum dependencies to consider",v),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Yh}),Re({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:_([f("--min-similarity <n>","Minimum JSX structure similarity (0-1)",tt,.62),f("--min-tokens <n>","Minimum structural tokens to consider",v,8),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:cb}),Re({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:_([f("--min-similarity <n>","Minimum behavior similarity (0-1)",tt,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:lb}),Re({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:_([f("--min-component-lines <n>","Minimum component lines",v,300),f("--min-file-lines <n>","Minimum file lines",v,800),f("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),f("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:ub}),Re({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:_([f("--min-similarity <n>","Minimum template similarity (0-1)",tt,.62),f("--min-tokens <n>","Minimum structural tokens to consider",v,8),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:db}),Re({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:_([f("--min-similarity <n>","Minimum behavior similarity (0-1)",tt,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:mb}),Re({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:_([f("--min-total-lines <n>","Minimum total component lines",v,800),f("--min-template-lines <n>","Minimum template lines",v,300),f("--min-script-lines <n>","Minimum script lines",v,300),f("--min-style-lines <n>","Minimum style lines",v,500),f("--review-thresholds","Use lower review thresholds without changing health scoring"),f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:pb}),Re({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:_([f("--min-similarity <n>","Minimum chain similarity (0-1)",tt,.5),f("-n, --limit <n>","Number of results",v,15),f("-s, --scope <path>","Limit to files matching path"),f("--min-length <n>","Minimum chain length",v,3),f("--max-length <n>","Maximum chain length",v,8),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Zh}),Re({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum function LOC",v,10),f("--min-callees <n>","Minimum callees to analyze",v,6),f("-n, --limit <n>","Number of results",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Wh}),Re({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:_([f("-s, --scope <path>","Limit scan mode to files matching path"),f("--min-consumers <n>","Minimum consumers in scan mode",v,1),f("-n, --limit <n>","Number of results",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Gh}),Re({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:_([f("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",ts,5),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:eb}),Re({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",v,15),f("-n, --limit <n>","Number of results",v,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:zh}),Re({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",v,15),f("-n, --limit <n>","Number of results",v,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Kh}),Re({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",v,3),f("-n, --limit <n>","Number of results",v,30),f("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Jh}),Re({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",v,10),f("-n, --limit <n>","Number of results",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Qh}),nt({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:tb}),Bh({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",v,30),f("--full","Run unbounded analysis on large indexes")],docs:w("Cleanup"),query:({db:e,opts:t})=>Ec(e,{scope:E(t,"scope"),limit:O(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
900
901
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
901
902
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
902
903
  Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
903
- ${e.length} redundant re-export(s).`)}),it({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC per function",v,3),f("-n, --limit <n>","Number of groups",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Jh})];var xM=z(({db:e,args:t,opts:n})=>{let i=Oe(e);if(R(n,"json")){$("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definitions: ${i.definitions}`),console.log(`References: ${i.references}`),console.log(`Index size: ${hi(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),ab=[{id:"stats",command:"stats",description:"Show index statistics",options:[Vc()],renderShape:"custom",docs:w("Core"),handler:xM}];var CM=ys("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ta(e,{limit:O(t,"limit",20),scope:E(t,"scope"),minFanIn:N(t,"minFanIn",2),minFanOut:N(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),vM=z(({db:e,args:t,opts:n})=>{let i=le(t,0),r=O(n,"limit",30);if(i){let s=La(e,i);if(R(n,"json")){$("fan-in",t,n,{mode:"symbol",symbol:i,rows:s});return}if(s.length===0)return P.empty(`No fan-in for ${i}.`);P.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=Ia(e,{limit:r,scope:E(n,"scope")});if(R(n,"json")){$("fan-in",t,n,{mode:"top",rows:o});return}P.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),RM=z(({db:e,args:t,opts:n})=>{let i=le(t,0),r=O(n,"limit",30);if(i){let s=Da(e,i);if(R(n,"json")){$("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return P.empty(`No fan-out for ${i}.`);P.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Pa(e,{limit:r,scope:E(n,"scope")});if(R(n,"json")){$("fan-out",t,n,{mode:"top",rows:o});return}P.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),kM=z(({db:e,args:t,opts:n})=>{let i=le(t,0),r=le(t,1),o=O(n,"limit",20);if(i&&r){let a=Na(e,i,r);if(R(n,"json")){$("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=Ea(e,{limit:o,scope:E(n,"scope")});if(R(n,"json")){$("coupling",t,n,{mode:"top",rows:s});return}P.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),wM=_n({commandName:"cycles",query:({db:e,opts:t})=>mn(e,{scope:E(t,"scope"),maxDepth:N(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(i=>i.kind==="real"),n=e.filter(i=>i.kind==="module-hierarchy");for(let i=0;i<t.length;i++){console.log(`
904
+ ${e.length} redundant re-export(s).`)}),nt({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC per function",v,3),f("-n, --limit <n>","Number of groups",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:nb})];var NM=z(({db:e,args:t,opts:n})=>{let i=Oe(e);if(R(n,"json")){F("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definitions: ${i.definitions}`),console.log(`References: ${i.references}`),console.log(`Index size: ${hi(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),fb=[{id:"stats",command:"stats",description:"Show index statistics",options:[Wc()],renderShape:"custom",docs:w("Core"),handler:NM}];var EM=Cs("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Fa(e,{limit:O(t,"limit",20),scope:E(t,"scope"),minFanIn:N(t,"minFanIn",2),minFanOut:N(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),TM=z(({db:e,args:t,opts:n})=>{let i=le(t,0),r=O(n,"limit",30);if(i){let s=Pa(e,i);if(R(n,"json")){F("fan-in",t,n,{mode:"symbol",symbol:i,rows:s});return}if(s.length===0)return P.empty(`No fan-in for ${i}.`);P.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=Ea(e,{limit:r,scope:E(n,"scope")});if(R(n,"json")){F("fan-in",t,n,{mode:"top",rows:o});return}P.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),_M=z(({db:e,args:t,opts:n})=>{let i=le(t,0),r=O(n,"limit",30);if(i){let s=Na(e,i);if(R(n,"json")){F("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return P.empty(`No fan-out for ${i}.`);P.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Ta(e,{limit:r,scope:E(n,"scope")});if(R(n,"json")){F("fan-out",t,n,{mode:"top",rows:o});return}P.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),$M=z(({db:e,args:t,opts:n})=>{let i=le(t,0),r=le(t,1),o=O(n,"limit",20);if(i&&r){let a=_a(e,i,r);if(R(n,"json")){F("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=$a(e,{limit:o,scope:E(n,"scope")});if(R(n,"json")){F("coupling",t,n,{mode:"top",rows:s});return}P.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),FM=_n({commandName:"cycles",query:({db:e,opts:t})=>mn(e,{scope:E(t,"scope"),maxDepth:N(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(i=>i.kind==="real"),n=e.filter(i=>i.kind==="module-hierarchy");for(let i=0;i<t.length;i++){console.log(`
904
905
  Cycle ${i+1} (${t[i].path.length-1} files):`);for(let r=0;r<t[i].path.length;r++){let o=r<t[i].path.length-1?" \u2192":" (cycle)";console.log(` ${t[i].path[r]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
905
- ${t.length} real cycle(s) found.`),n.length>0&&console.log(`(${n.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}}),LM=_n({commandName:"deep-chains",query:({db:e,opts:t})=>Ma(e,{limit:O(t,"limit",10),scope:E(t,"scope"),minDepth:N(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
906
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`);console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),cb=[xs({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[f("-n, --limit <n>","Number of results",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")],docs:w("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>xa(e,{limit:O(t,"limit",30),scope:E(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"How many files reference a symbol (or top fan-in across codebase)",options:_([f("-n, --limit <n>","Number of results for top mode",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:vM},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:_([f("-n, --limit <n>","Number of results for top mode",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:RM},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:_([f("-n, --limit <n>","Number of results for top mode",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:kM},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--max-depth <n>","Maximum cycle depth",v,10)]),renderShape:"custom",docs:w("Graph"),handler:wM},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:_([f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-fan-in <n>","Minimum fan-in",v,2),f("--min-fan-out <n>","Minimum fan-out",v,2),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:w("Graph"),handler:CM},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:_([f("-n, --limit <n>","Number of chains to show",v,10),f("-s, --scope <path>","Limit to files matching path"),f("--min-depth <n>","Minimum chain depth",v,3),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:LM},Cs({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:w("Graph"),query:({db:e,args:t,budget:n})=>Xi(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
907
- `)},sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.callees.map(t=>` ${t.file} ${t.shortName}`)}]:[]})];var DM=X("complexity",({db:e,args:t,opts:n,budget:i})=>{let r=mr(e,H(t,0),{semantic:i.semantic});if(R(n,"json")){$("complexity",t,n,r);return}if(!r)return P.empty("Symbol not found.");console.log(`${ye(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
908
- `),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),IM=z(({db:e,args:t,opts:n})=>{let i=Nc(e,{samples:N(n,"samples",50),scope:E(n,"scope")});if(R(n,"json")){$("self-audit",t,n,i);return}if(!i.available)return P.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${i.sampleSize} symbols; oracle answered ${Math.round(i.oracleCoverage*100)}%.
906
+ ${t.length} real cycle(s) found.`),n.length>0&&console.log(`(${n.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}}),AM=_n({commandName:"deep-chains",query:({db:e,opts:t})=>Ba(e,{limit:O(t,"limit",10),scope:E(t,"scope"),minDepth:N(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
907
+ Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`);console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),gb=[Rs({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[f("-n, --limit <n>","Number of results",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")],docs:w("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Ra(e,{limit:O(t,"limit",30),scope:E(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"How many files reference a symbol (or top fan-in across codebase)",options:_([f("-n, --limit <n>","Number of results for top mode",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:TM},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:_([f("-n, --limit <n>","Number of results for top mode",v,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:_M},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:_([f("-n, --limit <n>","Number of results for top mode",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:$M},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:_([f("-s, --scope <path>","Limit to files matching path"),f("--max-depth <n>","Maximum cycle depth",v,10)]),renderShape:"custom",docs:w("Graph"),handler:FM},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:_([f("-n, --limit <n>","Number of results",v,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-fan-in <n>","Minimum fan-in",v,2),f("--min-fan-out <n>","Minimum fan-out",v,2),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:w("Graph"),handler:EM},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:_([f("-n, --limit <n>","Number of chains to show",v,10),f("-s, --scope <path>","Limit to files matching path"),f("--min-depth <n>","Minimum chain depth",v,3),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:w("Graph"),handler:AM},ks({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:w("Graph"),query:({db:e,args:t,budget:n})=>Xi(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
908
+ `)},sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.callees.map(t=>` ${t.file} ${t.shortName}`)}]:[]})];var MM=X("complexity",({db:e,args:t,opts:n,budget:i})=>{let r=mr(e,H(t,0),{semantic:i.semantic});if(R(n,"json")){F("complexity",t,n,r);return}if(!r)return P.empty("Symbol not found.");console.log(`${ye(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
909
+ `),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),OM=z(({db:e,args:t,opts:n})=>{let i=_c(e,{samples:N(n,"samples",50),scope:E(n,"scope")});if(R(n,"json")){F("self-audit",t,n,i);return}if(!i.available)return P.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${i.sampleSize} symbols; oracle answered ${Math.round(i.oracleCoverage*100)}%.
909
910
  `),console.log("Agreement with compiler semantics (file-level):");for(let r of i.scores){let o=r.precision===null?`unverified ${r.unverified} (oracle partial \u2014 no precision claim)`:`precision ${r.precision}`;console.log(` ${r.question.padEnd(11)} ${o} recall ${r.recall} (${r.comparedSymbols} symbols)`)}if(i.topDisagreements.length>0){console.log(`
910
- Top disagreements (debugging targets):`);for(let r of i.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),lb=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:_([f("--samples <n>","Number of symbols to sample",v,50),f("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:w("Health",["scip-query self-audit --samples 100"]),handler:IM},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Health"),handler:DM}];var PM=z(({db:e,args:t,opts:n})=>{let i=nr(e,H(t,0),{maxDepth:N(n,"maxDepth",5),scope:E(n,"scope")});if(R(n,"json")){$("affected",t,n,i);return}if(i.length===0)return P.empty("No affected symbols found.");let r=-1;for(let o of i)o.depth!==r&&(console.log(`
911
+ Top disagreements (debugging targets):`);for(let r of i.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),hb=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:_([f("--samples <n>","Number of symbols to sample",v,50),f("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:w("Health",["scip-query self-audit --samples 100"]),handler:OM},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Health"),handler:MM}];var jM=z(({db:e,args:t,opts:n})=>{let i=nr(e,H(t,0),{maxDepth:N(n,"maxDepth",5),scope:E(n,"scope")});if(R(n,"json")){F("affected",t,n,i);return}if(i.length===0)return P.empty("No affected symbols found.");let r=-1;for(let o of i)o.depth!==r&&(console.log(`
911
912
  \u2500\u2500 Depth ${o.depth} \u2500\u2500`),r=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
912
- ${i.length} affected symbol(s) across ${new Set(i.map(o=>o.file)).size} files.`)}),NM=z(({db:e,args:t,opts:n})=>{let i=t[0]===void 0?void 0:H(t,0),r=xn(e,i,{minTogether:N(n,"minTogether",4),limit:O(n,"limit",30),includeLinked:n.all===!0});if(R(n,"json")){$("co-change",t,n,r);return}if(!r.available)return P.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return P.empty(i?`No co-change partners found for ${i} in ${r.commitsAnalyzed} commits.`:`No hidden coupling found in ${r.commitsAnalyzed} commits.`);console.log(i?`Co-change partners (${r.commitsAnalyzed} commits analyzed):
913
+ ${i.length} affected symbol(s) across ${new Set(i.map(o=>o.file)).size} files.`)}),BM=z(({db:e,args:t,opts:n})=>{let i=t[0]===void 0?void 0:H(t,0),r=xn(e,i,{minTogether:N(n,"minTogether",4),limit:O(n,"limit",30),includeLinked:n.all===!0});if(R(n,"json")){F("co-change",t,n,r);return}if(!r.available)return P.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return P.empty(i?`No co-change partners found for ${i} in ${r.commitsAnalyzed} commits.`:`No hidden coupling found in ${r.commitsAnalyzed} commits.`);console.log(i?`Co-change partners (${r.commitsAnalyzed} commits analyzed):
913
914
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${r.commitsAnalyzed} commits analyzed):
914
- `);for(let o of r.findings){let s=o.structurallyLinked?" [dep edge]":"",a=` [${o.partnerClass}]`,c=` [${o.commitScope}/${o.recency}]`;console.log(` ${o.together}x (${Math.round(o.confidence*100)}%) ${o.fileA} <-> ${o.fileB}${a}${c}${s}`),console.log(` history: ${o.focusedTogether} focused, ${o.broadTogether} broad-sweep (${Math.round(o.broadCommitRatio*100)}% broad), ${o.recentTogether} recent; last ${EM(o.lastTogetherAt)}`),console.log(` subjects: ${TM(o.subjectContext)}`),o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`)}console.log(`
915
- ${r.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function EM(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function TM(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var _M=X("change-surface",({db:e,args:t,opts:n,budget:i})=>{let r=ir(e,H(t,0),{semantic:i.semantic});if(R(n,"json")){$("change-surface",t,n,r);return}if(!r)return P.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
916
- `),P.list(r.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${ve(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),FM=z(({db:e,args:t,opts:n})=>{let i=lr(e,{base:E(n,"base"),minContainment:N(n,"minContainment",.7),maxHelpers:Ee(n,"maxHelpers"),limit:O(n,"limit",20)});if(R(n,"json")){$("incomplete-migration",t,n,i),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return P.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return P.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let r of i.skipped)console.log(` skipped ${r.helperShortName} (${r.helperFile}): ${r.reason}`);if(i.findings.length===0){console.log(`
915
+ `);for(let o of r.findings){let s=o.structurallyLinked?" [dep edge]":"",a=` [${o.partnerClass}]`,c=` [${o.commitScope}/${o.recency}]`;console.log(` ${o.together}x (${Math.round(o.confidence*100)}%) ${o.fileA} <-> ${o.fileB}${a}${c}${s}`),console.log(` history: ${o.focusedTogether} focused, ${o.broadTogether} broad-sweep (${Math.round(o.broadCommitRatio*100)}% broad), ${o.recentTogether} recent; last ${HM(o.lastTogetherAt)}`),console.log(` subjects: ${VM(o.subjectContext)}`),o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`)}console.log(`
916
+ ${r.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function HM(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function VM(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var qM=X("change-surface",({db:e,args:t,opts:n,budget:i})=>{let r=ir(e,H(t,0),{semantic:i.semantic});if(R(n,"json")){F("change-surface",t,n,r);return}if(!r)return P.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
917
+ `),P.list(r.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${ve(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),UM=z(({db:e,args:t,opts:n})=>{let i=lr(e,{base:E(n,"base"),minContainment:N(n,"minContainment",.7),maxHelpers:Ee(n,"maxHelpers"),limit:O(n,"limit",20)});if(R(n,"json")){F("incomplete-migration",t,n,i),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return P.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return P.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let r of i.skipped)console.log(` skipped ${r.helperShortName} (${r.helperFile}): ${r.reason}`);if(i.findings.length===0){console.log(`
917
918
  No incomplete migrations detected.`);return}for(let r of i.findings){console.log(`
918
919
  ${r.helperShortName} (${r.helperFile})`),console.log(` helper shape: ${r.helperShape} (${r.specificHelperCalleeCount}/${r.helperCalleeCount} specific callees)`),console.log(` wired into: ${r.migratedFiles.join(", ")}`);for(let o of r.leftovers)console.log(` un-migrated: ${Math.round(o.containment*100)}% helper / ${Math.round(o.siteCoverage*100)}% site [${o.migrationScope}] ${o.shortName} (${o.file})`),console.log(` scope: ${o.migrationScopeReasons.join("; ")}`),o.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${o.uniqueSiteCalleeCount}`),console.log(` shared: ${o.sharedCallees.join(", ")}`)}console.log(`
919
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function $M(e){let t=Array.isArray(e)?e:[],n=t.filter(i=>!Bo.includes(i));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Bo.join(", ")}`),process.exit(1)),t}var AM=z(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&as(xr()))return;!n&&Bc(e)&&Ol(e)===0&&console.error("Large index with a cold evidence cache: this first run computes semantic callee evidence for every production callable and can take minutes. Re-runs are incremental (evidence.db).");let i=dr(e,{base:E(t,"base"),minTogether:N(t,"minTogether",6),maxEchoChecks:Ee(t,"maxEchoChecks"),maxHelpers:Ee(t,"maxHelpers"),skip:$M(t.skip)});if(!n&&R(t,"json")){$("diff-gate",[],t,{exitCode:i.findings.length>0?1:0,...i}),i.findings.length>0&&(process.exitCode=1);return}if(n){if(i.findings.length===0)return;console.error(Cr(i)),process.exitCode=2;return}if(i.changedFiles.length===0)return P.empty(i.note??`No changes vs ${i.base}.`);console.log(`Diff gate vs ${i.base}: ${i.changedFiles.length} file(s), ${i.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${i.checksRun.join(", ")}
920
- `);for(let o of i.skipped)console.log(` skipped ${o.check}: ${o.reason}`);if(i.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}let r=i.rootCauseGroups?.filter(o=>o.count>1)??[];if(r.length>0){console.log(`Root-cause groups (${r.length}):`);for(let o of r){console.log(` [${o.check}] ${o.count} finding(s), ${o.severity}${o.actionTier?`, tier: ${o.actionTier}`:""}`),(o.sourceAnalyzer||o.rootCauseKey)&&console.log(` source: ${o.sourceAnalyzer??o.check}${o.rootCauseKey?` root cause: ${o.rootCauseKey}`:""}`);let s=[...new Set([...o.files,...o.relatedFiles])].slice(0,6);s.length>0&&console.log(` files: ${s.join(", ")}`),console.log(` -> ${o.remediation}`)}console.log("")}for(let o of i.findings){if(console.log(` [${o.check}] ${o.message}`),o.partnerClass){console.log(` partner class: ${o.partnerClass}`);for(let s of o.partnerClassReasons??[])console.log(` reason: ${s}`)}o.citationKind&&console.log(` citation kind: ${o.citationKind}${o.actionTier?` (tier: ${o.actionTier})`:""}`);for(let s of o.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${Ko(s)}`);o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`),console.log(` -> ${o.remediation}`)}console.log(`
921
- FAIL: ${i.findings.length} finding(s), ${i.rootCauseGroups?.length??i.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),ub=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:_([f("--max-depth <n>","Maximum traversal depth",v,5),f("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:w("Impact"),handler:PM},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:w("Impact"),handler:_M},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-together <n>","Minimum historical co-changes for the partner check",v,6),f("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",v),f("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",v),f("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",Zo,[]),f("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),f("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:w("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:AM},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",options:_([f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",nt,.7),f("--max-helpers <n>","Maximum new helpers to score (default: all)",v),f("-n, --limit <n>","Maximum findings to report",v,20),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:w("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:FM},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:_([f("--min-together <n>","Minimum commits where both files changed",v,4),f("-n, --limit <n>","Maximum pairs to report",v,30),f("--all","Include pairs that already have a dependency edge"),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:w("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:NM}];function MM(e){let t=[];for(let r of e.definitions){let o=r.signature?` \u2014 ${r.signature}`:"";t.push(` ${ye(r.relativePath,r.startLine,r.endLine)}${o}`),r.source&&t.push(r.source.split(`
920
+ ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function WM(e){let t=Array.isArray(e)?e:[],n=t.filter(i=>!Ho.includes(i));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Ho.join(", ")}`),process.exit(1)),t}var GM=z(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&cs(xr()))return;!n&&qc(e)&&Hl(e)===0&&console.error("Large index with a cold evidence cache: this first run computes semantic callee evidence for every production callable and can take minutes. Re-runs are incremental (evidence.db).");let i=dr(e,{base:E(t,"base"),minTogether:N(t,"minTogether",6),maxEchoChecks:Ee(t,"maxEchoChecks"),maxHelpers:Ee(t,"maxHelpers"),skip:WM(t.skip)});if(!n&&R(t,"json")){F("diff-gate",[],t,{exitCode:i.findings.length>0?1:0,...i}),i.findings.length>0&&(process.exitCode=1);return}if(n){if(i.findings.length===0)return;console.error(Cr(i)),process.exitCode=2;return}if(i.changedFiles.length===0)return P.empty(i.note??`No changes vs ${i.base}.`);console.log(`Diff gate vs ${i.base}: ${i.changedFiles.length} file(s), ${i.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${i.checksRun.join(", ")}
921
+ `);for(let o of i.skipped)console.log(` skipped ${o.check}: ${o.reason}`);if(i.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}let r=i.rootCauseGroups?.filter(o=>o.count>1)??[];if(r.length>0){console.log(`Root-cause groups (${r.length}):`);for(let o of r){console.log(` [${o.check}] ${o.count} finding(s), ${o.severity}${o.actionTier?`, tier: ${o.actionTier}`:""}`),(o.sourceAnalyzer||o.rootCauseKey)&&console.log(` source: ${o.sourceAnalyzer??o.check}${o.rootCauseKey?` root cause: ${o.rootCauseKey}`:""}`);let s=[...new Set([...o.files,...o.relatedFiles])].slice(0,6);s.length>0&&console.log(` files: ${s.join(", ")}`),console.log(` -> ${o.remediation}`)}console.log("")}for(let o of i.findings){if(console.log(` [${o.check}] ${o.message}`),o.partnerClass){console.log(` partner class: ${o.partnerClass}`);for(let s of o.partnerClassReasons??[])console.log(` reason: ${s}`)}o.citationKind&&console.log(` citation kind: ${o.citationKind}${o.actionTier?` (tier: ${o.actionTier})`:""}`);for(let s of o.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${Jo(s)}`);o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`),console.log(` -> ${o.remediation}`)}console.log(`
922
+ FAIL: ${i.findings.length} finding(s), ${i.rootCauseGroups?.length??i.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),bb=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:_([f("--max-depth <n>","Maximum traversal depth",v,5),f("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:w("Impact"),handler:jM},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:w("Impact"),handler:qM},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-together <n>","Minimum historical co-changes for the partner check",v,6),f("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",v),f("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",v),f("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",es,[]),f("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),f("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:w("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:GM},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",options:_([f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",tt,.7),f("--max-helpers <n>","Maximum new helpers to score (default: all)",v),f("-n, --limit <n>","Maximum findings to report",v,20),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:w("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:UM},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:_([f("--min-together <n>","Minimum commits where both files changed",v,4),f("-n, --limit <n>","Maximum pairs to report",v,30),f("--all","Include pairs that already have a dependency edge"),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:w("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:BM}];function zM(e){let t=[];for(let r of e.definitions){let o=r.signature?` \u2014 ${r.signature}`:"";t.push(` ${ye(r.relativePath,r.startLine,r.endLine)}${o}`),r.source&&t.push(r.source.split(`
922
923
  `).map((s,a)=>` ${Me(r.startLine+a)} ${s}`).join(`
923
- `))}let n=[],i="";for(let r of e.referencedBy)r.relativePath!==i&&(i&&n.push(""),n.push(` ${r.relativePath}`),i=r.relativePath),n.push(` line ${Me(r.line)} in ${r.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var OM=z(({db:e,args:t,opts:n})=>{let i=H(t,0),r=R(n,"signatures"),o=ka(e,i);if(R(n,"json")){$("outline",t,n,o);return}if(o.length===0)return P.empty(`No symbols found for "${i}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=r&&l.signature?` - ${jM(l.signature)}`:"";console.log(`${u}${ve(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function jM(e){return e.length>120?`${e.slice(0,117)}...`:e}var BM=Nt("imports",{query:({db:e,args:t,budget:n})=>Ca(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),HM=Ss("refs",{query:({db:e,args:t,budget:n})=>fa(e,H(t,0),{semantic:n.semantic}),format:e=>` line ${Me(e.line)}`}),VM=z(({db:e,args:t,opts:n})=>{let i=Dc(e,H(t,0),{context:N(n,"context",0)});if(R(n,"json")){$("code",t,n,i);return}if(!i)return P.empty("Symbol not found or file unreadable.");console.log(`${ye(i.relativePath,i.startLine,i.endLine)} ${i.shortName} [${i.language??"unknown"}]
924
+ `))}let n=[],i="";for(let r of e.referencedBy)r.relativePath!==i&&(i&&n.push(""),n.push(` ${r.relativePath}`),i=r.relativePath),n.push(` line ${Me(r.line)} in ${r.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var KM=z(({db:e,args:t,opts:n})=>{let i=H(t,0),r=R(n,"signatures"),o=Da(e,i);if(R(n,"json")){F("outline",t,n,o);return}if(o.length===0)return P.empty(`No symbols found for "${i}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=r&&l.signature?` - ${JM(l.signature)}`:"";console.log(`${u}${ve(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function JM(e){return e.length>120?`${e.slice(0,117)}...`:e}var QM=Nt("imports",{query:({db:e,args:t,budget:n})=>ka(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),XM=vs("refs",{query:({db:e,args:t,budget:n})=>ba(e,H(t,0),{semantic:n.semantic}),format:e=>` line ${Me(e.line)}`}),YM=z(({db:e,args:t,opts:n})=>{let i=Nc(e,H(t,0),{context:N(n,"context",0)});if(R(n,"json")){F("code",t,n,i);return}if(!i)return P.empty("Symbol not found or file unreadable.");console.log(`${ye(i.relativePath,i.startLine,i.endLine)} ${i.shortName} [${i.language??"unknown"}]
924
925
  `);let r=i.source.split(`
925
- `);for(let o=0;o<r.length;o++)console.log(` ${String(Me(i.startLine+o)).padStart(4)} ${r[o]}`)}),qM=X("dataflow",({db:e,args:t,opts:n,budget:i})=>{let r=pr(e,H(t,0),{semantic:i.semantic});if(R(n,"json")){$("dataflow",t,n,r);return}if(!r)return P.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
926
+ `);for(let o=0;o<r.length;o++)console.log(` ${String(Me(i.startLine+o)).padStart(4)} ${r[o]}`)}),ZM=X("dataflow",({db:e,args:t,opts:n,budget:i})=>{let r=pr(e,H(t,0),{semantic:i.semantic});if(R(n,"json")){F("dataflow",t,n,r);return}if(!r)return P.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
926
927
  `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let o of r.definitionSites)console.log(` ${o.file}:${Me(o.line)}`)}if(r.usageSites.length>0){console.log(`
927
928
  \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of r.usageSites)console.log(` ${o.file}:${Me(o.line)} in ${o.enclosingShort}`)}if(r.producers.length>0){console.log(`
928
929
  \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let o of r.producers)console.log(` ${o.file} ${o.shortName}`)}if(r.consumers.length>0){console.log(`
929
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of r.consumers)console.log(` ${o.file} ${o.shortName}`)}}),UM=X("slice",({db:e,args:t,opts:n,budget:i})=>{let r=R(n,"forward")?"forward":"backward",o=mi(e,H(t,0),{direction:r,maxDepth:N(n,"depth",3),semantic:i.semantic});if(R(n,"json")){$("slice",t,n,o);return}if(!o)return P.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
930
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of r.consumers)console.log(` ${o.file} ${o.shortName}`)}}),eO=X("slice",({db:e,args:t,opts:n,budget:i})=>{let r=R(n,"forward")?"forward":"backward",o=mi(e,H(t,0),{direction:r,maxDepth:N(n,"depth",3),semantic:i.semantic});if(R(n,"json")){F("slice",t,n,o);return}if(!o)return P.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
930
931
  `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}P.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
931
932
  ${s.relationship}`),console.log(`
932
- ${o.connectedSymbols.length} connected symbol(s).`)}),db=[ht({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:w("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Is(e,H(t,0)),format:e=>e.relativePath}),ht({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:w("Navigation"),query:({db:e,args:t})=>pa(e,H(t,0)),format:e=>` ${ve(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:w("Navigation",["scip-query refs login"]),handler:HM},Cs({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:w("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Wi(e,H(t,0),{semantic:n.semantic}),sections:MM}),ht({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:w("Navigation"),query:({db:e,args:t})=>Gi(e,H(t,0)),format:e=>e.relativePath}),ht({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:w("Navigation"),query:({db:e,args:t})=>zi(e,H(t,0)),format:e=>e.relativePath}),Fh({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:w("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Ki(e,H(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ve(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),ht({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:w("Navigation"),query:({db:e,args:t})=>Ji(e,H(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:w("Navigation"),handler:BM},ht({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:w("Navigation"),query:({db:e,args:t})=>va(e,H(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:_([f("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:w("Navigation"),handler:OM},ht({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:w("Navigation"),query:({db:e,args:t})=>wa(e,H(t,0)),format:e=>` ${ve(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),ht({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",v,100),f("--full","Run unbounded analysis on large indexes")],docs:w("Navigation"),query:({db:e,args:t,opts:n})=>$a(e,H(t,0),{scope:E(n,"scope"),limit:O(n,"limit",100)}),format:e=>` ${ye(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${H(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
933
- ${e.length} symbol(s)`)}),xs({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[f("-s, --scope <path>","Limit to files matching path")],docs:w("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Aa(e,{scope:E(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),ht({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:w("Navigation"),query:({db:e,args:t})=>Oa(e,H(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,emptyMessage:()=>"Symbol not found."}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:_([f("-C, --context <n>","Extra lines of context above/below",v,0)]),renderShape:"custom",docs:w("Navigation"),handler:VM},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Navigation"),handler:qM},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:_([f("--forward","Forward slice (what does this affect). Default is backward."),f("--depth <n>","Max transitive depth for backward slice",v,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Navigation"),handler:UM}];var WM=X("plan-context",({db:e,args:t,opts:n,budget:i})=>{let r=O(n,"limit",20),o=xc(e,H(t,0),{semantic:i.semantic,impactDepth:N(n,"impactDepth",3),sliceDepth:N(n,"sliceDepth",3),scope:E(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(R(n,"json")){$("plan-context",t,n,o);return}return P.empty(o.warnings[0])}if(R(n,"json")){$("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:GM(o)},{title:"DEFINITIONS",rows:zM(o,r),skipIfEmpty:!0},{title:"REFERENCES",rows:KM(o,r),skipIfEmpty:!0},{title:"CALL GRAPH",rows:JM(o,r),skipIfEmpty:!0},{title:"DATAFLOW",rows:QM(o,r),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:XM(o,r),skipIfEmpty:!0},{title:"SURFACE",rows:YM(o,r),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:ZM(o,r),skipIfEmpty:!0},{title:"CHANGE RISK",rows:eO(o,r),skipIfEmpty:!0},{title:"HISTORY",rows:tO(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:nO(o),skipIfEmpty:!0}];P.sectionedReport(s)}),mb=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:_([f("--impact-depth <n>","Maximum affected traversal depth",v,3),f("--slice-depth <n>","Maximum backward slice depth",v,3),f("-s, --scope <path>","Limit downstream impact to files matching path"),f("-n, --limit <n>","Rows per section",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Planning",["scip-query plan-context parseSymbol"]),handler:WM}];function GM(e){return[`Target: ${e.target}`,`Matched: symbol=${wl(e.matched.symbol)} file=${wl(e.matched.file)} module=${wl(e.matched.module)}`]}function zM(e,t){let n=[];for(let i of e.trace.definitions){let r=i.signature?` -- ${i.signature}`:"";n.push(` ${ye(i.relativePath,i.startLine,i.endLine)}${r}`),i.source&&n.push(...i.source.split(`
934
- `).map((o,s)=>` ${String(Me(i.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${ve(i.startLine,i.endLine)} ${i.shortName}`)),zt(n,t).rows}function KM(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${Me(i.line)} in ${i.enclosingShort}`);return Fn(zt(n,t))}function JM(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(r=>` caller ${r.file} ${r.shortName}`),i=e.callGraph.callees.map(r=>` callee ${r.file} ${r.shortName}`);return Fn(zt([...n,...i],t))}function QM(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),i=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),r=e.dataflow.usageSites.map(o=>` usage ${o.file}:${Me(o.line)} in ${o.enclosingShort}`);return Fn(zt([...n,...i,...r],t))}function XM(e,t){let n=[...e.deps.map(i=>` file depends on ${i.relativePath}`),...e.rdeps.map(i=>` file depended on by ${i.relativePath}`),...e.system.dependsOn.map(i=>` module depends on ${i}`),...e.system.dependedOnBy.map(i=>` module used by ${i}`)];return Fn(zt(n,t))}function YM(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${ve(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return Fn(zt(n,t))}function ZM(e,t){let n=[],i=-1;for(let r of e.affected)r.depth!==i&&(n.push(` -- Depth ${r.depth} --`),i=r.depth),n.push(` ${r.file} ${r.shortName}`);return Fn(zt(n,t))}function eO(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),n.push(...e.changeSurface.symbols.map(i=>{let r=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${ve(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${r}`}))),e.complexity&&(n.push(` Complexity: ${ye(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),Fn(zt(n,t))}function tO(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let i=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${i}`)}for(let i of t.coChangePartners)n.push(` Usually changes with: ${i.file} (${i.together}x, ${Math.round(i.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function nO(e){let t=e.warnings.map(i=>` ${i}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(i=>i.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function zt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Fn(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function wl(e){return e?"yes":"no"}var pb=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],iO=[ab,db,cb,vs,ub,mb,lb],fb=iO.flat(),rO=new Map(fb.map(e=>[e.id,e]));for(let e of fb)if(!pb.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var ki=pb.map(e=>oO(e));function oO(e){let t=rO.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var sO=ki.slice(0,Ll("plan-context")),aO=ki.slice(Rs("drift"),Ll("self-audit")),cO=ki.slice(Rs("convergence"),Ll("slice")),lO=ki.slice(Rs("redundant-reexports")),gb=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[f("-l, --language <lang>","Index only this language (can be repeated)",Zo,[]),f("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),f("--force","Rebuild even if source inputs are unchanged"),f("--allow-partial","Write an incomplete index when one or more detected languages fail"),f("--indexer-concurrency <n>","Number of language indexers to run at once",es)],renderShape:"custom",docs:w("Indexing",["scip-query reindex"]),handler:uh},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:w("Indexing"),handler:dh},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[f("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:w("Indexing"),handler:mh},...sO,{id:Xo,command:Xo,description:"Internal diff-impact batch worker",hidden:!0,options:[f("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:ph},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:_([f("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:w("Impact"),handler:fh},...aO,{id:Qo,command:Qo,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:gh},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),f("--json","Output as JSON for programmatic consumption"),f("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),f("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:w("Health",["scip-query health --json","scip-query health --baseline"]),handler:hh},...cO,{id:"install-skills",command:"install-skills",description:`Install skills (${al.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:w("Maintenance"),handler:bh},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:yh},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:og},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:sg},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:w("Maintenance"),handler:Sh},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:xh},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:Ch},...lO,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:w("Maintenance"),handler:Rh},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance",["scip-query config-validate"]),handler:kh},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:_([f("--reason <text>","Required human reason for accepting the finding"),f("--check <check>","Optional detector/check name to narrow the suppression"),f("--file <path>","Optional file path to narrow the suppression"),f("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:w("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:wh},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:Lh},{id:"setup",command:"setup",description:"Bootstrap this project: install agent skills, refresh the index, verify capabilities, and report health",options:_([f("--git-hook","Also install a git pre-commit hook that runs diff-gate")]),renderShape:"custom",docs:w("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Ph},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[f("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Ih},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[f("--force","Overwrite an existing workflow"),f("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-ci"]),handler:Nh},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[f("--debounce <ms>","Ms to wait after last change (default: 30000)",Hc),f("--cooldown <ms>","Min ms between reindexes (default: 60000)",Hc)],renderShape:"custom",docs:w("Maintenance"),handler:Eh},{id:"status",command:"status",description:"Show index status for this project",options:[f("--json","Output as JSON for programmatic consumption"),f("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:w("Maintenance"),handler:Th}];function Rs(e){let t=ki.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function Ll(e){return Rs(e)+1}function hb(e,t){return t.map(n=>{let i=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);i.description(n.description);for(let r of n.arguments??[])i.argument(r.name);for(let r of n.options??[])r.parser&&Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.parser,r.defaultValue):r.parser?i.option(r.flags,r.description,r.parser):Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.defaultValue):i.option(r.flags,r.description);return i.action(async(...r)=>{try{await n.handler(...r)}catch(o){uO(o)}}),{descriptor:n,command:i}})}function uO(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as dO,mkdirSync as mO,readFileSync as pO,writeFileSync as fO}from"fs";import{homedir as gO}from"os";import{join as ks}from"path";var hO=1440*60*1e3,yb="update-check.json",bO="https://registry.npmjs.org/scip-query/latest";async function Sb(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??xO(t),i=e.now??Date.now(),r=e.currentVersion??Jo,o=CO(n),s=o&&i-o.checkedAt<hO?o.latestVersion:await vO(n,e.fetchLatestVersion??kO,i);if(!s||!SO(s,r))return;(e.writeNotice??(c=>console.error(c)))(yO(r,s))}function yO(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
935
- `)}function SO(e,t){let n=bb(e),i=bb(t);if(!n||!i)return e!==t;for(let r=0;r<n.length;r++){let o=n[r]-i[r];if(o>0)return!0;if(o<0)return!1}return!1}function xO(e){let t=e.XDG_CACHE_HOME||ks(gO(),".cache");return ks(t,"scip-query")}function CO(e){let t=ks(e,yb);if(!dO(t))return null;try{let n=JSON.parse(pO(t,"utf8"));return typeof n.checkedAt=="number"&&(typeof n.latestVersion=="string"||n.latestVersion===null)?{checkedAt:n.checkedAt,latestVersion:n.latestVersion}:null}catch{return null}}async function vO(e,t,n){let i;try{i=await t()}catch{i=null}return RO(e,{checkedAt:n,latestVersion:i}),i}function RO(e,t){try{mO(e,{recursive:!0}),fO(ks(e,yb),`${JSON.stringify(t,null,2)}
936
- `)}catch{}}async function kO(){let e=await fetch(bO,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function bb(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}ws.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Jo);hb(ws,gb);ws.hook("preAction",async()=>{await Sb()});LO()&&await ws.parseAsync();function LO(){if(!process.argv[1])return!1;let e=wO(import.meta.url);try{return xb(e)===xb(process.argv[1])}catch{return e===process.argv[1]}}export{ws as program,bi as renderHeuristicNotice};
933
+ ${o.connectedSymbols.length} connected symbol(s).`)}),yb=[ht({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:w("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Es(e,H(t,0)),format:e=>e.relativePath}),ht({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:w("Navigation"),query:({db:e,args:t})=>ha(e,H(t,0)),format:e=>` ${ve(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:w("Navigation",["scip-query refs login"]),handler:XM},ks({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:w("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Wi(e,H(t,0),{semantic:n.semantic}),sections:zM}),ht({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:w("Navigation"),query:({db:e,args:t})=>Gi(e,H(t,0)),format:e=>e.relativePath}),ht({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:w("Navigation"),query:({db:e,args:t})=>zi(e,H(t,0)),format:e=>e.relativePath}),Hh({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:w("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Ki(e,H(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ve(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),ht({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:w("Navigation"),query:({db:e,args:t})=>Ji(e,H(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:w("Navigation"),handler:QM},ht({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:w("Navigation"),query:({db:e,args:t})=>wa(e,H(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:_([f("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:w("Navigation"),handler:KM},ht({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:w("Navigation"),query:({db:e,args:t})=>Ia(e,H(t,0)),format:e=>` ${ve(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),ht({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",v,100),f("--full","Run unbounded analysis on large indexes")],docs:w("Navigation"),query:({db:e,args:t,opts:n})=>Oa(e,H(t,0),{scope:E(n,"scope"),limit:O(n,"limit",100)}),format:e=>` ${ye(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${H(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
934
+ ${e.length} symbol(s)`)}),Rs({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[f("-s, --scope <path>","Limit to files matching path")],docs:w("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>ja(e,{scope:E(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),ht({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:w("Navigation"),query:({db:e,args:t})=>Ha(e,H(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,emptyMessage:()=>"Symbol not found."}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:_([f("-C, --context <n>","Extra lines of context above/below",v,0)]),renderShape:"custom",docs:w("Navigation"),handler:YM},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:_([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Navigation"),handler:ZM},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:_([f("--forward","Forward slice (what does this affect). Default is backward."),f("--depth <n>","Max transitive depth for backward slice",v,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Navigation"),handler:eO}];var tO=X("plan-context",({db:e,args:t,opts:n,budget:i})=>{let r=O(n,"limit",20),o=Rc(e,H(t,0),{semantic:i.semantic,impactDepth:N(n,"impactDepth",3),sliceDepth:N(n,"sliceDepth",3),scope:E(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(R(n,"json")){F("plan-context",t,n,o);return}return P.empty(o.warnings[0])}if(R(n,"json")){F("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:nO(o)},{title:"DEFINITIONS",rows:iO(o,r),skipIfEmpty:!0},{title:"REFERENCES",rows:rO(o,r),skipIfEmpty:!0},{title:"CALL GRAPH",rows:oO(o,r),skipIfEmpty:!0},{title:"DATAFLOW",rows:sO(o,r),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:aO(o,r),skipIfEmpty:!0},{title:"SURFACE",rows:cO(o,r),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:lO(o,r),skipIfEmpty:!0},{title:"CHANGE RISK",rows:uO(o,r),skipIfEmpty:!0},{title:"HISTORY",rows:dO(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:mO(o),skipIfEmpty:!0}];P.sectionedReport(s)}),Sb=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:_([f("--impact-depth <n>","Maximum affected traversal depth",v,3),f("--slice-depth <n>","Maximum backward slice depth",v,3),f("-s, --scope <path>","Limit downstream impact to files matching path"),f("-n, --limit <n>","Rows per section",v,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:w("Planning",["scip-query plan-context parseSymbol"]),handler:tO}];function nO(e){return[`Target: ${e.target}`,`Matched: symbol=${Il(e.matched.symbol)} file=${Il(e.matched.file)} module=${Il(e.matched.module)}`]}function iO(e,t){let n=[];for(let i of e.trace.definitions){let r=i.signature?` -- ${i.signature}`:"";n.push(` ${ye(i.relativePath,i.startLine,i.endLine)}${r}`),i.source&&n.push(...i.source.split(`
935
+ `).map((o,s)=>` ${String(Me(i.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${ve(i.startLine,i.endLine)} ${i.shortName}`)),zt(n,t).rows}function rO(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${Me(i.line)} in ${i.enclosingShort}`);return $n(zt(n,t))}function oO(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(r=>` caller ${r.file} ${r.shortName}`),i=e.callGraph.callees.map(r=>` callee ${r.file} ${r.shortName}`);return $n(zt([...n,...i],t))}function sO(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),i=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),r=e.dataflow.usageSites.map(o=>` usage ${o.file}:${Me(o.line)} in ${o.enclosingShort}`);return $n(zt([...n,...i,...r],t))}function aO(e,t){let n=[...e.deps.map(i=>` file depends on ${i.relativePath}`),...e.rdeps.map(i=>` file depended on by ${i.relativePath}`),...e.system.dependsOn.map(i=>` module depends on ${i}`),...e.system.dependedOnBy.map(i=>` module used by ${i}`)];return $n(zt(n,t))}function cO(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${ve(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return $n(zt(n,t))}function lO(e,t){let n=[],i=-1;for(let r of e.affected)r.depth!==i&&(n.push(` -- Depth ${r.depth} --`),i=r.depth),n.push(` ${r.file} ${r.shortName}`);return $n(zt(n,t))}function uO(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),n.push(...e.changeSurface.symbols.map(i=>{let r=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${ve(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${r}`}))),e.complexity&&(n.push(` Complexity: ${ye(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),$n(zt(n,t))}function dO(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let i=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${i}`)}for(let i of t.coChangePartners)n.push(` Usually changes with: ${i.file} (${i.together}x, ${Math.round(i.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function mO(e){let t=e.warnings.map(i=>` ${i}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(i=>i.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function zt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function $n(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Il(e){return e?"yes":"no"}var xb=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],pO=[fb,yb,gb,ws,bb,Sb,hb],Cb=pO.flat(),fO=new Map(Cb.map(e=>[e.id,e]));for(let e of Cb)if(!xb.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var ki=xb.map(e=>gO(e));function gO(e){let t=fO.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var hO=ki.slice(0,Pl("plan-context")),bO=ki.slice(Ls("drift"),Pl("self-audit")),yO=ki.slice(Ls("convergence"),Pl("slice")),SO=ki.slice(Ls("redundant-reexports")),vb=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[f("-l, --language <lang>","Index only this language (can be repeated)",es,[]),f("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),f("--force","Rebuild even if source inputs are unchanged"),f("--allow-partial","Write an incomplete index when one or more detected languages fail"),f("--indexer-concurrency <n>","Number of language indexers to run at once",ts)],renderShape:"custom",docs:w("Indexing",["scip-query reindex"]),handler:bh},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:w("Indexing"),handler:yh},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[f("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:w("Indexing"),handler:Sh},...hO,{id:Yo,command:Yo,description:"Internal diff-impact batch worker",hidden:!0,options:[f("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:xh},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:_([f("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:w("Impact"),handler:Ch},...bO,{id:Xo,command:Xo,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:vh},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),f("--json","Output as JSON for programmatic consumption"),f("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),f("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:w("Health",["scip-query health --json","scip-query health --baseline"]),handler:Rh},...yO,{id:"install-skills",command:"install-skills",description:`Install skills (${ul.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:w("Maintenance"),handler:kh},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:wh},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:cg},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:lg},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:w("Maintenance"),handler:Lh},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:Dh},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:Ih},...SO,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:w("Maintenance"),handler:Nh},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance",["scip-query config-validate"]),handler:Eh},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:_([f("--reason <text>","Required human reason for accepting the finding"),f("--check <check>","Optional detector/check name to narrow the suppression"),f("--file <path>","Optional file path to narrow the suppression"),f("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:w("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:Th},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:_h},{id:"setup",command:"setup",description:"Bootstrap this project: install agent skills, refresh the index, verify capabilities, and report health",options:_([f("--git-hook","Also install a git pre-commit hook that runs diff-gate")]),renderShape:"custom",docs:w("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Ah},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[f("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Fh},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[f("--force","Overwrite an existing workflow"),f("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-ci"]),handler:Mh},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[f("--debounce <ms>","Ms to wait after last change (default: 30000)",Uc),f("--cooldown <ms>","Min ms between reindexes (default: 60000)",Uc)],renderShape:"custom",docs:w("Maintenance"),handler:Oh},{id:"status",command:"status",description:"Show index status for this project",options:[f("--json","Output as JSON for programmatic consumption"),f("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:w("Maintenance"),handler:jh}];function Ls(e){let t=ki.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function Pl(e){return Ls(e)+1}function Rb(e,t){return t.map(n=>{let i=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);i.description(n.description);for(let r of n.arguments??[])i.argument(r.name);for(let r of n.options??[])r.parser&&Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.parser,r.defaultValue):r.parser?i.option(r.flags,r.description,r.parser):Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.defaultValue):i.option(r.flags,r.description);return i.action(async(...r)=>{try{await n.handler(...r)}catch(o){xO(o)}}),{descriptor:n,command:i}})}function xO(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as CO,mkdirSync as vO,readFileSync as RO,writeFileSync as kO}from"fs";import{homedir as wO}from"os";import{join as Ds}from"path";var LO=1440*60*1e3,wb="update-check.json",DO="https://registry.npmjs.org/scip-query/latest";async function Lb(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??NO(t),i=e.now??Date.now(),r=e.currentVersion??Qo,o=EO(n),s=o&&i-o.checkedAt<LO?o.latestVersion:await TO(n,e.fetchLatestVersion??$O,i);if(!s||!PO(s,r))return;(e.writeNotice??(c=>console.error(c)))(IO(r,s))}function IO(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
936
+ `)}function PO(e,t){let n=kb(e),i=kb(t);if(!n||!i)return e!==t;for(let r=0;r<n.length;r++){let o=n[r]-i[r];if(o>0)return!0;if(o<0)return!1}return!1}function NO(e){let t=e.XDG_CACHE_HOME||Ds(wO(),".cache");return Ds(t,"scip-query")}function EO(e){let t=Ds(e,wb);if(!CO(t))return null;try{let n=JSON.parse(RO(t,"utf8"));return typeof n.checkedAt=="number"&&(typeof n.latestVersion=="string"||n.latestVersion===null)?{checkedAt:n.checkedAt,latestVersion:n.latestVersion}:null}catch{return null}}async function TO(e,t,n){let i;try{i=await t()}catch{i=null}return _O(e,{checkedAt:n,latestVersion:i}),i}function _O(e,t){try{vO(e,{recursive:!0}),kO(Ds(e,wb),`${JSON.stringify(t,null,2)}
937
+ `)}catch{}}async function $O(){let e=await fetch(DO,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function kb(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}Is.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Qo);Rb(Is,vb);Is.hook("preAction",async()=>{await Lb()});AO()&&await Is.parseAsync();function AO(){if(!process.argv[1])return!1;let e=FO(import.meta.url);try{return Db(e)===Db(process.argv[1])}catch{return e===process.argv[1]}}export{Is as program,bi as renderHeuristicNotice};
937
938
  //# sourceMappingURL=cli.js.map