scip-query 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{program as Di}from"commander";import{realpathSync as sd}from"fs";import{fileURLToPath as QN}from"url";import{createRequire as YC}from"module";import{fileURLToPath as mu}from"url";import{statSync as ad}from"fs";function Ne(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...cd(e.config.dbPath)}}function cd(e){try{let t=ad(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function T(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",r=t.like?"AND relative_path LIKE ?":"",i=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
2
+ import{program as Di}from"commander";import{realpathSync as cd}from"fs";import{fileURLToPath as YN}from"url";import{createRequire as ZC}from"module";import{fileURLToPath as mu}from"url";import{statSync as ld}from"fs";function Ne(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...ud(e.config.dbPath)}}function ud(e){try{let t=ld(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function A(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",r=t.like?"AND relative_path LIKE ?":"",i=[...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
  ${r}
8
- ORDER BY relative_path`,...i).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 ld(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Ni(e,t){let n=ld(t);return T(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as Qs}from"path";var ud={".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 $(e){return ud[Qs(e).toLowerCase()]??null}function ht(e){return Qs(e).toLowerCase()===".vue"}var Ks=[];function rt(e){e.groups.length>0&&Ks.push(e)}function Li(e,t){let n=new Set(t.groups);for(let r of Ks)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function Ys(){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 W(e,t){let{cache:n,ensure:r}=Ys(),i={get(o,s,a){let c=r(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 rt({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function re(e,t){let n=new WeakMap,r={get(i,o){let s=n.get(i);if(s)return s.value;let a=o();return n.set(i,{value:a}),a},invalidate(i){n.delete(i)},has(i){return n.has(i)}};return rt({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}function ur(e,t){let{cache:n,ensure:r}=Ys(),i={get(o,s,a,c){let l=r(o),u=l.get(s);if(u&&u.source===a)return u.value;let m=c();return l.set(s,{source:a,value:m}),m},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return rt({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}import{createRequire as md}from"module";var ae=md(import.meta.url),mr=null,Xs=!1;function dd(){if(Xs)return null;if(mr)return mr;try{return mr=ae("tree-sitter"),mr}catch{return Xs=!0,null}}var Zs=new Map,_i=new Set;function pd(e){if(_i.has(e))return null;let t=Zs.get(e);if(t)return t;let n;try{switch(e){case"rust":n=ae("tree-sitter-rust");break;case"typescript":n=ae("tree-sitter-typescript").typescript;break;case"tsx":n=ae("tree-sitter-typescript").tsx;break;case"javascript":n=ae("tree-sitter-javascript");break;case"python":n=ae("tree-sitter-python");break;case"java":n=ae("tree-sitter-java");break;case"kotlin":n=ae("tree-sitter-kotlin");break;case"scala":n=ae("tree-sitter-scala");break;case"ruby":n=ae("tree-sitter-ruby");break;case"c":n=ae("tree-sitter-c");break;case"cpp":n=ae("tree-sitter-cpp");break;case"csharp":n=ae("tree-sitter-c-sharp");break;case"php":n=ae("tree-sitter-php").php;break;case"vb":{let r=ae("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return _i.add(e),null}return Zs.set(e,n),n}var ea=new Map;function fd(e){let t=ea.get(e);if(t)return t;let n=pd(e);if(!n)return null;let r=dd();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return _i.add(e),null}return ea.set(e,i),i}function gd(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function wi(e,t){let n=fd(e);if(!n)return null;try{return gd(n,t)}catch{return null}}import{existsSync as hd,readFileSync as yd}from"fs";import{join as bd}from"path";var Sd=W("source-text",{clearGroups:["whole-project","source-file"]});function A(e,t){let n=t.replace(/\\/g,"/");return Sd.get(e,n,()=>{let r=bd(e.config.projectRoot,n);return hd(r)?yd(r,"utf-8"):""})}var xd=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function Ei(e,t,n){if(n<=0)return!1;let r=A(e,t);if(!r)return!1;let i=r.split(`
9
- `);for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(xd.test(s))return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function ta(e){let t=[],n=/<script\b([^>]*)>([\s\S]*?)<\/script>/g;for(let a of e.matchAll(n))typeof a.index=="number"&&t.push({tagOpen:a[1]??"",body:a[2]??"",openIdx:a.index+(a[0].length-(a[2]?.length??0)-9)});if(t.length===0)return null;let r=t.find(a=>/\bsetup\b/.test(a.tagOpen))??t[0],o=r.tagOpen.match(/\blang\s*=\s*["']?([\w-]+)/)?.[1]?.toLowerCase(),s=o==="ts"||o==="typescript"?"typescript":o==="tsx"?"tsx":"javascript";return{body:r.body,startLine:Cd(e,r.openIdx),language:s}}function Cd(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}var na=ur("ast-trees",{clearGroups:["whole-project","source-file"]});function ce(e,t){if(ht(t))return Rd(e,t);let n=$(t);if(!n)return null;let r=A(e,t);return r?na.get(e,t,r,()=>wi(n,r)):null}function Rd(e,t){let n=A(e,t);return n?na.get(e,t,n,()=>{let r=ta(n);if(!r)return null;let i=`
10
- `.repeat(r.startLine)+r.body;return wi(r.language,i)}):null}function ra(e,t){let n=Id(e,t);if(!n)return null;let r=zt(n);return r?{calleeLeaf:r,memberAccess:vd(n),line:e.startPosition.row}:null}function Id(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 vd(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function zt(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?zt(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?zt(t):null}case"super":case"self":case"this":return null;default:return null}}function In(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var Dd=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function ca(e,t){let n=Ld(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:sa(n.functionNode),params:ia(n.functionNode),paramsEndLine:oa(n.functionNode),isLiteralPassthrough:aa(n.functionNode,t)};if(!Nd(e.type,t))return null;let r=e.childForFieldName("name")??e.namedChildren.find(i=>i.type==="identifier"||i.type==="property_identifier");return r?{name:r.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:sa(e),params:ia(e),paramsEndLine:oa(e),isLiteralPassthrough:aa(e,t)}:null}function la(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function ia(e){let t=la(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(In(r))continue;if(r.type==="identifier"){n.push({name:r.text,simple:!0});continue}let i=r.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(r.text),o=r.childForFieldName("pattern");if(!i&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=r.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function oa(e){let t=la(e);return t?t.endPosition.row:e.startPosition.row}function Nd(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?Dd.has(e):!1}function Ld(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}return null}function sa(e){let t=e.namedChildren.find(r=>r.type==="parameters"||r.type==="formal_parameters");if(!t)return 0;let n=0;for(let r of t.namedChildren)In(r)||(n+=1);return n}function aa(e,t){let n=e.namedChildren.find(m=>m.type==="block"||m.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(m=>!In(m));if(r.length!==1)return!1;let i=r[0],o=null;if(i.type==="return_statement"||i.type==="expression_statement"?o=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(o=i),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(m=>m.type==="arguments"||m.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(m=>!In(m)),l=e.namedChildren.find(m=>m.type==="parameters"||m.type==="formal_parameters");if(!l)return!1;let u=[];for(let m of l.namedChildren){if(m.type==="identifier"){u.push(m.text);continue}let d=m.namedChildren.find(p=>p.type==="identifier");d&&u.push(d.text)}if(c.length!==u.length)return!1;for(let m=0;m<u.length;m+=1){let d=c[m];if(d.type!=="identifier"||d.text!==u[m])return!1}return!0}var _d=new Set(["identifier","type_identifier","field_identifier"]),wd=new Set(["identifier"]),Ed=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),kd=new Set(["rust","python"]),Pd=/\{([^{}]*)\}/g,Fd=/\b([A-Za-z_][\w]*)\b/g;function ua(e,t){return Td(t).has(e.type)}function ma(e,t){return kd.has(t)&&e.type==="string_content"}function da(e){let t=0;for(let r of e.values()){let i=r[r.length-1];i!==void 0&&i>t&&(t=i)}let n=new Array(t+1);for(let r=0;r<=t;r+=1)n[r]=new Set;for(let[r,i]of e)for(let o of i)n[o].add(r);return n}function Td(e){return e==="rust"?_d:e==="python"?wd:Ed}function pa(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(Pd)){let i=r[1]??"";for(let o of i.matchAll(Fd))o[1]&&t(o[1],n)}}var Ad=[/\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],Md=/^#!?\[\s*serde\s*\(/,Od=/^#!?\[\s*schemars\s*\(/,$d=/^#!?\[\s*validate\s*\(/,jd=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function fa(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let r=e.childForFieldName("function")??e.namedChild(0);if(!r)return;let i=zt(r);if(!i||!jd.has(i))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 ga(e,t){let n=Md.test(e),r=Od.test(e),i=$d.test(e);if(!(!n&&!r&&!i))for(let o of Ad){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 ha(e,t){let n=new Map,r=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},i=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{i.has(l.type)&&l.text!==a&&r(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&&r(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 ya=new WeakMap;function K(e,t){let n=$(t);if(!n)return null;let r=ce(e,t);if(!r)return null;let i=ya.get(r);if(i)return i;let o=Hd(r,n);return ya.set(r,o),o}function ki(e,t,n,r){let i=K(e,t);return i?Bd(i,n,r)?.isLiteralPassthrough??!0:!0}function Bd(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function Hd(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let m=s.get(l);if(!m){s.set(l,[u]);return}m[m.length-1]!==u&&m.push(u)},c=l=>{let u=ca(l,t);u&&n.push(u);let m=ra(l,t);m&&r.push(m),fa(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&ga(l.text,i),ua(l,t)&&a(l.text,l.startPosition.row),ma(l,t)&&pa(l,a);for(let d of l.children)c(d)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:ha(e,t),identifierLineMap:s,identifiersByLine:da(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var ba=new Set(["rust","typescript","tsx","javascript","python"]);function Pi(e,t){let n=K(e,t);return!n||!ba.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Qt(e,t){let n=K(e,t);return!n||!ba.has(n.language)?null:n.callSites}function Fi(e,t){return K(e,t)?.typeContainerMap??new Map}function yt(e,t,n={}){let r=K(e,t);if(!r)return[];let i=[];if(n.includeCrossLanguageDispatchNames)for(let o of r.crossLanguageDispatchNames)i.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&r.language==="rust")for(let o of r.rustAttrReferencedNames)i.push({name:o,kind:"rust-attribute",occurrences:1});return i}var qd={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Z(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],r=t[1],i=e.slice(n.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=Vd(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Ae(e){let t=Z(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function Vd(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||Sa(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 r;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!Sa(e[n]);)n++;r=e.slice(o,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:r,suffix:"method"}),n=o+2):o!==-1?(t.push({name:r,suffix:"method"}),n=o+1):(t.push({name:r,suffix:"term"}),n++)}else{let o=qd[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Sa(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function b(e){let t=Z(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let o=Wd(i);o&&r.push(o)}return r.join(":")}function Wd(e){let t=e.suffix==="namespace"?Ud(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function Ud(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 P(e){let t=Z(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 ee(e){let t=Z(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function ie(e){return e.endsWith("().")||ee(e)==="method"}function Y(e){let t=ee(e);return t==="method"||t==="term"}function it(e){return ee(e)==="namespace"}var Gd=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function dr(e){return Gd.test(e)}var Jd=new Set(["test","tests","_tests"]);function Kt(e){let t=Z(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&Jd.has(r.name))return!0}return!1}function xa(e,t){let n=Z(e),r=Z(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length!==i.length+1)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Ca(e,t){let n=Z(e),r=Z(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length<=i.length)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Yt(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
8
+ ORDER BY relative_path`,...i).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 md(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Ni(e,t){let n=md(t);return A(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as Qs}from"path";var dd={".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 $(e){return dd[Qs(e).toLowerCase()]??null}function yt(e){return Qs(e).toLowerCase()===".vue"}var Ks=[];function it(e){e.groups.length>0&&Ks.push(e)}function Li(e,t){let n=new Set(t.groups);for(let r of Ks)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function Ys(){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 W(e,t){let{cache:n,ensure:r}=Ys(),i={get(o,s,a){let c=r(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 it({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function re(e,t){let n=new WeakMap,r={get(i,o){let s=n.get(i);if(s)return s.value;let a=o();return n.set(i,{value:a}),a},invalidate(i){n.delete(i)},has(i){return n.has(i)}};return it({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}function ur(e,t){let{cache:n,ensure:r}=Ys(),i={get(o,s,a,c){let l=r(o),u=l.get(s);if(u&&u.source===a)return u.value;let m=c();return l.set(s,{source:a,value:m}),m},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return it({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}import{createRequire as pd}from"module";var ae=pd(import.meta.url),mr=null,Xs=!1;function fd(){if(Xs)return null;if(mr)return mr;try{return mr=ae("tree-sitter"),mr}catch{return Xs=!0,null}}var Zs=new Map,_i=new Set;function gd(e){if(_i.has(e))return null;let t=Zs.get(e);if(t)return t;let n;try{switch(e){case"rust":n=ae("tree-sitter-rust");break;case"typescript":n=ae("tree-sitter-typescript").typescript;break;case"tsx":n=ae("tree-sitter-typescript").tsx;break;case"javascript":n=ae("tree-sitter-javascript");break;case"python":n=ae("tree-sitter-python");break;case"java":n=ae("tree-sitter-java");break;case"kotlin":n=ae("tree-sitter-kotlin");break;case"scala":n=ae("tree-sitter-scala");break;case"ruby":n=ae("tree-sitter-ruby");break;case"c":n=ae("tree-sitter-c");break;case"cpp":n=ae("tree-sitter-cpp");break;case"csharp":n=ae("tree-sitter-c-sharp");break;case"php":n=ae("tree-sitter-php").php;break;case"vb":{let r=ae("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return _i.add(e),null}return Zs.set(e,n),n}var ea=new Map;function hd(e){let t=ea.get(e);if(t)return t;let n=gd(e);if(!n)return null;let r=fd();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return _i.add(e),null}return ea.set(e,i),i}function yd(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function wi(e,t){let n=hd(e);if(!n)return null;try{return yd(n,t)}catch{return null}}import{existsSync as bd,readFileSync as Sd}from"fs";import{join as xd}from"path";var Cd=W("source-text",{clearGroups:["whole-project","source-file"]});function T(e,t){let n=t.replace(/\\/g,"/");return Cd.get(e,n,()=>{let r=xd(e.config.projectRoot,n);return bd(r)?Sd(r,"utf-8"):""})}var Rd=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function Ei(e,t,n){if(n<=0)return!1;let r=T(e,t);if(!r)return!1;let i=r.split(`
9
+ `);for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(Rd.test(s))return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function ta(e){let t=[],n=/<script\b([^>]*)>([\s\S]*?)<\/script>/g;for(let a of e.matchAll(n))typeof a.index=="number"&&t.push({tagOpen:a[1]??"",body:a[2]??"",openIdx:a.index+(a[0].length-(a[2]?.length??0)-9)});if(t.length===0)return null;let r=t.find(a=>/\bsetup\b/.test(a.tagOpen))??t[0],o=r.tagOpen.match(/\blang\s*=\s*["']?([\w-]+)/)?.[1]?.toLowerCase(),s=o==="ts"||o==="typescript"?"typescript":o==="tsx"?"tsx":"javascript";return{body:r.body,startLine:Id(e,r.openIdx),language:s}}function Id(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}var na=ur("ast-trees",{clearGroups:["whole-project","source-file"]});function ce(e,t){if(yt(t))return vd(e,t);let n=$(t);if(!n)return null;let r=T(e,t);return r?na.get(e,t,r,()=>wi(n,r)):null}function vd(e,t){let n=T(e,t);return n?na.get(e,t,n,()=>{let r=ta(n);if(!r)return null;let i=`
10
+ `.repeat(r.startLine)+r.body;return wi(r.language,i)}):null}function ra(e,t){let n=Dd(e,t);if(!n)return null;let r=zt(n);return r?{calleeLeaf:r,memberAccess:Nd(n),line:e.startPosition.row}:null}function Dd(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 Nd(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function zt(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?zt(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?zt(t):null}case"super":case"self":case"this":return null;default:return null}}function In(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var Ld=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function ca(e,t){let n=wd(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:sa(n.functionNode),params:ia(n.functionNode),paramsEndLine:oa(n.functionNode),isLiteralPassthrough:aa(n.functionNode,t)};if(!_d(e.type,t))return null;let r=e.childForFieldName("name")??e.namedChildren.find(i=>i.type==="identifier"||i.type==="property_identifier");return r?{name:r.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:sa(e),params:ia(e),paramsEndLine:oa(e),isLiteralPassthrough:aa(e,t)}:null}function la(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function ia(e){let t=la(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(In(r))continue;if(r.type==="identifier"){n.push({name:r.text,simple:!0});continue}let i=r.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(r.text),o=r.childForFieldName("pattern");if(!i&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=r.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function oa(e){let t=la(e);return t?t.endPosition.row:e.startPosition.row}function _d(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?Ld.has(e):!1}function wd(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}return null}function sa(e){let t=e.namedChildren.find(r=>r.type==="parameters"||r.type==="formal_parameters");if(!t)return 0;let n=0;for(let r of t.namedChildren)In(r)||(n+=1);return n}function aa(e,t){let n=e.namedChildren.find(m=>m.type==="block"||m.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(m=>!In(m));if(r.length!==1)return!1;let i=r[0],o=null;if(i.type==="return_statement"||i.type==="expression_statement"?o=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(o=i),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(m=>m.type==="arguments"||m.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(m=>!In(m)),l=e.namedChildren.find(m=>m.type==="parameters"||m.type==="formal_parameters");if(!l)return!1;let u=[];for(let m of l.namedChildren){if(m.type==="identifier"){u.push(m.text);continue}let d=m.namedChildren.find(p=>p.type==="identifier");d&&u.push(d.text)}if(c.length!==u.length)return!1;for(let m=0;m<u.length;m+=1){let d=c[m];if(d.type!=="identifier"||d.text!==u[m])return!1}return!0}var Ed=new Set(["identifier","type_identifier","field_identifier"]),kd=new Set(["identifier"]),Pd=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),Fd=new Set(["rust","python"]),Ad=/\{([^{}]*)\}/g,Td=/\b([A-Za-z_][\w]*)\b/g;function ua(e,t){return Md(t).has(e.type)}function ma(e,t){return Fd.has(t)&&e.type==="string_content"}function da(e){let t=0;for(let r of e.values()){let i=r[r.length-1];i!==void 0&&i>t&&(t=i)}let n=new Array(t+1);for(let r=0;r<=t;r+=1)n[r]=new Set;for(let[r,i]of e)for(let o of i)n[o].add(r);return n}function Md(e){return e==="rust"?Ed:e==="python"?kd:Pd}function pa(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(Ad)){let i=r[1]??"";for(let o of i.matchAll(Td))o[1]&&t(o[1],n)}}var Od=[/\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],$d=/^#!?\[\s*serde\s*\(/,jd=/^#!?\[\s*schemars\s*\(/,Bd=/^#!?\[\s*validate\s*\(/,Hd=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function fa(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let r=e.childForFieldName("function")??e.namedChild(0);if(!r)return;let i=zt(r);if(!i||!Hd.has(i))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 ga(e,t){let n=$d.test(e),r=jd.test(e),i=Bd.test(e);if(!(!n&&!r&&!i))for(let o of Od){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 ha(e,t){let n=new Map,r=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},i=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{i.has(l.type)&&l.text!==a&&r(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&&r(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 ya=new WeakMap;function K(e,t){let n=$(t);if(!n)return null;let r=ce(e,t);if(!r)return null;let i=ya.get(r);if(i)return i;let o=Vd(r,n);return ya.set(r,o),o}function ki(e,t,n,r){let i=K(e,t);return i?qd(i,n,r)?.isLiteralPassthrough??!0:!0}function qd(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function Vd(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let m=s.get(l);if(!m){s.set(l,[u]);return}m[m.length-1]!==u&&m.push(u)},c=l=>{let u=ca(l,t);u&&n.push(u);let m=ra(l,t);m&&r.push(m),fa(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&ga(l.text,i),ua(l,t)&&a(l.text,l.startPosition.row),ma(l,t)&&pa(l,a);for(let d of l.children)c(d)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:ha(e,t),identifierLineMap:s,identifiersByLine:da(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var ba=new Set(["rust","typescript","tsx","javascript","python"]);function Pi(e,t){let n=K(e,t);return!n||!ba.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Qt(e,t){let n=K(e,t);return!n||!ba.has(n.language)?null:n.callSites}function Fi(e,t){return K(e,t)?.typeContainerMap??new Map}function bt(e,t,n={}){let r=K(e,t);if(!r)return[];let i=[];if(n.includeCrossLanguageDispatchNames)for(let o of r.crossLanguageDispatchNames)i.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&r.language==="rust")for(let o of r.rustAttrReferencedNames)i.push({name:o,kind:"rust-attribute",occurrences:1});return i}var Wd={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Z(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],r=t[1],i=e.slice(n.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=Ud(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Me(e){let t=Z(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function Ud(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||Sa(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 r;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!Sa(e[n]);)n++;r=e.slice(o,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:r,suffix:"method"}),n=o+2):o!==-1?(t.push({name:r,suffix:"method"}),n=o+1):(t.push({name:r,suffix:"term"}),n++)}else{let o=Wd[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Sa(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function b(e){let t=Z(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let o=Gd(i);o&&r.push(o)}return r.join(":")}function Gd(e){let t=e.suffix==="namespace"?Jd(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function Jd(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 P(e){let t=Z(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 ee(e){let t=Z(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function ie(e){return e.endsWith("().")||ee(e)==="method"}function Y(e){let t=ee(e);return t==="method"||t==="term"}function ot(e){return ee(e)==="namespace"}var zd=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function dr(e){return zd.test(e)}var Qd=new Set(["test","tests","_tests"]);function Kt(e){let t=Z(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&Qd.has(r.name))return!0}return!1}function xa(e,t){let n=Z(e),r=Z(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length!==i.length+1)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Ca(e,t){let n=Z(e),r=Z(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length<=i.length)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Yt(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
11
11
  FROM global_symbols gs
12
12
  JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
13
13
  JOIN documents d ON der.document_id = d.id
@@ -32,7 +32,7 @@ import{program as Di}from"commander";import{realpathSync as sd}from"fs";import{f
32
32
  ${e.pathExclusionsFor("d")}
33
33
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
34
34
  ${Ia(t.orderBy)}
35
- ${va(t.limit)}`,...t.params??[])}function Ia(e){return e?`ORDER BY ${e}`:""}function va(e){return typeof e=="number"?`LIMIT ${e}`:""}function bt(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 St(e){if(!e)return null;let t=Ra(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(Ra(r)??r).replace(/\n/g," ")}function Ra(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function zd(e){if(Ae(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 Zt(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!zd(o)||r.set(o.id,o);for(let o of e)r.set(o.id,o);let i=[...r.values()];return n.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var Qd=W("file-definitions",{clearGroups:["definition-catalog"]});function H(e,t){return Qd.get(e,t,()=>{let n=Zt(Kd(e,t),Yd(e,t),{sort:!0});return Zd(e,t,n.map(Xd))})}function Kd(e,t){return e.all(`SELECT
35
+ ${va(t.limit)}`,...t.params??[])}function Ia(e){return e?`ORDER BY ${e}`:""}function va(e){return typeof e=="number"?`LIMIT ${e}`:""}function St(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 xt(e){if(!e)return null;let t=Ra(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(Ra(r)??r).replace(/\n/g," ")}function Ra(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function Kd(e){if(Me(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 Zt(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!Kd(o)||r.set(o.id,o);for(let o of e)r.set(o.id,o);let i=[...r.values()];return n.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var Yd=W("file-definitions",{clearGroups:["definition-catalog"]});function H(e,t){return Yd.get(e,t,()=>{let n=Zt(Xd(e,t),Zd(e,t),{sort:!0});return tp(e,t,n.map(ep))})}function Xd(e,t){return e.all(`SELECT
36
36
  gs.id,
37
37
  gs.symbol,
38
38
  der.document_id,
@@ -48,7 +48,7 @@ import{program as Di}from"commander";import{realpathSync as sd}from"fs";import{f
48
48
  JOIN documents d ON der.document_id = d.id
49
49
  WHERE d.relative_path = ?
50
50
  ${e.symbolNoiseFor("gs")}
51
- ORDER BY der.start_line, der.end_line`,t)}function Yd(e,t){return e.all(`SELECT
51
+ ORDER BY der.start_line, der.end_line`,t)}function Zd(e,t){return e.all(`SELECT
52
52
  gs.id,
53
53
  gs.symbol,
54
54
  c.document_id,
@@ -67,10 +67,10 @@ import{program as Di}from"commander";import{realpathSync as sd}from"fs";import{f
67
67
  AND m.role = 1
68
68
  ${e.symbolNoiseFor("gs")}
69
69
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
70
- ORDER BY start_line, end_line`,t)}function Xd(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:P(e.symbol),parentTypeName:Ae(e.symbol),isFunctionLike:Y(e.symbol),isTypeLike:ee(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Me(e,t={}){return Ti(e,t.scope)}function Ti(e,t){return T(e,{scope:t,includeIgnored:!1}).flatMap(n=>H(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function pr(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>H(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:b(i.symbol),signature:bt(St(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function be(e,t){let n=null;for(let r of e)r.startLine>t||r.endLine<t||(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n}function xt(e,t){let n=H(e,t.relative_path).find(r=>r.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 Zd(e,t,n){let r=A(e,t),i=Pi(e,t);return i?op(n,i,r):r?ep(n,r):n}function ep(e,t){let n=t.split(/\r?\n/),r=tp(e,n),i=np(e,r),o=rp(i,n);return ip(e,o)}function tp(e,t){let n=e.some(i=>fr(i.symbol))?cp(t):null,r=new Map;for(let i of e)r.set(i.symbolId,ap(t,n,i));return r}function np(e,t){return e.filter(n=>fr(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function rp(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],o=e[r+1],s=o?Math.max(i.startLine,o.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:lp(t,i.definition,i.startLine,s)})}return n}function ip(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function op(e,t,n=null){let r=new Map;for(let i of t){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return e.map(i=>{if(!sp(i)||!i.leaf)return Da(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Da(i,n);let s=o[0],a=Math.abs(s.startLine-i.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-i.startLine);u<a&&(s=l,a=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function sp(e){return fr(e.symbol)?!0:ee(e.symbol)==="term"&&Ae(e.symbol)===null}function Da(e,t){if(!t||!e.leaf||ee(e.symbol)!=="term"||Ae(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function ap(e,t,n){if(!fr(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function cp(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,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\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(r);l?.[1]&&s(l[1],a);for(let u of c.matchAll(i))u[1]&&s(u[1],a)}return o}function lp(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),o=Math.max(n,Math.min(i,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=i;l+=1){let u=up(e[l]??"");for(let m of u)m==="{"?(s+=1,c=!0):m==="}"?s=Math.max(0,s-1):m==="("?a+=1:m===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function up(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i],s=e[i+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(o==="\\"){r=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function fr(e){return e.includes("().")}function gr(e){let t=Z(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}import{existsSync as vp}from"fs";import{basename as Na,isAbsolute as Dp,join as Np}from"path";function F(e,t){let n=tn(e,t.trim());if(n)return n;let r=hp(e,t);if(r)return r;let i=mp(e,t);return i||gp(e,t)}function mp(e,t){let n=Mi(t),r=Ai(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=dp(e,i,o,n)[0];return a?xt(e,a):null}function dp(e,t,n,r){let i=Zt([],[...pp(e,t,n),...fp(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>en(o,r)>1);return i.sort((o,s)=>en(s,r)-en(o,r)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),i}function pp(e,t,n){return Yt(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function fp(e,t,n){return Xt(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function gp(e,t){let n=Mi(t),r=Rp(t),i=xp(e,r),o=Ip(i,t,n);if(o&&!e.isIgnored(o.relative_path))return xt(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=Cp(a,t,n,r);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?xt(e,s.row):null}function hp(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1),c=yp(e,r,s,a)??bp(e,r,s,a);return c&&!e.isIgnored(c.relative_path)?xt(e,c):null}function yp(e,t,n,r){return Yt(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function bp(e,t,n,r){return Xt(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function tn(e,t){let r=Yt(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??Xt(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!r||e.isIgnored(r.relative_path)?null:xt(e,r)}function hr(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=Sp(e,t.symbolId)[0];return n?xt(e,n):null}function Sp(e,t){let n=Yt(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Xt(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Zt(n,r)}function xp(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),i=n.join(`
71
- AND `),o=Yt(e,{where:i,params:r,limit:200}),s=Xt(e,{where:i,params:r,limit:200});return Zt(o,s)}function Cp(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,m=b(e.symbol),d=P(e.symbol),p=e.display_name??"",h=e.symbol.toLowerCase(),f=m.toLowerCase(),y=d.toLowerCase(),C=p.toLowerCase(),E=e.relative_path.toLowerCase(),N=/[/:.]/.test(n),I=Ai(n),v=I?.leaf.toLowerCase(),w=0;return(u===i||u===o)&&(w+=1150),(m===i||m===o)&&(w+=1100),p===s&&(w+=1180),d===s&&(w+=1160),(`${d}()`===i||`${d}()`===o)&&(w+=955),(h===a||h===c)&&(w+=1e3),(f===a||f===c)&&(w+=950),(E===a||E===c)&&(w+=925),(E.endsWith(`/${c}`)||E.endsWith(`/${a}`))&&(w+=875),C===l&&(w+=850),y===l&&(w+=825),(`${y}()`===a||`${y}()`===c)&&(w+=820),(f.endsWith(`:${c}`)||f.endsWith(`:${l}`)||f.endsWith(`:${l}()`))&&(w+=800),h.includes(c)&&(w+=120),f.includes(c)&&(w+=140),E.includes(c)&&(w+=140),C.includes(c)&&(w+=110),r.every(V=>{let O=V.toLowerCase();return h.includes(O)||f.includes(O)||E.includes(O)||C.includes(O)})&&(w+=100+r.length*15),I&&E.includes(I.path.toLowerCase())&&(w+=360,v&&(y===v||`${y}()`===v||`${y}()`==`${v}()`)&&(w+=700),ie(e.symbol)&&(w+=180)),Y(e.symbol)&&y===l&&(w+=60),!N&&it(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function Ai(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function Mi(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function Rp(e){let t=Mi(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function Ip(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=b(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||en(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>en(s,n)-en(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)),i[0]??null)}function en(e,t){let n=Ai(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=P(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:ie(e.symbol)?Ae(e.symbol)===null?5:4:Ae(e.symbol)===null?3:2:0}function me(e,t){let n=La(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Lp(e,t)}function nn(e,t){return La(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Lp(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Dp(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Np(e.config.projectRoot,r);return vp(i)?r:null}function La(e,t,n){let r=_a(t);if(!r)return[];let i=T(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:_p(a,r)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(i.length===0){let a=F(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=i.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=i.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?i:[i[0]]}function _p(e,t){let n=_a(e),r=Na(n),i=Na(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),r===i&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function _a(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as Th}from"path";import{existsSync as yr}from"fs";import{basename as wp,dirname as ot,extname as We,join as Le,relative as vn,resolve as Se}from"path";var Ep=re("indexed-paths",{clearGroups:[]}),Ct=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],br=[".py",".pyi"],fe=[".java",".scala",".kt",".kts"],Sr=[".rs"],xr=[".rb"],Cr=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],st=[".cs",".vb"],Rr=[".dart"],Rt=[".php"],kp=new Set(Ct),Oi=new Set(br),wa=new Set(fe),$i=new Set(Sr),ji=new Set(xr),Ea=new Set(Cr),ka=new Set(st),Bi=new Set(Rr),Pa=new Set(Rt),Pp=[{extensions:Ct,lookup:kp},{extensions:br,lookup:Oi},{extensions:fe,lookup:wa},{extensions:Sr,lookup:$i},{extensions:xr,lookup:ji},{extensions:Cr,lookup:Ea},{extensions:st,lookup:ka},{extensions:Rr,lookup:Bi},{extensions:Rt,lookup:Pa}];function at(e,t){return t.has(We(e).toLowerCase())}function Fp(e){return at(e,Oi)}function Tp(e){return at(e,wa)}function Ap(e){return at(e,$i)}function Mp(e){return at(e,ji)}function Op(e){return at(e,Ea)}function $p(e){return at(e,ka)}function Fa(e){return We(e).toLowerCase()===".vb"}function jp(e){return at(e,Bi)}function Bp(e){return at(e,Pa)}function Hi(e){let t=We(e).toLowerCase();for(let n of Pp)if(n.lookup.has(t))return n.extensions;return Ct}function Hp(e){return Tp(e)||$p(e)||Bp(e)}function we(e,t,n){return Fp(t)?rn(e,t,n):Ap(t)?Ue(e,t,n):Mp(t)?Ir(e,t,n):Op(t)?vr(e,t,n):Hp(t)?J(e,n.replace(/\\/g,"."),Hi(t)):jp(t)?Dr(e,t,n):qp(e,t,n)}function qp(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=ot(Le(e.config.projectRoot,t)),i=Se(r,n),o=Dn(e);for(let s of Jp(i)){let a=_e(vn(e.config.projectRoot,s));if(o.has(a)||yr(s))return a}return _e(vn(e.config.projectRoot,i))}function rn(e,t,n){let r=Dn(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=ot(Le(e.config.projectRoot,t));for(let l=1;l<s;l++)c=ot(c);i=a?Se(c,a.replace(/\./g,"/")):c}else i=Se(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Vp(i)){let s=_e(vn(e.config.projectRoot,o));if(r.has(s)||yr(o))return s}return null}function Ue(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=ot(Le(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=Se(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=Se(i,r.slice(6).replace(/::/g,"/")):o=Se(ot(i),r.slice(7).replace(/::/g,"/")),qi(e,Wp(o))}function Ir(e,t,n){let r=ot(Le(e.config.projectRoot,t)),i=Se(r,n);return qi(e,Up(i))}function vr(e,t,n){let r=ot(Le(e.config.projectRoot,t)),i=[Se(r,n),Se(e.config.projectRoot,n),Se(e.config.projectRoot,"include",n),Se(e.config.projectRoot,"src",n)];return qi(e,i)}function J(e,t,n){let r=Dn(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=i.replace(/\./g,"/"),s=i.split(".").pop()??i;for(let c of n){let l=`${o}${c}`,u=[...r].find(m=>m.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>wp(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(We(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Dr(e,t,n){let r=Dn(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=_e(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=ot(Le(e.config.projectRoot,t)),o=Se(i,n);for(let s of Gp(o)){let a=_e(vn(e.config.projectRoot,s));if(r.has(a)||yr(s))return a}return null}function Vp(e){let t=We(e);return Oi.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Le(e,"__init__.py"),Le(e,"__init__.pyi")]}function qi(e,t){let n=Dn(e);for(let r of t){let i=_e(vn(e.config.projectRoot,r));if(n.has(i)||yr(r))return i}return null}function Wp(e){let t=We(e);return $i.has(t)?[e]:[`${e}.rs`,Le(e,"mod.rs")]}function Up(e){let t=We(e);return ji.has(t)?[e]:[`${e}.rb`,Le(e,"index.rb")]}function Gp(e){let t=We(e);return Bi.has(t)?[e]:[`${e}.dart`,e]}function Jp(e){let t=We(e),n=new Set;if(t){n.add(e);for(let r of Ct)n.add(e.slice(0,-t.length)+r)}else for(let r of Ct)n.add(`${e}${r}`),n.add(Le(e,`index${r}`));return[...n]}function Dn(e){return Ep.get(e,()=>new Set(T(e,{includeIgnored:!1}).map(_e)))}function _e(e){return e.replace(/\\/g,"/")}import{basename as Aa}from"path";function It(e){return e.replace(/'''[\s\S]*?'''/g,ct).replace(/"""[\s\S]*?"""/g,ct).replace(/#.*$/gm,ct).replace(/\/\/.*$/gm,ct).replace(/\/\*[\s\S]*?\*\//g,ct).replace(/`(?:\\[\s\S]|[^`])*`/g,ct).replace(/'(?:\\.|[^'\\\r\n])*'/g,ct).replace(/"(?:\\.|[^"\\\r\n])*"/g,ct)}function ct(e){return e.replace(/[^\r\n]/g," ")}var D_=ur("stripped-lines",{clearGroups:["whole-project","source-file"]});rt({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Nr=null,Nn=""},clearFile:()=>{Nr=null,Nn=""}});var Nr=null,Nn="";function zp(e){return Nr===e||(Nr=e,Nn=It(e)),Nn}function lt(e,t,n){let r=zp(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function de(e,t){return new RegExp(`\\b${Ta(t)}\\b`,"m").test(e)}function on(e,t){let n=new Set,r=new RegExp(`\\b${Ta(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function Ta(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ln(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var Qp=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function pe(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let o=e[i];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function ge(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function z(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&Qp.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function Oe(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??J(e,r,Hi(t)),kind:"named",used:de(n,o),usedMembers:[]}}function U(e,t,n,r,i="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function sn(e,t,n,r,i="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r,usedMembers:o,isTypeOnly:s.isTypeOnly}}function vt(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Dt(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 xe(e,t,n){let r=[];for(let i of e.matchAll(t)){let o=i[0];if(!o||typeof i.index!="number")continue;let s=lt(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function Ce(e,t,n,r){let i=ce(e,t);if(i){let o=n(i);if(o)return o}return r()}function Lr(e,t,n,r){let i=ce(e,t),o=$(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Ma(e,t,n){return Ce(e,t,r=>Yp(e,t,r),()=>Kp(e,t,n))}function Kp(e,t,n){return xe(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Aa(o).replace(/\.[^.]+$/,"");return[sn(o,s,vr(e,t,o),de(i,s))]})}function Yp(e,t,n){let r=z(n,new Set(["preproc_include"])),i=[];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=Aa(s).replace(/\.[^.]+$/,"");i.push(U(s,a,vr(e,t,s),r))}return i}function Oa(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=i[1]?.trim(),s=i[2]?.trim()??null,a=i[0];if(!o||!a||typeof i.index!="number")continue;let c=lt(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:Dr(e,t,o),kind:s?"namespace":"side-effect",used:s?de(c,s):!0,usedMembers:s?on(c,s):[]})}return r}function $a(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=i[1]?.trim();o&&r.push({specifier:o,sourcePath:Dr(e,t,o)})}return r}function ja(e,t,n){return Lr(e,t,{csharp:r=>Zp(e,t,r),vb:r=>Xp(e,t,r)},()=>{let r=Fa(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return xe(n,r,(i,o)=>{let s=i[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,m=u.split(".").pop()??u,d=l?a?.trim()??m:m;return[Oe(e,t,o,u,m,d,J(e,u,st))]})})}function Xp(e,t,n){let r=z(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(d=>d.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,m=c?.text??u;i.push(U(u,m,J(e,l,st),r,c?"namespace":"named"))}return i}function Zp(e,t,n){let r=z(n,new Set(["using_directive"])),i=[];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,m=a?.text??u;i.push(U(u,m,J(e,l,st),r,a?"namespace":"named"))}return i}var ef=W("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Ba(e,t){return ef.get(e,t,()=>{let n=new Set,r=A(e,t);if(!r)return n;let o=r.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 Vi(e,t,n){return Ce(e,t,r=>nf(e,t,r),()=>tf(e,t,n))}function tf(e,t,n){return ff(n).flatMap(r=>gf(e,t,r.clause,r.specifier,r.start,r.end,n))}function nf(e,t,n){let r=rf(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...of(e,t,n,o,r));return i}function rf(e,t,n){let r=z(n,new Set(["import_statement"]));if(ht(t))for(let i of Ba(e,t))r.add(i);return r}function of(e,t,n,r,i){let o=uf(r);if(!o)return[];let s=we(e,t,o),a=ge(r,"import_clause");return a?sf(n,a,s,i,mf(r.text)):[vt("*",s)]}function sf(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(af(s.text,n,r,i));else if(s.type==="namespace_import"){let a=cf(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...lf(s,n,r,i));return o}function af(e,t,n,r){return U("default",e,t,n,"default",{isTypeOnly:r})}function cf(e,t,n,r,i){let s=ge(t,"identifier")?.text??"";if(!s)return null;let a=pf(e,s);return Dt("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function lf(e,t,n,r){let i=[];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;i.push(U(c,l,t,n,"named",{isTypeOnly:r||df(o.text)}))}return i}function uf(e){let t=ge(e,"string");if(!t)return null;let n=ge(t,"string_fragment");return n?n.text:null}function mf(e){return/^\s*import\s+type\b/.test(e)}function df(e){return/^\s*type\b/.test(e.trim())}function pf(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),o=r.namedChild(1);!i||!o||i.type!=="identifier"||i.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function ff(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let o=i[0],s=i[1],a=i[2];!o||!a||typeof i.index!="number"||t.push({clause:s,specifier:a,start:i.index,end:i.index+o.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let o=i[0],s=i[1];!o||!s||typeof i.index!="number"||t.push({clause:null,specifier:s,start:i.index,end:i.index+o.length})}return t.sort((i,o)=>i.start-o.start)}function gf(e,t,n,r,i,o,s){let a=we(e,t,r),c=lt(s,i,o);return n?hf(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let m=on(c,u.localName);return Dt(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:m,used:m.length>0||de(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?vt(u.importedName,u.sourcePath):sn(u.importedName,u.localName??"",u.sourcePath,u.localName?de(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[vt("*",a)]}function hf(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=yf(r),s=[];return i&&s.push(...Ha(i,n)),o&&s.push(...Ha(o,n)),s}function Ha(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?pe(r).map(i=>{let o=i.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 yf(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Wi(e,t,n){let r=ce(e,t);return r?If(e,t,r):bf(e,t,n)}function bf(e,t,n){return[...Sf(e,t,n),...xf(e,t,n),...Cf(e,t,n)]}function Sf(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=pe(s).map(m=>Rf(m.trim())).filter(m=>!!m),l=an(n,o.index),u=an(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:we(e,t,a),names:c,startLine:l,endLine:u})}return r}function xf(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[2]??"",a=an(n,o.index),c=an(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:we(e,t,s),names:[],startLine:a,endLine:c})}return r}function Cf(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=an(n,o.index),c=an(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:we(e,t,s),names:[],startLine:a,endLine:c})}return r}function Rf(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 r=t.match(/^(\w+)$/);return r?r[1]??null:null}function an(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function If(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=vf(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=Df(i,o,s,a);r.push(c)}return r}function vf(e,t,n){let r=ge(n,"string");if(!r)return;let i=ge(r,"string_fragment");if(i)return we(e,t,i.text)}function Df(e,t,n,r){let i=ge(e,"export_clause");if(i){let s=[];for(let a of i.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:r}}return ge(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function qa(e,t,n){return Lr(e,t,{java:r=>Nf(e,t,r),kotlin:r=>Lf(e,t,r),scala:r=>_f(e,t,r)},()=>xe(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?wf(e,t,o,i):[]}))}function Nf(e,t,n){let r=z(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(m=>m.type==="asterisk"),c=o.namedChildren.find(m=>m.type==="scoped_identifier")??o.namedChildren.find(m=>m.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(Dt("*",J(e,l,fe)));continue}let u=l.split(".").pop()??l;i.push(U(u,u,J(e,l,fe),r))}return i}function Lf(e,t,n){let r=z(n,new Set(["import_header","import_list"])),i=[];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){i.push(Dt("*",J(e,s.text,fe)));continue}let l=s.text,u=l.split(".").pop()??l,d=c?.namedChild(0)?.text??u;i.push(U(u,d,J(e,l,fe),r))}return i}function _f(e,t,n){let r=z(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(m=>m.type==="namespace_selectors"||m.type==="namespace_wildcard"),a=o.namedChildren.filter(m=>m!==s&&(m.type==="identifier"||m.type==="stable_identifier")),c=a.map(m=>m.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(Dt("*",J(e,c,fe)));continue}if(s?.type==="namespace_selectors"){for(let m of s.namedChildren)if(m.type==="arrow_renamed_identifier"){let[d,p]=m.namedChildren;if(!d)continue;let h=d.text,f=p?.text??h;if(h==="_")continue;i.push(U(h,f,J(e,`${c}.${h}`,fe),r))}else if(m.type==="identifier"){let d=m.text;i.push(U(d,d,J(e,`${c}.${d}`,fe),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(m=>m.text).join(".")||c;i.push(U(l,l,J(e,u&&a.length>1?`${u}.${l}`:c,fe),r))}return i}function wf(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return pe(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 m=(l??u.split(".").pop()??u).trim(),d=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[Oe(e,t,r,d,u,m)]})}return[Oe(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Wa(e,t,n){return Ce(e,t,r=>Ef(e,t,r),()=>xe(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?pe(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,m=u.split("\\").pop()??u,d=(l??m).trim();return[Oe(e,t,i,u,m,d,J(e,u.replace(/\\/g,"."),Rt))]}):[]}))}function Ef(e,t,n){let r=z(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(U(a,c,J(e,s.replace(/\\/g,"."),Rt),r))};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:m,qualified:d}=Va(l,c);u&&o(d,u,m)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:m}=Va(c,"");l&&o(m,l,u)}}return i}function Va(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),r=e.namedChildren.filter(l=>l.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,c=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:c}}function Ga(e,t,n){return Ce(e,t,r=>kf(e,t,r),()=>Ff(n).flatMap(r=>Af(e,t,r,n)))}function kf(e,t,n){let r=z(n,new Set(["import_statement","import_from_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Ua(s);if(!a)continue;let c=rn(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=Pf(s);if(a===null)continue;let c=rn(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let m=Ua(u);m&&i.push({importedName:m.qualifiedName,localName:m.localName,sourcePath:c,kind:"named",used:r.has(m.localName),usedMembers:[]})}}return i}function Ua(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 Pf(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ge(e,"import_prefix")?.text??"",n=ge(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Ff(e){let t=e.split(`
70
+ ORDER BY start_line, end_line`,t)}function ep(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:P(e.symbol),parentTypeName:Me(e.symbol),isFunctionLike:Y(e.symbol),isTypeLike:ee(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Oe(e,t={}){return Ai(e,t.scope)}function Ai(e,t){return A(e,{scope:t,includeIgnored:!1}).flatMap(n=>H(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function pr(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>H(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:b(i.symbol),signature:St(xt(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function be(e,t){let n=null;for(let r of e)r.startLine>t||r.endLine<t||(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n}function Ct(e,t){let n=H(e,t.relative_path).find(r=>r.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 tp(e,t,n){let r=T(e,t),i=Pi(e,t);return i?ap(n,i,r):r?np(n,r):n}function np(e,t){let n=t.split(/\r?\n/),r=rp(e,n),i=ip(e,r),o=op(i,n);return sp(e,o)}function rp(e,t){let n=e.some(i=>fr(i.symbol))?up(t):null,r=new Map;for(let i of e)r.set(i.symbolId,lp(t,n,i));return r}function ip(e,t){return e.filter(n=>fr(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function op(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],o=e[r+1],s=o?Math.max(i.startLine,o.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:mp(t,i.definition,i.startLine,s)})}return n}function sp(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function ap(e,t,n=null){let r=new Map;for(let i of t){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return e.map(i=>{if(!cp(i)||!i.leaf)return Da(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Da(i,n);let s=o[0],a=Math.abs(s.startLine-i.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-i.startLine);u<a&&(s=l,a=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function cp(e){return fr(e.symbol)?!0:ee(e.symbol)==="term"&&Me(e.symbol)===null}function Da(e,t){if(!t||!e.leaf||ee(e.symbol)!=="term"||Me(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function lp(e,t,n){if(!fr(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function up(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,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\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(r);l?.[1]&&s(l[1],a);for(let u of c.matchAll(i))u[1]&&s(u[1],a)}return o}function mp(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),o=Math.max(n,Math.min(i,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=i;l+=1){let u=dp(e[l]??"");for(let m of u)m==="{"?(s+=1,c=!0):m==="}"?s=Math.max(0,s-1):m==="("?a+=1:m===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function dp(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i],s=e[i+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(o==="\\"){r=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function fr(e){return e.includes("().")}function gr(e){let t=Z(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}import{existsSync as Np}from"fs";import{basename as Na,isAbsolute as Lp,join as _p}from"path";function F(e,t){let n=tn(e,t.trim());if(n)return n;let r=bp(e,t);if(r)return r;let i=pp(e,t);return i||yp(e,t)}function pp(e,t){let n=Mi(t),r=Ti(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=fp(e,i,o,n)[0];return a?Ct(e,a):null}function fp(e,t,n,r){let i=Zt([],[...gp(e,t,n),...hp(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>en(o,r)>1);return i.sort((o,s)=>en(s,r)-en(o,r)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),i}function gp(e,t,n){return Yt(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function hp(e,t,n){return Xt(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function yp(e,t){let n=Mi(t),r=vp(t),i=Rp(e,r),o=Dp(i,t,n);if(o&&!e.isIgnored(o.relative_path))return Ct(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=Ip(a,t,n,r);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?Ct(e,s.row):null}function bp(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1),c=Sp(e,r,s,a)??xp(e,r,s,a);return c&&!e.isIgnored(c.relative_path)?Ct(e,c):null}function Sp(e,t,n,r){return Yt(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function xp(e,t,n,r){return Xt(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function tn(e,t){let r=Yt(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??Xt(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!r||e.isIgnored(r.relative_path)?null:Ct(e,r)}function hr(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=Cp(e,t.symbolId)[0];return n?Ct(e,n):null}function Cp(e,t){let n=Yt(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Xt(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Zt(n,r)}function Rp(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),i=n.join(`
71
+ AND `),o=Yt(e,{where:i,params:r,limit:200}),s=Xt(e,{where:i,params:r,limit:200});return Zt(o,s)}function Ip(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,m=b(e.symbol),d=P(e.symbol),p=e.display_name??"",h=e.symbol.toLowerCase(),f=m.toLowerCase(),y=d.toLowerCase(),C=p.toLowerCase(),E=e.relative_path.toLowerCase(),N=/[/:.]/.test(n),I=Ti(n),v=I?.leaf.toLowerCase(),w=0;return(u===i||u===o)&&(w+=1150),(m===i||m===o)&&(w+=1100),p===s&&(w+=1180),d===s&&(w+=1160),(`${d}()`===i||`${d}()`===o)&&(w+=955),(h===a||h===c)&&(w+=1e3),(f===a||f===c)&&(w+=950),(E===a||E===c)&&(w+=925),(E.endsWith(`/${c}`)||E.endsWith(`/${a}`))&&(w+=875),C===l&&(w+=850),y===l&&(w+=825),(`${y}()`===a||`${y}()`===c)&&(w+=820),(f.endsWith(`:${c}`)||f.endsWith(`:${l}`)||f.endsWith(`:${l}()`))&&(w+=800),h.includes(c)&&(w+=120),f.includes(c)&&(w+=140),E.includes(c)&&(w+=140),C.includes(c)&&(w+=110),r.every(V=>{let O=V.toLowerCase();return h.includes(O)||f.includes(O)||E.includes(O)||C.includes(O)})&&(w+=100+r.length*15),I&&E.includes(I.path.toLowerCase())&&(w+=360,v&&(y===v||`${y}()`===v||`${y}()`==`${v}()`)&&(w+=700),ie(e.symbol)&&(w+=180)),Y(e.symbol)&&y===l&&(w+=60),!N&&ot(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function Ti(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function Mi(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function vp(e){let t=Mi(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function Dp(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=b(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||en(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>en(s,n)-en(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)),i[0]??null)}function en(e,t){let n=Ti(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=P(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:ie(e.symbol)?Me(e.symbol)===null?5:4:Me(e.symbol)===null?3:2:0}function me(e,t){let n=La(e,t,{allowMultiple:!1})[0]?.relativePath;return n||wp(e,t)}function nn(e,t){return La(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function wp(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Lp(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=_p(e.config.projectRoot,r);return Np(i)?r:null}function La(e,t,n){let r=_a(t);if(!r)return[];let i=A(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:Ep(a,r)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(i.length===0){let a=F(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=i.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=i.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?i:[i[0]]}function Ep(e,t){let n=_a(e),r=Na(n),i=Na(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),r===i&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function _a(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as Mh}from"path";import{existsSync as yr}from"fs";import{basename as kp,dirname as st,extname as Ue,join as Le,relative as vn,resolve as Se}from"path";var Pp=re("indexed-paths",{clearGroups:[]}),Rt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],br=[".py",".pyi"],fe=[".java",".scala",".kt",".kts"],Sr=[".rs"],xr=[".rb"],Cr=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],at=[".cs",".vb"],Rr=[".dart"],It=[".php"],Fp=new Set(Rt),Oi=new Set(br),wa=new Set(fe),$i=new Set(Sr),ji=new Set(xr),Ea=new Set(Cr),ka=new Set(at),Bi=new Set(Rr),Pa=new Set(It),Ap=[{extensions:Rt,lookup:Fp},{extensions:br,lookup:Oi},{extensions:fe,lookup:wa},{extensions:Sr,lookup:$i},{extensions:xr,lookup:ji},{extensions:Cr,lookup:Ea},{extensions:at,lookup:ka},{extensions:Rr,lookup:Bi},{extensions:It,lookup:Pa}];function ct(e,t){return t.has(Ue(e).toLowerCase())}function Tp(e){return ct(e,Oi)}function Mp(e){return ct(e,wa)}function Op(e){return ct(e,$i)}function $p(e){return ct(e,ji)}function jp(e){return ct(e,Ea)}function Bp(e){return ct(e,ka)}function Fa(e){return Ue(e).toLowerCase()===".vb"}function Hp(e){return ct(e,Bi)}function qp(e){return ct(e,Pa)}function Hi(e){let t=Ue(e).toLowerCase();for(let n of Ap)if(n.lookup.has(t))return n.extensions;return Rt}function Vp(e){return Mp(e)||Bp(e)||qp(e)}function we(e,t,n){return Tp(t)?rn(e,t,n):Op(t)?Ge(e,t,n):$p(t)?Ir(e,t,n):jp(t)?vr(e,t,n):Vp(t)?J(e,n.replace(/\\/g,"."),Hi(t)):Hp(t)?Dr(e,t,n):Wp(e,t,n)}function Wp(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=st(Le(e.config.projectRoot,t)),i=Se(r,n),o=Dn(e);for(let s of Qp(i)){let a=_e(vn(e.config.projectRoot,s));if(o.has(a)||yr(s))return a}return _e(vn(e.config.projectRoot,i))}function rn(e,t,n){let r=Dn(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=st(Le(e.config.projectRoot,t));for(let l=1;l<s;l++)c=st(c);i=a?Se(c,a.replace(/\./g,"/")):c}else i=Se(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Up(i)){let s=_e(vn(e.config.projectRoot,o));if(r.has(s)||yr(o))return s}return null}function Ge(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=st(Le(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=Se(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=Se(i,r.slice(6).replace(/::/g,"/")):o=Se(st(i),r.slice(7).replace(/::/g,"/")),qi(e,Gp(o))}function Ir(e,t,n){let r=st(Le(e.config.projectRoot,t)),i=Se(r,n);return qi(e,Jp(i))}function vr(e,t,n){let r=st(Le(e.config.projectRoot,t)),i=[Se(r,n),Se(e.config.projectRoot,n),Se(e.config.projectRoot,"include",n),Se(e.config.projectRoot,"src",n)];return qi(e,i)}function J(e,t,n){let r=Dn(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=i.replace(/\./g,"/"),s=i.split(".").pop()??i;for(let c of n){let l=`${o}${c}`,u=[...r].find(m=>m.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>kp(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(Ue(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Dr(e,t,n){let r=Dn(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=_e(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=st(Le(e.config.projectRoot,t)),o=Se(i,n);for(let s of zp(o)){let a=_e(vn(e.config.projectRoot,s));if(r.has(a)||yr(s))return a}return null}function Up(e){let t=Ue(e);return Oi.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Le(e,"__init__.py"),Le(e,"__init__.pyi")]}function qi(e,t){let n=Dn(e);for(let r of t){let i=_e(vn(e.config.projectRoot,r));if(n.has(i)||yr(r))return i}return null}function Gp(e){let t=Ue(e);return $i.has(t)?[e]:[`${e}.rs`,Le(e,"mod.rs")]}function Jp(e){let t=Ue(e);return ji.has(t)?[e]:[`${e}.rb`,Le(e,"index.rb")]}function zp(e){let t=Ue(e);return Bi.has(t)?[e]:[`${e}.dart`,e]}function Qp(e){let t=Ue(e),n=new Set;if(t){n.add(e);for(let r of Rt)n.add(e.slice(0,-t.length)+r)}else for(let r of Rt)n.add(`${e}${r}`),n.add(Le(e,`index${r}`));return[...n]}function Dn(e){return Pp.get(e,()=>new Set(A(e,{includeIgnored:!1}).map(_e)))}function _e(e){return e.replace(/\\/g,"/")}import{basename as Ta}from"path";function vt(e){return e.replace(/'''[\s\S]*?'''/g,lt).replace(/"""[\s\S]*?"""/g,lt).replace(/#.*$/gm,lt).replace(/\/\/.*$/gm,lt).replace(/\/\*[\s\S]*?\*\//g,lt).replace(/`(?:\\[\s\S]|[^`])*`/g,lt).replace(/'(?:\\.|[^'\\\r\n])*'/g,lt).replace(/"(?:\\.|[^"\\\r\n])*"/g,lt)}function lt(e){return e.replace(/[^\r\n]/g," ")}var L_=ur("stripped-lines",{clearGroups:["whole-project","source-file"]});it({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Nr=null,Nn=""},clearFile:()=>{Nr=null,Nn=""}});var Nr=null,Nn="";function Kp(e){return Nr===e||(Nr=e,Nn=vt(e)),Nn}function ut(e,t,n){let r=Kp(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function de(e,t){return new RegExp(`\\b${Aa(t)}\\b`,"m").test(e)}function on(e,t){let n=new Set,r=new RegExp(`\\b${Aa(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function Aa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ln(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var Yp=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function pe(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let o=e[i];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function ge(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function z(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&Yp.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function $e(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??J(e,r,Hi(t)),kind:"named",used:de(n,o),usedMembers:[]}}function U(e,t,n,r,i="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function sn(e,t,n,r,i="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r,usedMembers:o,isTypeOnly:s.isTypeOnly}}function Dt(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Nt(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 xe(e,t,n){let r=[];for(let i of e.matchAll(t)){let o=i[0];if(!o||typeof i.index!="number")continue;let s=ut(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function Ce(e,t,n,r){let i=ce(e,t);if(i){let o=n(i);if(o)return o}return r()}function Lr(e,t,n,r){let i=ce(e,t),o=$(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Ma(e,t,n){return Ce(e,t,r=>Zp(e,t,r),()=>Xp(e,t,n))}function Xp(e,t,n){return xe(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Ta(o).replace(/\.[^.]+$/,"");return[sn(o,s,vr(e,t,o),de(i,s))]})}function Zp(e,t,n){let r=z(n,new Set(["preproc_include"])),i=[];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=Ta(s).replace(/\.[^.]+$/,"");i.push(U(s,a,vr(e,t,s),r))}return i}function Oa(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=i[1]?.trim(),s=i[2]?.trim()??null,a=i[0];if(!o||!a||typeof i.index!="number")continue;let c=ut(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:Dr(e,t,o),kind:s?"namespace":"side-effect",used:s?de(c,s):!0,usedMembers:s?on(c,s):[]})}return r}function $a(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=i[1]?.trim();o&&r.push({specifier:o,sourcePath:Dr(e,t,o)})}return r}function ja(e,t,n){return Lr(e,t,{csharp:r=>tf(e,t,r),vb:r=>ef(e,t,r)},()=>{let r=Fa(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return xe(n,r,(i,o)=>{let s=i[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,m=u.split(".").pop()??u,d=l?a?.trim()??m:m;return[$e(e,t,o,u,m,d,J(e,u,at))]})})}function ef(e,t,n){let r=z(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(d=>d.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,m=c?.text??u;i.push(U(u,m,J(e,l,at),r,c?"namespace":"named"))}return i}function tf(e,t,n){let r=z(n,new Set(["using_directive"])),i=[];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,m=a?.text??u;i.push(U(u,m,J(e,l,at),r,a?"namespace":"named"))}return i}var nf=W("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Ba(e,t){return nf.get(e,t,()=>{let n=new Set,r=T(e,t);if(!r)return n;let o=r.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 Vi(e,t,n){return Ce(e,t,r=>of(e,t,r),()=>rf(e,t,n))}function rf(e,t,n){return hf(n).flatMap(r=>yf(e,t,r.clause,r.specifier,r.start,r.end,n))}function of(e,t,n){let r=sf(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...af(e,t,n,o,r));return i}function sf(e,t,n){let r=z(n,new Set(["import_statement"]));if(yt(t))for(let i of Ba(e,t))r.add(i);return r}function af(e,t,n,r,i){let o=df(r);if(!o)return[];let s=we(e,t,o),a=ge(r,"import_clause");return a?cf(n,a,s,i,pf(r.text)):[Dt("*",s)]}function cf(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(lf(s.text,n,r,i));else if(s.type==="namespace_import"){let a=uf(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...mf(s,n,r,i));return o}function lf(e,t,n,r){return U("default",e,t,n,"default",{isTypeOnly:r})}function uf(e,t,n,r,i){let s=ge(t,"identifier")?.text??"";if(!s)return null;let a=gf(e,s);return Nt("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function mf(e,t,n,r){let i=[];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;i.push(U(c,l,t,n,"named",{isTypeOnly:r||ff(o.text)}))}return i}function df(e){let t=ge(e,"string");if(!t)return null;let n=ge(t,"string_fragment");return n?n.text:null}function pf(e){return/^\s*import\s+type\b/.test(e)}function ff(e){return/^\s*type\b/.test(e.trim())}function gf(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),o=r.namedChild(1);!i||!o||i.type!=="identifier"||i.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function hf(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let o=i[0],s=i[1],a=i[2];!o||!a||typeof i.index!="number"||t.push({clause:s,specifier:a,start:i.index,end:i.index+o.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let o=i[0],s=i[1];!o||!s||typeof i.index!="number"||t.push({clause:null,specifier:s,start:i.index,end:i.index+o.length})}return t.sort((i,o)=>i.start-o.start)}function yf(e,t,n,r,i,o,s){let a=we(e,t,r),c=ut(s,i,o);return n?bf(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let m=on(c,u.localName);return Nt(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:m,used:m.length>0||de(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Dt(u.importedName,u.sourcePath):sn(u.importedName,u.localName??"",u.sourcePath,u.localName?de(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Dt("*",a)]}function bf(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=Sf(r),s=[];return i&&s.push(...Ha(i,n)),o&&s.push(...Ha(o,n)),s}function Ha(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?pe(r).map(i=>{let o=i.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 Sf(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Wi(e,t,n){let r=ce(e,t);return r?Df(e,t,r):xf(e,t,n)}function xf(e,t,n){return[...Cf(e,t,n),...Rf(e,t,n),...If(e,t,n)]}function Cf(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=pe(s).map(m=>vf(m.trim())).filter(m=>!!m),l=an(n,o.index),u=an(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:we(e,t,a),names:c,startLine:l,endLine:u})}return r}function Rf(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[2]??"",a=an(n,o.index),c=an(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:we(e,t,s),names:[],startLine:a,endLine:c})}return r}function If(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=an(n,o.index),c=an(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:we(e,t,s),names:[],startLine:a,endLine:c})}return r}function vf(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 r=t.match(/^(\w+)$/);return r?r[1]??null:null}function an(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Df(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Nf(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=Lf(i,o,s,a);r.push(c)}return r}function Nf(e,t,n){let r=ge(n,"string");if(!r)return;let i=ge(r,"string_fragment");if(i)return we(e,t,i.text)}function Lf(e,t,n,r){let i=ge(e,"export_clause");if(i){let s=[];for(let a of i.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:r}}return ge(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function qa(e,t,n){return Lr(e,t,{java:r=>_f(e,t,r),kotlin:r=>wf(e,t,r),scala:r=>Ef(e,t,r)},()=>xe(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?kf(e,t,o,i):[]}))}function _f(e,t,n){let r=z(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(m=>m.type==="asterisk"),c=o.namedChildren.find(m=>m.type==="scoped_identifier")??o.namedChildren.find(m=>m.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(Nt("*",J(e,l,fe)));continue}let u=l.split(".").pop()??l;i.push(U(u,u,J(e,l,fe),r))}return i}function wf(e,t,n){let r=z(n,new Set(["import_header","import_list"])),i=[];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){i.push(Nt("*",J(e,s.text,fe)));continue}let l=s.text,u=l.split(".").pop()??l,d=c?.namedChild(0)?.text??u;i.push(U(u,d,J(e,l,fe),r))}return i}function Ef(e,t,n){let r=z(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(m=>m.type==="namespace_selectors"||m.type==="namespace_wildcard"),a=o.namedChildren.filter(m=>m!==s&&(m.type==="identifier"||m.type==="stable_identifier")),c=a.map(m=>m.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(Nt("*",J(e,c,fe)));continue}if(s?.type==="namespace_selectors"){for(let m of s.namedChildren)if(m.type==="arrow_renamed_identifier"){let[d,p]=m.namedChildren;if(!d)continue;let h=d.text,f=p?.text??h;if(h==="_")continue;i.push(U(h,f,J(e,`${c}.${h}`,fe),r))}else if(m.type==="identifier"){let d=m.text;i.push(U(d,d,J(e,`${c}.${d}`,fe),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(m=>m.text).join(".")||c;i.push(U(l,l,J(e,u&&a.length>1?`${u}.${l}`:c,fe),r))}return i}function kf(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return pe(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 m=(l??u.split(".").pop()??u).trim(),d=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[$e(e,t,r,d,u,m)]})}return[$e(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Wa(e,t,n){return Ce(e,t,r=>Pf(e,t,r),()=>xe(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?pe(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,m=u.split("\\").pop()??u,d=(l??m).trim();return[$e(e,t,i,u,m,d,J(e,u.replace(/\\/g,"."),It))]}):[]}))}function Pf(e,t,n){let r=z(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(U(a,c,J(e,s.replace(/\\/g,"."),It),r))};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:m,qualified:d}=Va(l,c);u&&o(d,u,m)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:m}=Va(c,"");l&&o(m,l,u)}}return i}function Va(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),r=e.namedChildren.filter(l=>l.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,c=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:c}}function Ga(e,t,n){return Ce(e,t,r=>Ff(e,t,r),()=>Tf(n).flatMap(r=>Of(e,t,r,n)))}function Ff(e,t,n){let r=z(n,new Set(["import_statement","import_from_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Ua(s);if(!a)continue;let c=rn(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=Af(s);if(a===null)continue;let c=rn(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let m=Ua(u);m&&i.push({importedName:m.qualifiedName,localName:m.localName,sourcePath:c,kind:"named",used:r.has(m.localName),usedMembers:[]})}}return i}function Ua(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 Af(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ge(e,"import_prefix")?.text??"",n=ge(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Tf(e){let t=e.split(`
72
72
  `),n=[],r=0;for(let i=0;i<t.length;i++){let o=t[i],s=o.trimStart(),a=r;if(r+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=Ln(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let d=t[i];c+=`
73
- ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,end:l})}return n}function Tf(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 r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function Af(e,t,n,r){let i=lt(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return pe(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,m]=l.split(/\s+as\s+/),d=u.trim(),p=(m??d.split(".")[0]??d).trim(),h=rn(e,t,d),f=on(i,p);return[{importedName:d,localName:p,sourcePath:h,kind:"namespace",used:de(i,p)||f.length>0,usedMembers:f}]});let s=n.module?rn(e,t,n.module):null,a=[];for(let c of pe(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,m]=l.split(/\s+as\s+/),d=(m??u).trim();a.push({importedName:u.trim(),localName:d,sourcePath:s,kind:"named",used:de(i,d),usedMembers:[]})}return a}import{basename as Mf}from"path";function Ja(e,t,n){return Ce(e,t,r=>$f(e,t,r),()=>Of(e,t,n))}function Of(e,t,n){return xe(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(r,i)=>{let o=r[1],s=r[2];if(!o||!s)return[];let a=o==="require_relative"?Ir(e,t,s):null;if(a){let c=za(s);return[sn(c,c,a,de(i,c))]}return[vt(s,a)]})}function $f(e,t,n){let r=z(n,new Set([])),i=[],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 m=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!m)continue;let d=a.text==="require_relative"?Ir(e,t,m):null;if(d){let p=za(m);i.push(U(p,p,d,r))}else i.push(vt(m,d))}return i}function za(e){return Mf(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Qa(e,t,n){return Ce(e,t,r=>jf(e,t,r),()=>xe(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?Bf(e,t,o,i):[]}))}function jf(e,t,n){let r=z(n,new Set(["use_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of _n(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Ue(e,t,a.qualifiedName)??Ue(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(U(a.importedName,a.localName,c,r))}}return i}function _n(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:_r(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:_r(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=_r(t,n.text),o=[];for(let s of r.namedChildren)o.push(..._n(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(..._n(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=_n(n,t),o=r.text;return i.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:_r(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function _r(e,t){return e?t?`${e}::${t}`:e:t}function Bf(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),m=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return pe(m).flatMap(d=>{let p=d.trim();if(!p||p==="self")return[];let[h,f]=p.split(/\s+as\s+/),y=h?.trim();if(!y)return[];let C=(f??y.split("::").pop()??y).trim(),E=`${u}::${y}`.replace(/::::/g,"::");return[Oe(e,t,r,E,y.split("::").pop()??y,C,Ue(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Ue(e,t,a)??Ue(e,t,a.split("::").slice(0,-1).join("::"));return[Oe(e,t,r,a,a.split("::").pop()??a,c,l)]}function Ka(e,t,n){let r=ce(e,t);if(r)return Hf(e,t,r);let i=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&i.push(...Vf(e,t,s))}return i}function Hf(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!qf(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of _n(o,""))s.importedName&&r.push(Ui(e,t,s.qualifiedName))}return r}function qf(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function Vf(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),o=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return pe(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${i}::${c?.trim()??a}`.replace(/::::/g,"::");return[Ui(e,t,l)]})}return[Ui(e,t,r)]}function Ui(e,t,n){return{specifier:n,sourcePath:Ue(e,t,n)??Ue(e,t,n.split("::").slice(0,-1).join("::"))}}function Nt({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function Ya(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var Wf={language:"javascript",extensions:Ct,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Vi,parseReExports:Wi},Uf=Nt({language:"python",extensions:br,imports:"ast-with-regex-fallback",parseImports:Ga}),Gf=Nt({language:"jvm",extensions:fe,imports:"ast-dispatch-with-regex-fallback",parseImports:qa}),Jf={language:"rust",extensions:Sr,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Qa,parseExports:Ka},zf=Nt({language:"ruby",extensions:xr,imports:"ast-with-regex-fallback",parseImports:Ja}),Qf=Nt({language:"c/cpp",extensions:Cr,imports:"ast-with-regex-fallback",parseImports:Ma}),Kf=Nt({language:"dotnet",extensions:st,imports:"ast-dispatch-with-regex-fallback",parseImports:ja}),Yf={language:"dart",extensions:Rr,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Oa,parseExports:$a},Xf=Nt({language:"php",extensions:Rt,imports:"ast-with-regex-fallback",parseImports:Wa}),Zf=[Wf,Uf,Gf,Jf,zf,Qf,Kf,Yf,Xf];function wr(e){return Ya(Zf,e)}var Gi={clearGroups:["whole-project","source-file"]},eg=W("source-imports",Gi),tg=W("source-exports",Gi),ng=W("source-reexports",Gi);function Xa(e,t){let n=_e(t);return ng.get(e,n,()=>{let r=wr(n);if(!r?.parseReExports)return[];let i=A(e,n);return i?r.parseReExports(e,n,i):[]})}function te(e,t){let n=_e(t);return eg.get(e,n,()=>{let r=wr(n);if(!r)return[];let i=A(e,n);return i?r.parseImports(e,n,i):[]})}function Ji(e,t){let n=_e(t);return tg.get(e,n,()=>{let r=wr(n);if(!r?.parseExports)return[];let i=A(e,n);return i?r.parseExports(e,n,i):[]})}var rg=W("file-dep-graph",{clearGroups:["whole-project"]});function oe(e,t){return rg.get(e,t??"",()=>{let n=new Map,r=new Set(T(e,{includeIgnored:!1})),i=(o,s)=>og(e,n,r,o,s);for(let o of ig(e,t))i(o.from_file,o.to_file);for(let o of r)if(!(t&&!o.includes(t)))for(let s of te(e,o))s.sourcePath&&i(o,s.sourcePath);return n})}function ig(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
73
+ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Mf(c);m&&n.push({...m,start:a,end:l})}return n}function Mf(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 r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function Of(e,t,n,r){let i=ut(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return pe(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,m]=l.split(/\s+as\s+/),d=u.trim(),p=(m??d.split(".")[0]??d).trim(),h=rn(e,t,d),f=on(i,p);return[{importedName:d,localName:p,sourcePath:h,kind:"namespace",used:de(i,p)||f.length>0,usedMembers:f}]});let s=n.module?rn(e,t,n.module):null,a=[];for(let c of pe(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,m]=l.split(/\s+as\s+/),d=(m??u).trim();a.push({importedName:u.trim(),localName:d,sourcePath:s,kind:"named",used:de(i,d),usedMembers:[]})}return a}import{basename as $f}from"path";function Ja(e,t,n){return Ce(e,t,r=>Bf(e,t,r),()=>jf(e,t,n))}function jf(e,t,n){return xe(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(r,i)=>{let o=r[1],s=r[2];if(!o||!s)return[];let a=o==="require_relative"?Ir(e,t,s):null;if(a){let c=za(s);return[sn(c,c,a,de(i,c))]}return[Dt(s,a)]})}function Bf(e,t,n){let r=z(n,new Set([])),i=[],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 m=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!m)continue;let d=a.text==="require_relative"?Ir(e,t,m):null;if(d){let p=za(m);i.push(U(p,p,d,r))}else i.push(Dt(m,d))}return i}function za(e){return $f(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Qa(e,t,n){return Ce(e,t,r=>Hf(e,t,r),()=>xe(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?qf(e,t,o,i):[]}))}function Hf(e,t,n){let r=z(n,new Set(["use_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of _n(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Ge(e,t,a.qualifiedName)??Ge(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(U(a.importedName,a.localName,c,r))}}return i}function _n(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:_r(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:_r(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=_r(t,n.text),o=[];for(let s of r.namedChildren)o.push(..._n(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(..._n(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=_n(n,t),o=r.text;return i.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:_r(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function _r(e,t){return e?t?`${e}::${t}`:e:t}function qf(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),m=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return pe(m).flatMap(d=>{let p=d.trim();if(!p||p==="self")return[];let[h,f]=p.split(/\s+as\s+/),y=h?.trim();if(!y)return[];let C=(f??y.split("::").pop()??y).trim(),E=`${u}::${y}`.replace(/::::/g,"::");return[$e(e,t,r,E,y.split("::").pop()??y,C,Ge(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Ge(e,t,a)??Ge(e,t,a.split("::").slice(0,-1).join("::"));return[$e(e,t,r,a,a.split("::").pop()??a,c,l)]}function Ka(e,t,n){let r=ce(e,t);if(r)return Vf(e,t,r);let i=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&i.push(...Uf(e,t,s))}return i}function Vf(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!Wf(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of _n(o,""))s.importedName&&r.push(Ui(e,t,s.qualifiedName))}return r}function Wf(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function Uf(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),o=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return pe(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${i}::${c?.trim()??a}`.replace(/::::/g,"::");return[Ui(e,t,l)]})}return[Ui(e,t,r)]}function Ui(e,t,n){return{specifier:n,sourcePath:Ge(e,t,n)??Ge(e,t,n.split("::").slice(0,-1).join("::"))}}function Lt({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function Ya(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var Gf={language:"javascript",extensions:Rt,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Vi,parseReExports:Wi},Jf=Lt({language:"python",extensions:br,imports:"ast-with-regex-fallback",parseImports:Ga}),zf=Lt({language:"jvm",extensions:fe,imports:"ast-dispatch-with-regex-fallback",parseImports:qa}),Qf={language:"rust",extensions:Sr,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Qa,parseExports:Ka},Kf=Lt({language:"ruby",extensions:xr,imports:"ast-with-regex-fallback",parseImports:Ja}),Yf=Lt({language:"c/cpp",extensions:Cr,imports:"ast-with-regex-fallback",parseImports:Ma}),Xf=Lt({language:"dotnet",extensions:at,imports:"ast-dispatch-with-regex-fallback",parseImports:ja}),Zf={language:"dart",extensions:Rr,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Oa,parseExports:$a},eg=Lt({language:"php",extensions:It,imports:"ast-with-regex-fallback",parseImports:Wa}),tg=[Gf,Jf,zf,Qf,Kf,Yf,Xf,Zf,eg];function wr(e){return Ya(tg,e)}var Gi={clearGroups:["whole-project","source-file"]},ng=W("source-imports",Gi),rg=W("source-exports",Gi),ig=W("source-reexports",Gi);function Xa(e,t){let n=_e(t);return ig.get(e,n,()=>{let r=wr(n);if(!r?.parseReExports)return[];let i=T(e,n);return i?r.parseReExports(e,n,i):[]})}function te(e,t){let n=_e(t);return ng.get(e,n,()=>{let r=wr(n);if(!r)return[];let i=T(e,n);return i?r.parseImports(e,n,i):[]})}function Ji(e,t){let n=_e(t);return rg.get(e,n,()=>{let r=wr(n);if(!r?.parseExports)return[];let i=T(e,n);return i?r.parseExports(e,n,i):[]})}var og=W("file-dep-graph",{clearGroups:["whole-project"]});function oe(e,t){return og.get(e,t??"",()=>{let n=new Map,r=new Set(A(e,{includeIgnored:!1})),i=(o,s)=>ag(e,n,r,o,s);for(let o of sg(e,t))i(o.from_file,o.to_file);for(let o of r)if(!(t&&!o.includes(t)))for(let s of te(e,o))s.sourcePath&&i(o,s.sourcePath);return n})}function sg(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
74
74
  d1.relative_path AS from_file,
75
75
  d2.relative_path AS to_file
76
76
  FROM mentions m
@@ -88,11 +88,11 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
88
88
  WHERE d1.id != d2.id
89
89
  AND m.role != 1
90
90
  ${e.pathExclusionsFor("d1","d2")}
91
- ${n}`)}function og(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}import{readdirSync as sg}from"fs";import{extname as Za,join as ag}from"path";var cg=[".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"],ec=[".vue"],tc=new Set(cg.map(e=>e.toLowerCase())),lg=[...tc].sort().join(","),zi=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function $e(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):tc,s=i?[...o].sort().join(","):lg,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return ug.get(e,a,()=>{let c=new Set;if(n)for(let l of T(e,{includeIgnored:!1}))o.has(Za(l).toLowerCase())&&c.add(l);if(r)for(let l of mg(e.config.projectRoot,o))e.isIgnored(l)||c.add(l);return[...c].sort()})}var ug=W("source-files",{clearGroups:[]});function mg(e,t){let n=new Set,r=i=>{let o=i?ag(e,i):e,s;try{s=sg(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!zi.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(Za(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}import{readFileSync as dg}from"fs";import{join as pg}from"path";var fg={files:new Set,pathPrefixes:[]},Qi=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,gg=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,hg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],yg=re("package-surface",{clearGroups:["whole-project"]});function bg(e){return yg.get(e,()=>Sg(e.config.projectRoot))}function rc(e,t){let n=bg(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function Sg(e){let t=xg(e);if(!t)return fg;let n=new Set,r=[];for(let i of Cg(t))Rg(i,n,r);return{files:n,pathPrefixes:r}}function xg(e){try{let t=dg(pg(e,"package.json"),"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Cg(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return ic(e.exports,t),t}function ic(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))ic(n,t)}function Rg(e,t,n){let r=e.replace(/\\/g,"/").replace(/^\.\//,"");if(r===""||r.startsWith(".."))return;let i=r.indexOf("*");if(i>=0){let s=r.slice(0,i);for(let a of nc(s))a!==""&&n.push(a);return}let o=r.replace(gg,"");for(let s of nc(o)){s===o&&s===r&&t.add(r);for(let a of hg)t.add(s+a)}t.add(r)}function nc(e){let t=[e];return Qi.test(e)&&(t.push(e.replace(Qi,"src/")),t.push(e.replace(Qi,""))),t}function G(e){let t=cn(e);return Dg(t)?"test":Ng(t)?"worker":Lg(t)?"entry":_g(t)?"barrel":"source"}function Er(e){return G(e)==="barrel"}function sc(e){return Ig.get(e,()=>{let t=oe(e),n=$e(e).filter(o=>{let s=G(o);return s==="entry"||s==="worker"}),r=new Set,i=new Set;for(;n.length>0;){let o=n.shift();if(!r.has(o)){r.add(o),G(o)==="barrel"&&i.add(o);for(let s of t.get(o)??[])r.has(s)||n.push(s)}}return i})}var Ig=re("live-barrels",{clearGroups:["whole-project"]});function Ki(e,t){return sc(e).has(cn(t))}function ac(e){let t=sc(e);return $e(e).filter(n=>Er(n)&&!t.has(n)&&!vg(e,n))}function vg(e,t){let n=cn(t),r=K(e,n)?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
91
+ ${n}`)}function ag(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}import{readdirSync as cg}from"fs";import{extname as Za,join as lg}from"path";var ug=[".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"],ec=[".vue"],tc=new Set(ug.map(e=>e.toLowerCase())),mg=[...tc].sort().join(","),zi=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function je(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):tc,s=i?[...o].sort().join(","):mg,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return dg.get(e,a,()=>{let c=new Set;if(n)for(let l of A(e,{includeIgnored:!1}))o.has(Za(l).toLowerCase())&&c.add(l);if(r)for(let l of pg(e.config.projectRoot,o))e.isIgnored(l)||c.add(l);return[...c].sort()})}var dg=W("source-files",{clearGroups:[]});function pg(e,t){let n=new Set,r=i=>{let o=i?lg(e,i):e,s;try{s=cg(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!zi.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(Za(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}import{readFileSync as fg}from"fs";import{join as gg}from"path";var hg={files:new Set,pathPrefixes:[]},Qi=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,yg=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,bg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Sg=re("package-surface",{clearGroups:["whole-project"]});function xg(e){return Sg.get(e,()=>Cg(e.config.projectRoot))}function rc(e,t){let n=xg(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function Cg(e){let t=Rg(e);if(!t)return hg;let n=new Set,r=[];for(let i of Ig(t))vg(i,n,r);return{files:n,pathPrefixes:r}}function Rg(e){try{let t=fg(gg(e,"package.json"),"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ig(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return ic(e.exports,t),t}function ic(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))ic(n,t)}function vg(e,t,n){let r=e.replace(/\\/g,"/").replace(/^\.\//,"");if(r===""||r.startsWith(".."))return;let i=r.indexOf("*");if(i>=0){let s=r.slice(0,i);for(let a of nc(s))a!==""&&n.push(a);return}let o=r.replace(yg,"");for(let s of nc(o)){s===o&&s===r&&t.add(r);for(let a of bg)t.add(s+a)}t.add(r)}function nc(e){let t=[e];return Qi.test(e)&&(t.push(e.replace(Qi,"src/")),t.push(e.replace(Qi,""))),t}function G(e){let t=cn(e);return Lg(t)?"test":_g(t)?"worker":wg(t)?"entry":Eg(t)?"barrel":"source"}function Er(e){return G(e)==="barrel"}function sc(e){return Dg.get(e,()=>{let t=oe(e),n=je(e).filter(o=>{let s=G(o);return s==="entry"||s==="worker"}),r=new Set,i=new Set;for(;n.length>0;){let o=n.shift();if(!r.has(o)){r.add(o),G(o)==="barrel"&&i.add(o);for(let s of t.get(o)??[])r.has(s)||n.push(s)}}return i})}var Dg=re("live-barrels",{clearGroups:["whole-project"]});function Ki(e,t){return sc(e).has(cn(t))}function ac(e){let t=sc(e);return je(e).filter(n=>Er(n)&&!t.has(n)&&!Ng(e,n))}function Ng(e,t){let n=cn(t),r=K(e,n)?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
92
92
  FROM defn_enclosing_ranges der
93
93
  JOIN documents d ON d.id = der.document_id
94
94
  WHERE d.relative_path = ?
95
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function le(e,t){let n=G(t);return n==="entry"||n==="worker"||Ki(e,t)}function ne(e,t,n){let r=cn(n);if(rc(e,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>cn(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(cn(o)))||i.qualifiedVars?.some(o=>wg(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}function Dg(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 Ng(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function Lg(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 _g(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 cn(e){return e.replace(/\\/g,"/")}function wg(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(oc(r)+"/")&&e.includes(oc(i)+".")}function oc(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function kr(e,t,n,r={}){if(!n)return[];let i=A(e,t);return i?i.indexOf(n)===-1?[]:(Ge(e,t).get(n)??[]).filter(s=>!Eg(s,r)):[]}function Eg(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var kg=W("file-identifiers",{clearGroups:["whole-project","source-file"]});function cc(e,t){let n=K(e,t);return n?n.fileIdentifiers:kg.get(e,t,()=>new Set(Ge(e,t).keys()))}var Pg=W("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Ge(e,t){let n=K(e,t);return n?n.identifierLineMap:Pg.get(e,t,()=>Tg(e,t))}var Fg=W("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function lc(e,t){let n=K(e,t);return n?n.identifiersByLine:Fg.get(e,t,()=>{let r=Ge(e,t),i=0;for(let s of r.values()){let a=s[s.length-1];a!==void 0&&a>i&&(i=a)}let o=new Array(i+1);for(let s=0;s<=i;s+=1)o[s]=new Set;for(let[s,a]of r)for(let c of a)o[c].add(s);return o})}function Tg(e,t){let n=new Map,r=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},i=A(e,t);if(!i)return n;let o=It(i).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]&&r(l[1],a)}return n}function uc(e,t){return Yi(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
95
+ AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function le(e,t){let n=G(t);return n==="entry"||n==="worker"||Ki(e,t)}function ne(e,t,n){let r=cn(n);if(rc(e,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>cn(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(cn(o)))||i.qualifiedVars?.some(o=>kg(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}function Lg(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 _g(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function wg(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 Eg(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 cn(e){return e.replace(/\\/g,"/")}function kg(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(oc(r)+"/")&&e.includes(oc(i)+".")}function oc(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function kr(e,t,n,r={}){if(!n)return[];let i=T(e,t);return i?i.indexOf(n)===-1?[]:(Je(e,t).get(n)??[]).filter(s=>!Pg(s,r)):[]}function Pg(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var Fg=W("file-identifiers",{clearGroups:["whole-project","source-file"]});function cc(e,t){let n=K(e,t);return n?n.fileIdentifiers:Fg.get(e,t,()=>new Set(Je(e,t).keys()))}var Ag=W("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Je(e,t){let n=K(e,t);return n?n.identifierLineMap:Ag.get(e,t,()=>Mg(e,t))}var Tg=W("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function lc(e,t){let n=K(e,t);return n?n.identifiersByLine:Tg.get(e,t,()=>{let r=Je(e,t),i=0;for(let s of r.values()){let a=s[s.length-1];a!==void 0&&a>i&&(i=a)}let o=new Array(i+1);for(let s=0;s<=i;s+=1)o[s]=new Set;for(let[s,a]of r)for(let c of a)o[c].add(s);return o})}function Mg(e,t){let n=new Map,r=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},i=T(e,t);if(!i)return n;let o=vt(i).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]&&r(l[1],a)}return n}function uc(e,t){return Yi(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
96
96
  m.symbol_id,
97
97
  d.relative_path,
98
98
  COUNT(*) AS ref_count
@@ -116,7 +116,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
116
116
  WHERE m.role != 1
117
117
  ${r}
118
118
  ${e.pathExclusionsFor("d")}
119
- ORDER BY d.relative_path, c.start_line`,...n??[])})}function Yi(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function dc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function ut(e,t){return dc(e)===dc(t)}function Fr(e,t){let n=pc(e);return n?t.filter(r=>pc(r.file)===n):t}function Tr(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(te(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(ut(a,s.file))return s;return null}return n.length===1?n[0]:null}function pc(e){let t=$(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Ag=re("global-leaf-index",{clearGroups:["whole-project"]});function Lt(e){return Ag.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
119
+ ORDER BY d.relative_path, c.start_line`,...n??[])})}function Yi(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function dc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function mt(e,t){return dc(e)===dc(t)}function Fr(e,t){let n=pc(e);return n?t.filter(r=>pc(r.file)===n):t}function Ar(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(te(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(mt(a,s.file))return s;return null}return n.length===1?n[0]:null}function pc(e){let t=$(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Og=re("global-leaf-index",{clearGroups:["whole-project"]});function _t(e){return Og.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
120
120
  COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
121
121
  FROM global_symbols gs
122
122
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -130,8 +130,8 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
130
130
  GROUP BY m.symbol_id
131
131
  ) mention_doc ON mention_doc.symbol_id = gs.id
132
132
  WHERE 1 = 1
133
- ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=P(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}function Ee(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import fc from"path";function Mg(e,t){return e.getReferences().map(n=>{let r=n.getNode();return yc(r,t)})}function Og(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function gc(e,t,n,r){let i=[];for(let o of Og(e))for(let s of Mg(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Ar(i)}function hc(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();wn(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:yc(a,r),node:a}))}return i}function yc(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:wn(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function bc(e,t,n){let r=e.getSourceFile(),i=ln(r,e),o=e.getText(),s=new RegExp(`\\b${$g(o)}\\b`,"g"),a=r.getFullText().split(`
134
- `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let m;for(;(m=s.exec(u))!==null;)c.push({file:t,line:l,column:m.index})}return Ar(c.filter(l=>wn(n,fc.join(n,l.file))===t))}function Xi(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 ln(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Ar(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function wn(e,t){let n=fc.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function $g(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sc(e,t,n,r){let i=jg(t,r);return i.size===0?new Map:Bg(e,n,i)}function jg(e,t){let n=new Map;for(let r of H(e,t)){let i=P(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function Bg(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of Hg(e,o)){let a=n.get(s);if(!a)continue;let c=ln(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),m=i.get(l.symbolId);m!==void 0&&m<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function Hg(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}function xc(e,t,n,r){return e.all(`SELECT
133
+ ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=P(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}function Ee(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import fc from"path";function $g(e,t){return e.getReferences().map(n=>{let r=n.getNode();return yc(r,t)})}function jg(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function gc(e,t,n,r){let i=[];for(let o of jg(e))for(let s of $g(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Tr(i)}function hc(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();wn(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:yc(a,r),node:a}))}return i}function yc(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:wn(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function bc(e,t,n){let r=e.getSourceFile(),i=ln(r,e),o=e.getText(),s=new RegExp(`\\b${Bg(o)}\\b`,"g"),a=r.getFullText().split(`
134
+ `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let m;for(;(m=s.exec(u))!==null;)c.push({file:t,line:l,column:m.index})}return Tr(c.filter(l=>wn(n,fc.join(n,l.file))===t))}function Xi(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 ln(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Tr(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function wn(e,t){let n=fc.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Bg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sc(e,t,n,r){let i=Hg(t,r);return i.size===0?new Map:qg(e,n,i)}function Hg(e,t){let n=new Map;for(let r of H(e,t)){let i=P(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function qg(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of Vg(e,o)){let a=n.get(s);if(!a)continue;let c=ln(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),m=i.get(l.symbolId);m!==void 0&&m<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function Vg(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}function xc(e,t,n,r){return e.all(`SELECT
135
135
  gs.id AS symbolId,
136
136
  gs.symbol,
137
137
  d.relative_path AS relativePath,
@@ -191,7 +191,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
191
191
  WHERE d.relative_path = ?
192
192
  AND m.role = 1
193
193
  GROUP BY gs.id, gs.symbol, d.id, d.relative_path, gs.display_name, gs.kind, gs.documentation, gs.enclosing_symbol
194
- ORDER BY startLine, endLine`,t,t),r=new Set,i=new Map;for(let o of n){if(r.has(o.symbolId))continue;r.add(o.symbolId);let s=o.leaf||P(o.symbol);!s||i.has(s)||i.set(s,{...o,leaf:s})}return i}import qg from"path";var En=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Mr(e){let t=e.toLowerCase();return En.some(n=>t.endsWith(n))}function Rc(e,t){let n=new Map,r=i=>Mr(i)?Ee(n,i,()=>{let o=qg.join(e.config.projectRoot,i);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:i=>r(i)?.sourceFile??null,sourceFileMatch:r,indexedTypeScriptLikeDocuments:()=>T(e,{extensions:En})}}import mt from"path";import{existsSync as Or,readdirSync as Vg,readFileSync as Ic}from"fs";function vc(e){let t=mt.join(e,"package.json");if(!Or(t))return[];let n;try{n=JSON.parse(Ic(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Wg(e,i)).flatMap(i=>Ug(e,i))}function Wg(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=mt.join(e,t);return Or(mt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=mt.join(e,r||".");if(!Or(o))return[];try{return Vg(o).map(s=>mt.join(o,s,i)).filter(s=>Or(mt.join(s,"package.json")))}catch{return[]}}function Ug(e,t){try{let n=JSON.parse(Ic(mt.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=mt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function Dc(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Nc(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as kn,readFileSync as Gg,readdirSync as Jg,statSync as zg}from"fs";import Q from"path";var eo=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function to(e,t){let r=t?Q.dirname(Q.join(e,t)):e,i=Q.resolve(e);for(;r.startsWith(i);){for(let s of eo){let a=Q.join(r,s);if(kn(a))return a}let o=Q.dirname(r);if(o===r)break;r=o}for(let o of eo){let s=Q.join(e,o);if(kn(s))return s}return null}function Lc(e){let t=e.config.projectRoot,n=new Set(no(t,e.config.semantic?.typescript?.tsconfigs)),r=T(e,{includeIgnored:!1,extensions:En});for(let i of r){let o=to(t,i);o&&n.add(Q.resolve(o))}if(n.size===0){let i=to(t);i&&n.add(Q.resolve(i))}return[...n].filter(i=>!_c(t,i)).sort((i,o)=>i.localeCompare(o))}function no(e,t=[]){let n=new Set;for(let r of t){let i=Q.isAbsolute(r)?r:Q.join(e,r);kn(i)&&n.add(Q.resolve(i))}for(let r of Qg(e))for(let i of eo){let o=Q.join(r,i);kn(o)&&n.add(Q.resolve(o))}if(n.size===0){let r=to(e);r&&n.add(Q.resolve(r))}return[...n].filter(r=>!_c(e,r)).sort((r,i)=>r.localeCompare(i))}function Qg(e){let t=Q.join(e,"package.json");if(!kn(t))return[];let n;try{n=JSON.parse(Gg(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Kg(e,i))}function Kg(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Q.join(e,t);return Zi(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Q.join(e,r||".");return Zi(o)?Jg(o).map(s=>Q.join(o,s,i)).filter(Zi):[]}function Zi(e){try{return zg(e).isDirectory()}catch{return!1}}function _c(e,t){let n=Q.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 Yg}from"module";var Xg=Yg(import.meta.url),Pn;function wc(){if(Pn!==void 0)return Pn;try{Pn=Xg("ts-morph")}catch{Pn=null}return Pn}function Ec(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function $r(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Fc(e,t){let n=wc();if(!n)return $r("ts-morph is not installed");let r=Lc(e);if(r.length===0)return $r("no tsconfig found");try{let i=Ec(n,r);return new ro(e,n,i)}catch(i){return $r(i instanceof Error?i.message:String(i),r[0],r)}}var ro=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=vc(t.config.projectRoot),this.sourceFiles=Rc(t,r)}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 Ee(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,i))r.push(o);return r})}referencesFor(t){return Ee(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?gc(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return Ee(this.calleesCache,t.symbolId,()=>Ee(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Ee(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 r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Pc(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Pc(o)}`})}importUsageForDeclaration(t,n){let r=we(this.db,t,n.getModuleSpecifierValue()),i=kc(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>Zg(t,r,o)):i.map(o=>this.valueImportUsageForEntry(t,r,o))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let l of i)for(let u of hc(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!Xi(l.node)),a=o.some(l=>Xi(l.node)),c=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.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 r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Ar(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=Dc(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of kc(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=bc(a.identifier,r,this.db.config.projectRoot);l.length>0&&nh(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of Nc(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?we(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,r,i);continue}for(let u of l){let m=u.getNameNode().getText(),d=u.getAliasNode()?.getText()??m,p=this.indexedDefinitionByLeaf(c,m);if(!p)continue;let h=r.get(d);h||(h=new Set,r.set(d,h)),h.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Ee(this.indexedDefinitionLeafCache,t,()=>Cc(this.db,t)).get(n)??null}nodeForDefinition(t){return Ee(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Ee(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Sc(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=wn(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=ln(i,r),a=xc(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 r=H(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,r,o);s&&eh(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,rh(s));return i}semanticCalleeForCallNode(t,n,r){let i=th(n,ln(t,r));if(!i)return null;let o=r.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function kc(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function Zg(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 eh(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function th(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function nh(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function rh(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function Pc(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var io=new WeakMap;rt({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>io.delete(e)});function Fn(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=io.get(e);r||(r=new Map,io.set(e,r));let i=r.get(n);if(i)return i;let o=Fc(e,t);return r.set(n,o),o}function Tn(e,t){let n=Br(e,t);return n?n.importUsage(t):[]}function _t(e,t){let n=Br(e,t.relativePath);return n?n.referencesFor(t):[]}function un(e,t){let n=new Map;for(let r of t)for(let i of _t(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let o=n.get(r.symbolId);o||(o=new Set,n.set(r.symbolId,o)),o.add(i.file)}return n}function jr(e,t){let n=new Map;for(let r of t){let i=Br(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function Tc(e,t){let n=Br(e,t.relativePath);return n?n.signatureFor(t):null}function Br(e,t){if(!Mr(t))return null;let n=Fn(e,t);return n.availability().available?n:null}function Hr(e,t){let n=new Map;for(let r of te(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Ac(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Ac(n,o,r.sourcePath)}return n}function Ac(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function mn(e,t,n){let r=Lt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[An(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(An);let o=Hr(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>ut(c,u.file));if(l.length>0)return l.map(An)}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=r.filter(u=>ut(c,u.file));if(l.length>0&&l.length===r.length)return l.map(An)}return[]}function Oc(e,t,n){let r=mn(e,t,n);if(r.length>0)return r;let i=Lt(e).get(n);return!i||i.length===0?[]:i.map(An)}function $c(e,t,n={}){let r=hr(e,t);if(!r)return[];let i=P(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=_t(e,{...r,leaf:i,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 Mc(e,a)}}let o=new Map;for(let s of $e(e)){let a=A(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!mn(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=kr(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Mc(e,o)}function jc(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 r=new Set(t.map(o=>o.symbolId)),i=new Map;for(let o of $e(e)){let s=cc(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of mn(e,o,a)){if(!r.has(c.symbolId)||o===c.relativePath)continue;let l=i.get(c.symbolId);l||(l=new Set,i.set(c.symbolId,l)),l.add(o)}}}return i}function An(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Mc(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=H(e,i);for(let a of o){let c=be(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function wt(e,t){let n=lh(e,t);return n?uh(e,oh(e,n.match,n.identifier)):[]}function dt(e,t,n={}){return ih(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function ih(e,t,n={}){let r=$c(e,t,{semantic:n.semantic}),i=r.length>0?Bc(r,"source-attribution"):Bc(wt(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Bc(e,t){return e.map(n=>({...n,provenance:t}))}function oh(e,t,n){let r=new Map;for(let[i,o]of sh(e,t.symbolId))r.set(i,ah(e,i,o,t,n));return r}function sh(e,t){let n=new Map;for(let r of Pr(e,[t])){if(e.isIgnored(r.relative_path))continue;let i=n.get(r.relative_path);i||(i=[],n.set(r.relative_path,i)),i.push({start_line:r.chunk_start,end_line:r.chunk_end})}return n}function ah(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?kr(e,t,i,o):[];return n.flatMap(a=>ch(s,a))}function ch(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function lh(e,t){let n=hr(e,t);return n?{match:n,identifier:P(n.symbol)||null}:null}function uh(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=H(e,i);for(let a of o){let c=be(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function he(e,t,n={}){let r=qr(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>ie(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Hc(e,t,n={}){let r=ph(e)?gh(e,t,{semantic:n.semantic!==!1}):fh(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var mh=re("caller-rows",{clearGroups:["whole-project"]}),dh=2e4;function ph(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>dh}function fh(e){return mh.get(e,()=>{let t=Me(e),n=qr(e,t),r=new Map;for(let s of t)r.set(s.symbol,s.symbolId);let i=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=r.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=i.get(l);u||(u=[],i.set(l,u),o.set(l,new Set));let m=`${s.symbol}|${s.relativePath}`;o.get(l).has(m)||(o.get(l).add(m),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function gh(e,t,n){let r=[],i=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;i.has(c)||(i.add(c),r.push(a))};for(let a of wt(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?hh(e,t):null;if(s)for(let a of _t(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=be(H(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function hh(e,t){return e.get(`SELECT
194
+ ORDER BY startLine, endLine`,t,t),r=new Set,i=new Map;for(let o of n){if(r.has(o.symbolId))continue;r.add(o.symbolId);let s=o.leaf||P(o.symbol);!s||i.has(s)||i.set(s,{...o,leaf:s})}return i}import Wg from"path";var En=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Mr(e){let t=e.toLowerCase();return En.some(n=>t.endsWith(n))}function Rc(e,t){let n=new Map,r=i=>Mr(i)?Ee(n,i,()=>{let o=Wg.join(e.config.projectRoot,i);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:i=>r(i)?.sourceFile??null,sourceFileMatch:r,indexedTypeScriptLikeDocuments:()=>A(e,{extensions:En})}}import dt from"path";import{existsSync as Or,readdirSync as Ug,readFileSync as Ic}from"fs";function vc(e){let t=dt.join(e,"package.json");if(!Or(t))return[];let n;try{n=JSON.parse(Ic(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Gg(e,i)).flatMap(i=>Jg(e,i))}function Gg(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=dt.join(e,t);return Or(dt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=dt.join(e,r||".");if(!Or(o))return[];try{return Ug(o).map(s=>dt.join(o,s,i)).filter(s=>Or(dt.join(s,"package.json")))}catch{return[]}}function Jg(e,t){try{let n=JSON.parse(Ic(dt.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=dt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function Dc(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Nc(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as kn,readFileSync as zg,readdirSync as Qg,statSync as Kg}from"fs";import Q from"path";var eo=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function to(e,t){let r=t?Q.dirname(Q.join(e,t)):e,i=Q.resolve(e);for(;r.startsWith(i);){for(let s of eo){let a=Q.join(r,s);if(kn(a))return a}let o=Q.dirname(r);if(o===r)break;r=o}for(let o of eo){let s=Q.join(e,o);if(kn(s))return s}return null}function Lc(e){let t=e.config.projectRoot,n=new Set(no(t,e.config.semantic?.typescript?.tsconfigs)),r=A(e,{includeIgnored:!1,extensions:En});for(let i of r){let o=to(t,i);o&&n.add(Q.resolve(o))}if(n.size===0){let i=to(t);i&&n.add(Q.resolve(i))}return[...n].filter(i=>!_c(t,i)).sort((i,o)=>i.localeCompare(o))}function no(e,t=[]){let n=new Set;for(let r of t){let i=Q.isAbsolute(r)?r:Q.join(e,r);kn(i)&&n.add(Q.resolve(i))}for(let r of Yg(e))for(let i of eo){let o=Q.join(r,i);kn(o)&&n.add(Q.resolve(o))}if(n.size===0){let r=to(e);r&&n.add(Q.resolve(r))}return[...n].filter(r=>!_c(e,r)).sort((r,i)=>r.localeCompare(i))}function Yg(e){let t=Q.join(e,"package.json");if(!kn(t))return[];let n;try{n=JSON.parse(zg(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Xg(e,i))}function Xg(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Q.join(e,t);return Zi(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Q.join(e,r||".");return Zi(o)?Qg(o).map(s=>Q.join(o,s,i)).filter(Zi):[]}function Zi(e){try{return Kg(e).isDirectory()}catch{return!1}}function _c(e,t){let n=Q.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 Zg}from"module";var eh=Zg(import.meta.url),Pn;function wc(){if(Pn!==void 0)return Pn;try{Pn=eh("ts-morph")}catch{Pn=null}return Pn}function Ec(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function $r(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Fc(e,t){let n=wc();if(!n)return $r("ts-morph is not installed");let r=Lc(e);if(r.length===0)return $r("no tsconfig found");try{let i=Ec(n,r);return new ro(e,n,i)}catch(i){return $r(i instanceof Error?i.message:String(i),r[0],r)}}var ro=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=vc(t.config.projectRoot),this.sourceFiles=Rc(t,r)}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 Ee(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,i))r.push(o);return r})}referencesFor(t){return Ee(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?gc(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return Ee(this.calleesCache,t.symbolId,()=>Ee(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Ee(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 r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Pc(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Pc(o)}`})}importUsageForDeclaration(t,n){let r=we(this.db,t,n.getModuleSpecifierValue()),i=kc(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>th(t,r,o)):i.map(o=>this.valueImportUsageForEntry(t,r,o))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let l of i)for(let u of hc(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!Xi(l.node)),a=o.some(l=>Xi(l.node)),c=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.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 r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Tr(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=Dc(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of kc(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=bc(a.identifier,r,this.db.config.projectRoot);l.length>0&&ih(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of Nc(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?we(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,r,i);continue}for(let u of l){let m=u.getNameNode().getText(),d=u.getAliasNode()?.getText()??m,p=this.indexedDefinitionByLeaf(c,m);if(!p)continue;let h=r.get(d);h||(h=new Set,r.set(d,h)),h.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Ee(this.indexedDefinitionLeafCache,t,()=>Cc(this.db,t)).get(n)??null}nodeForDefinition(t){return Ee(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Ee(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Sc(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=wn(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=ln(i,r),a=xc(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 r=H(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,r,o);s&&nh(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,oh(s));return i}semanticCalleeForCallNode(t,n,r){let i=rh(n,ln(t,r));if(!i)return null;let o=r.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function kc(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function th(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 nh(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function rh(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function ih(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function oh(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function Pc(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var io=new WeakMap;it({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>io.delete(e)});function Fn(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=io.get(e);r||(r=new Map,io.set(e,r));let i=r.get(n);if(i)return i;let o=Fc(e,t);return r.set(n,o),o}function An(e,t){let n=Br(e,t);return n?n.importUsage(t):[]}function wt(e,t){let n=Br(e,t.relativePath);return n?n.referencesFor(t):[]}function un(e,t){let n=new Map;for(let r of t)for(let i of wt(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let o=n.get(r.symbolId);o||(o=new Set,n.set(r.symbolId,o)),o.add(i.file)}return n}function jr(e,t){let n=new Map;for(let r of t){let i=Br(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function Ac(e,t){let n=Br(e,t.relativePath);return n?n.signatureFor(t):null}function Br(e,t){if(!Mr(t))return null;let n=Fn(e,t);return n.availability().available?n:null}function Hr(e,t){let n=new Map;for(let r of te(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Tc(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Tc(n,o,r.sourcePath)}return n}function Tc(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function mn(e,t,n){let r=_t(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Tn(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(Tn);let o=Hr(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>mt(c,u.file));if(l.length>0)return l.map(Tn)}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=r.filter(u=>mt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(Tn)}return[]}function Oc(e,t,n){let r=mn(e,t,n);if(r.length>0)return r;let i=_t(e).get(n);return!i||i.length===0?[]:i.map(Tn)}function $c(e,t,n={}){let r=hr(e,t);if(!r)return[];let i=P(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=wt(e,{...r,leaf:i,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 Mc(e,a)}}let o=new Map;for(let s of je(e)){let a=T(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!mn(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=kr(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Mc(e,o)}function jc(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 r=new Set(t.map(o=>o.symbolId)),i=new Map;for(let o of je(e)){let s=cc(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of mn(e,o,a)){if(!r.has(c.symbolId)||o===c.relativePath)continue;let l=i.get(c.symbolId);l||(l=new Set,i.set(c.symbolId,l)),l.add(o)}}}return i}function Tn(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Mc(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=H(e,i);for(let a of o){let c=be(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Et(e,t){let n=mh(e,t);return n?dh(e,ah(e,n.match,n.identifier)):[]}function pt(e,t,n={}){return sh(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function sh(e,t,n={}){let r=$c(e,t,{semantic:n.semantic}),i=r.length>0?Bc(r,"source-attribution"):Bc(Et(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Bc(e,t){return e.map(n=>({...n,provenance:t}))}function ah(e,t,n){let r=new Map;for(let[i,o]of ch(e,t.symbolId))r.set(i,lh(e,i,o,t,n));return r}function ch(e,t){let n=new Map;for(let r of Pr(e,[t])){if(e.isIgnored(r.relative_path))continue;let i=n.get(r.relative_path);i||(i=[],n.set(r.relative_path,i)),i.push({start_line:r.chunk_start,end_line:r.chunk_end})}return n}function lh(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?kr(e,t,i,o):[];return n.flatMap(a=>uh(s,a))}function uh(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function mh(e,t){let n=hr(e,t);return n?{match:n,identifier:P(n.symbol)||null}:null}function dh(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=H(e,i);for(let a of o){let c=be(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function he(e,t,n={}){let r=qr(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>ie(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Hc(e,t,n={}){let r=gh(e)?yh(e,t,{semantic:n.semantic!==!1}):hh(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var ph=re("caller-rows",{clearGroups:["whole-project"]}),fh=2e4;function gh(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>fh}function hh(e){return ph.get(e,()=>{let t=Oe(e),n=qr(e,t),r=new Map;for(let s of t)r.set(s.symbol,s.symbolId);let i=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=r.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=i.get(l);u||(u=[],i.set(l,u),o.set(l,new Set));let m=`${s.symbol}|${s.relativePath}`;o.get(l).has(m)||(o.get(l).add(m),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function yh(e,t,n){let r=[],i=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;i.has(c)||(i.add(c),r.push(a))};for(let a of Et(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?bh(e,t):null;if(s)for(let a of wt(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=be(H(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function bh(e,t){return e.get(`SELECT
195
195
  d.id AS documentId,
196
196
  gs.id AS symbolId,
197
197
  gs.symbol,
@@ -210,7 +210,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
210
210
  LEFT JOIN chunks c ON c.document_id = der.document_id
211
211
  JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
212
212
  WHERE gs.id = ?
213
- LIMIT 1`,t.symbolId)??null}function qr(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)$(u.relativePath)&&Qt(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[m,d]of u){let p=s.get(m);p||(p=[],s.set(m,p));let h=a.get(m);h||(h=new Set,a.set(m,h));for(let f of d){let y=`${f.symbol}|${f.chunkId}`;h.has(y)||(h.add(y),p.push(f))}}};i.length>0&&c(yh(e,i)),n.semantic!==!1&&c(Rh(jr(e,t)));let l=r?t:o;return l.length>0&&c(Ch(e,l)),s}function yh(e,t){let n=new Map,r=bh(t,n),i=Lt(e);for(let[o,s]of r){let a=Qt(e,o);if(a)for(let c of a){let l=Sh(s,c.line);if(!l)continue;let u=xh(e,o,i,c.calleeLeaf,c.memberAccess);u&&u.symbol!==l.symbol&&n.get(l.symbolId).push({symbol:u.symbol,file:u.file,chunkId:c.line,source:"ast-callsite"})}}return n}function bh(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function Sh(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function xh(e,t,n,r,i){let o=Fr(t,n.get(r)??[]);return o.length===0?null:Tr(e,t,o,i)}function Ch(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
213
+ LIMIT 1`,t.symbolId)??null}function qr(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)$(u.relativePath)&&Qt(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[m,d]of u){let p=s.get(m);p||(p=[],s.set(m,p));let h=a.get(m);h||(h=new Set,a.set(m,h));for(let f of d){let y=`${f.symbol}|${f.chunkId}`;h.has(y)||(h.add(y),p.push(f))}}};i.length>0&&c(Sh(e,i)),n.semantic!==!1&&c(vh(jr(e,t)));let l=r?t:o;return l.length>0&&c(Ih(e,l)),s}function Sh(e,t){let n=new Map,r=xh(t,n),i=_t(e);for(let[o,s]of r){let a=Qt(e,o);if(a)for(let c of a){let l=Ch(s,c.line);if(!l)continue;let u=Rh(e,o,i,c.calleeLeaf,c.memberAccess);u&&u.symbol!==l.symbol&&n.get(l.symbolId).push({symbol:u.symbol,file:u.file,chunkId:c.line,source:"ast-callsite"})}}return n}function xh(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function Ch(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function Rh(e,t,n,r,i){let o=Fr(t,n.get(r)??[]);return o.length===0?null:Ar(e,t,o,i)}function Ih(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
214
214
  FROM mentions m
215
215
  JOIN chunks c ON m.chunk_id = c.id
216
216
  WHERE m.role != 1`),r=new Map;for(let l of n)r.has(l.document_id)||r.set(l.document_id,[]),r.get(l.document_id).push(l);let i=new Map(e.all("SELECT id, relative_path FROM documents").map(l=>[l.id,l.relative_path])),o=new Map,s=e.all(`SELECT gs.id AS symbol_id, gs.symbol,
@@ -223,10 +223,10 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
223
223
  JOIN chunks c ON m.chunk_id = c.id
224
224
  WHERE m.role = 1
225
225
  GROUP BY m.symbol_id
226
- ) def_chunk ON def_chunk.symbol_id = gs.id`);for(let l of s)o.has(l.symbol_id)||o.set(l.symbol_id,{symbol:l.symbol,file:l.document_id!==null?i.get(l.document_id)??"":""});let a=new Map,c=i;for(let l of t){let u=r.get(l.documentId)??[],m=new Set,d=[],p=null,h=()=>{if(p)return p;let f=c.get(l.documentId)??"",y=new Set;if(f){let C=lc(e,f),E=Math.max(0,l.startLine),N=Math.min(C.length-1,l.endLine);for(let I=E;I<=N;I+=1)for(let v of C[I])y.add(v)}return p=y,y};for(let f of u){if(f.symbol_id===l.symbolId)continue;let y=o.get(f.symbol_id);if(!y)continue;if(!(f.start_line>=l.startLine&&f.end_line<=l.endLine)){if(!(f.start_line<=l.endLine&&f.end_line>=l.startLine))continue;let I=P(y.symbol);if(!I||!h().has(I))continue}let E=`${y.symbol}|${f.chunk_id}`;m.has(E)||(m.add(E),d.push({...y,chunkId:f.chunk_id,source:"scip-chunk"}))}a.set(l.symbolId,d)}return a}function Rh(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,i)}return t}function qc(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=T(e,{includeIgnored:!1}),o=Lt(e),s=t??Me(e),a=new Set(s.map(c=>c.symbolId));return Ih(e,r,i,o,a),vh(e,r,s,a),_h(e,r,i,o,a),n.semantic!==!1&&Eh(r,un(e,wh(s))),r}function Ih(e,t,n,r,i){for(let o of n){if(!$(o))continue;let s=Qt(e,o);if(s)for(let a of s){let c=Fr(o,r.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=Tr(e,o,c,a.memberAccess);l&&i.has(l.symbolId)&&l.file!==o&&oo(t,l.symbolId,o)}}}function vh(e,t,n,r){let i=Nh(n);for(let o of Dh(e,r))e.isIgnored(o.relative_path)||Lh(o,i.get(o.symbol_id))||oo(t,o.symbol_id,o.relative_path)}function Dh(e,t){return Pr(e,t?[...t]:void 0)}function Nh(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 Lh(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function _h(e,t,n,r,i){for(let o of n){if($(o)!=="rust")continue;let s=yt(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=r.get(a);if(c)for(let l of c)i.has(l.symbolId)&&l.file!==o&&oo(t,l.symbolId,o)}}}function oo(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function wh(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Eh(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function Re(e,t,n={}){return Hc(e,t,n)}function so(e,t,n={}){return qc(e,t,n)}function ao(e,t){return jc(e,t)}function Vc(e,t,n={}){let r=so(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:kh(r,ao(e,t))}function kh(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function Wc(e,t,n){let r=t.identifierResolution==="strict"?mn:Oc;for(let i of t.paths)if(!(!$(i)&&!(t.includeVueSfc&&ht(i)))&&!e.isIgnored(i)&&!t.skipPath?.(i))try{let s=(c,l,u,m)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let d=t.resolveTargets?t.resolveTargets({sourceFile:i,name:c,kind:l,defaultTargets:m}):m();for(let p of d)n({sourceFile:i,name:c,target:p,occurrences:u,kind:l})},a=Ge(e,i);for(let[c,l]of a)s(c,"identifier",l.length,()=>r(e,i,c));for(let c of yt(e,i,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>mn(e,i,c.name):()=>r(e,i,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(i)}}var L=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Ti(this.db,t)}definitionsForFile(t){return H(this.db,t)}productionCallableDefinitions(t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:d=!1,sortByLocDesc:p=!1}=t,h=[];for(let f of this.scopedDefinitions(n)){let y=f.relativePath;if(this.db.isIgnored(y)||s&&le(this.db,y)||!Ph(f,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&f.symbol===o)continue;let C=co(f);C<r||C>i||a&&Fh(y)||c&&ne(this.db,f.symbol,y)||m&&dr(f.symbol)||G(y)!=="test"&&(Kt(f.symbol)||!d&&Ei(this.db,y,f.startLine)||h.push(f))}return p?h.sort((f,y)=>co(y)-co(f)):h}calleeMap(t,n={}){return qr(this.db,t,n)}crossFileCallerMap(t,n={}){return so(this.db,t,n)}sourceFallbackCallerFiles(t){return ao(this.db,t)}callerFileMap(t,n={}){return Vc(this.db,t,n)}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of T(this.db,{includeIgnored:!1}))if($(i)==="rust")for(let{name:o}of yt(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return oe(this.db,t)}fileKind(t){return G(t)}hasSuppressionComment(t){return Ei(this.db,t.relativePath,t.startLine)}sourceFiles(){return $e(this.db)}scanSourceReferences(t,n){Wc(this.db,t,n)}callableSignature(t){let n=K(this.db,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function Ph(e,t){return t.requireCallableSymbol?ie(e.symbol):t.requireFunctionLikeSymbol?Y(e.symbol):e.isFunctionLike}function co(e){return e.endLine-e.startLine+1}function Fh(e){return(e.split("/").pop()??"").includes("types")}function lo(e,t){let n=F(e,t);if(!n)return[];let r=P(n.symbol),o=new L(e).definitionsForFile(n.relativePath).filter(c=>ie(c.symbol)),s=o.filter(c=>c.parentTypeName===r||c.symbol.includes(r));return(s.length>0?s:Ah(Th(n.relativePath))===r?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:P(c.symbol)}))}function Ah(e){return e.replace(/\.[^.]+$/,"")}function uo(e,t,n={}){let r=F(e,t);if(!r)return[];let o=!Y(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=dt(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=Mh(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let m=`${u.relativePath}:${u.line}`;c.has(m)||(c.add(m),l.push(u))}return l}function Mh(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Oh(t.symbol);if(n.length===0)return[];let r=[];for(let i of T(e,{extensions:[".rb"],includeIgnored:!1})){let o=A(e,i);if(!o)continue;let s=o.split(`
227
- `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function Oh(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,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}function Mn(e,t,n={}){let r=F(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=St(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:jh(o,i?.display_name??null,r.symbol),source:$h(e,r.relativePath,r.startLine,r.endLine)}],a=dt(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function $h(e,t,n,r){let i=A(e,t);if(!i)return null;let s=i.split(`
226
+ ) def_chunk ON def_chunk.symbol_id = gs.id`);for(let l of s)o.has(l.symbol_id)||o.set(l.symbol_id,{symbol:l.symbol,file:l.document_id!==null?i.get(l.document_id)??"":""});let a=new Map,c=i;for(let l of t){let u=r.get(l.documentId)??[],m=new Set,d=[],p=null,h=()=>{if(p)return p;let f=c.get(l.documentId)??"",y=new Set;if(f){let C=lc(e,f),E=Math.max(0,l.startLine),N=Math.min(C.length-1,l.endLine);for(let I=E;I<=N;I+=1)for(let v of C[I])y.add(v)}return p=y,y};for(let f of u){if(f.symbol_id===l.symbolId)continue;let y=o.get(f.symbol_id);if(!y)continue;if(!(f.start_line>=l.startLine&&f.end_line<=l.endLine)){if(!(f.start_line<=l.endLine&&f.end_line>=l.startLine))continue;let I=P(y.symbol);if(!I||!h().has(I))continue}let E=`${y.symbol}|${f.chunk_id}`;m.has(E)||(m.add(E),d.push({...y,chunkId:f.chunk_id,source:"scip-chunk"}))}a.set(l.symbolId,d)}return a}function vh(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,i)}return t}function qc(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=A(e,{includeIgnored:!1}),o=_t(e),s=t??Oe(e),a=new Set(s.map(c=>c.symbolId));return Dh(e,r,i,o,a),Nh(e,r,s,a),Eh(e,r,i,o,a),n.semantic!==!1&&Ph(r,un(e,kh(s))),r}function Dh(e,t,n,r,i){for(let o of n){if(!$(o))continue;let s=Qt(e,o);if(s)for(let a of s){let c=Fr(o,r.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=Ar(e,o,c,a.memberAccess);l&&i.has(l.symbolId)&&l.file!==o&&oo(t,l.symbolId,o)}}}function Nh(e,t,n,r){let i=_h(n);for(let o of Lh(e,r))e.isIgnored(o.relative_path)||wh(o,i.get(o.symbol_id))||oo(t,o.symbol_id,o.relative_path)}function Lh(e,t){return Pr(e,t?[...t]:void 0)}function _h(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 wh(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Eh(e,t,n,r,i){for(let o of n){if($(o)!=="rust")continue;let s=bt(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=r.get(a);if(c)for(let l of c)i.has(l.symbolId)&&l.file!==o&&oo(t,l.symbolId,o)}}}function oo(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function kh(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Ph(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function Re(e,t,n={}){return Hc(e,t,n)}function so(e,t,n={}){return qc(e,t,n)}function ao(e,t){return jc(e,t)}function Vc(e,t,n={}){let r=so(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:Fh(r,ao(e,t))}function Fh(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function Wc(e,t,n){let r=t.identifierResolution==="strict"?mn:Oc;for(let i of t.paths)if(!(!$(i)&&!(t.includeVueSfc&&yt(i)))&&!e.isIgnored(i)&&!t.skipPath?.(i))try{let s=(c,l,u,m)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let d=t.resolveTargets?t.resolveTargets({sourceFile:i,name:c,kind:l,defaultTargets:m}):m();for(let p of d)n({sourceFile:i,name:c,target:p,occurrences:u,kind:l})},a=Je(e,i);for(let[c,l]of a)s(c,"identifier",l.length,()=>r(e,i,c));for(let c of bt(e,i,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>mn(e,i,c.name):()=>r(e,i,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(i)}}var L=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Ai(this.db,t)}definitionsForFile(t){return H(this.db,t)}productionCallableDefinitions(t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:d=!1,sortByLocDesc:p=!1}=t,h=[];for(let f of this.scopedDefinitions(n)){let y=f.relativePath;if(this.db.isIgnored(y)||s&&le(this.db,y)||!Ah(f,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&f.symbol===o)continue;let C=co(f);C<r||C>i||a&&Th(y)||c&&ne(this.db,f.symbol,y)||m&&dr(f.symbol)||G(y)!=="test"&&(Kt(f.symbol)||!d&&Ei(this.db,y,f.startLine)||h.push(f))}return p?h.sort((f,y)=>co(y)-co(f)):h}calleeMap(t,n={}){return qr(this.db,t,n)}crossFileCallerMap(t,n={}){return so(this.db,t,n)}sourceFallbackCallerFiles(t){return ao(this.db,t)}callerFileMap(t,n={}){return Vc(this.db,t,n)}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of A(this.db,{includeIgnored:!1}))if($(i)==="rust")for(let{name:o}of bt(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return oe(this.db,t)}fileKind(t){return G(t)}hasSuppressionComment(t){return Ei(this.db,t.relativePath,t.startLine)}sourceFiles(){return je(this.db)}scanSourceReferences(t,n){Wc(this.db,t,n)}callableSignature(t){let n=K(this.db,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function Ah(e,t){return t.requireCallableSymbol?ie(e.symbol):t.requireFunctionLikeSymbol?Y(e.symbol):e.isFunctionLike}function co(e){return e.endLine-e.startLine+1}function Th(e){return(e.split("/").pop()??"").includes("types")}function lo(e,t){let n=F(e,t);if(!n)return[];let r=P(n.symbol),o=new L(e).definitionsForFile(n.relativePath).filter(c=>ie(c.symbol)),s=o.filter(c=>c.parentTypeName===r||c.symbol.includes(r));return(s.length>0?s:Oh(Mh(n.relativePath))===r?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:P(c.symbol)}))}function Oh(e){return e.replace(/\.[^.]+$/,"")}function uo(e,t,n={}){let r=F(e,t);if(!r)return[];let o=!Y(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=pt(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=$h(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let m=`${u.relativePath}:${u.line}`;c.has(m)||(c.add(m),l.push(u))}return l}function $h(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=jh(t.symbol);if(n.length===0)return[];let r=[];for(let i of A(e,{extensions:[".rb"],includeIgnored:!1})){let o=T(e,i);if(!o)continue;let s=o.split(`
227
+ `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function jh(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,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}function Mn(e,t,n={}){let r=F(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=xt(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:Hh(o,i?.display_name??null,r.symbol),source:Bh(e,r.relativePath,r.startLine,r.endLine)}],a=pt(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function Bh(e,t,n,r){let i=T(e,t);if(!i)return null;let s=i.split(`
228
228
  `).slice(n,r+1).join(`
229
- `).trimEnd();return s.length>0?s:null}function jh(e,t,n){let r=bt(e);if(r&&!Bh(r))return r;let i=(t??"").trim();return i?Y(n)&&!i.endsWith("()")?`${i}()`:i:b(n)}function Bh(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function On(e,t){let n=me(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
229
+ `).trimEnd();return s.length>0?s:null}function Hh(e,t,n){let r=St(e);if(r&&!qh(r))return r;let i=(t??"").trim();return i?Y(n)&&!i.endsWith("()")?`${i}()`:i:b(n)}function qh(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function On(e,t){let n=me(e,t);return n?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
@@ -290,7 +290,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
290
290
  JOIN documents d2 ON sym_def.document_id = d2.id
291
291
  WHERE d2.relative_path IN (${r})
292
292
  AND d1.relative_path NOT IN (${r})
293
- ORDER BY d1.relative_path`,...n,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function Bn(e,t){let n=nn(e,t);return n.length===0?[]:Vh([...Hh(e,n),...qh(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(Wh)}function Hh(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
293
+ ORDER BY d1.relative_path`,...n,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function Bn(e,t){let n=nn(e,t);return n.length===0?[]:Uh([...Vh(e,n),...Wh(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(Gh)}function Vh(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
294
294
  FROM mentions m
295
295
  JOIN chunks c ON m.chunk_id = c.id
296
296
  JOIN documents d1 ON c.document_id = d1.id
@@ -317,7 +317,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
317
317
  AND m.role != 1
318
318
  AND ${e.localSymbolPredicate}
319
319
  ${e.pathExclusionsFor("d1")}
320
- ORDER BY d1.relative_path`,...t,...t,...t)}function qh(e,t){let n=new L(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>ie(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function Vh(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function Wh(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:b(e.symbol)}}var Hn=new WeakMap;function Gc(e,t){let n=$(t);return n==="rust"?Qh(e,t):n==="typescript"||n==="tsx"||n==="javascript"?Gh(e,t):[]}var Uh=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function Gh(e,t){let n=ce(e,t);if(!n)return[];let r=Hn.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),o=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),s=!1,a=n.rootNode;for(let l of a.namedChildren){if(l.type!=="expression_statement")continue;let u=l.namedChild(0);if(!u||u.type!=="call_expression")continue;let m=u.namedChild(0);if(!m)continue;let d=m.type==="member_expression"?m.namedChild(m.namedChildCount-1)?.text:m.text;if(d&&Uh.has(d)){s=!0;break}}let c=[];s&&c.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||o)&&c.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let l of a.namedChildren){let u=null,m=null;if(l.type==="function_declaration")u=l.namedChild(0)?.text??null,m=l;else if(l.type==="export_statement"){let d=l.namedChild(0);d?.type==="function_declaration"&&(u=d.namedChild(0)?.text??null,m=d)}else if(l.type==="lexical_declaration"){let d=l.namedChild(0);if(d?.type==="variable_declarator"){let p=d.namedChild(0)?.text,h=d.namedChild(1);p&&(h?.type==="arrow_function"||h?.type==="function_expression")&&(u=p,m=d)}}u&&/^use[A-Z]/.test(u)&&m&&c.push({startLine:m.startPosition.row,endLine:m.endPosition.row,reason:"React custom hook (use*)"})}return c.push(...Jc(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Hn.set(n,c),c}var Jh=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function zh(e){return Jh.test(e)}function Jc(e,t,n){let r=[],i=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(zh(u.text)){r.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)i(s)};return i(e.rootNode),r}function Qh(e,t){let n=ce(e,t);if(!n)return[];let r=Hn.get(n);if(r)return r;let i=[],o=Kh(n);return o?(Hn.set(n,o),o):(zc(n.rootNode,i,!1,!1),i.push(...Jc(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"]))),i.push(...iy(n.rootNode)),Hn.set(n,i),i)}function Kh(e){return oy(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function zc(e,t,n,r){let i=n,o=r;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"?Yh(e,t,n,r):r&&ry(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"?Xh(e,t,n):e.type==="mod_item"&&mo(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)zc(s,t,i,o)}function Yh(e,t,n,r){let i=mo(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=ey(s);if(a){o=a;break}if(Qc(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function Xh(e,t,n){let r=mo(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(ny)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(Qc)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function mo(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var Zh=[{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 ey(e){return Zh.find(({re:t})=>t.test(e))?.reason??null}var ty=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function ny(e){return/#\[\s*derive\s*\(/.test(e)?ty.some(t=>t.test(e)):!1}function Qc(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function ry(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function iy(e){let t=ay(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function oy(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 sy=/^#!?\[\s*serde\s*\(/,Uc=/\bwith\s*=\s*"([^"]+)"/g;function ay(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!sy.test(n.text))continue;Uc.lastIndex=0;let r;for(;(r=Uc.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function Kc(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Gc(e,r);return i={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r);for(let c of a.ranges)if(i>=c.startLine&&i<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of gr(o))if(a.containers.has(c))return!0;return!1}}function po(e,t={}){Li(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function fo(e,t,n={}){Li(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Xc(e,t){return t.isIgnoredPath(e.relativePath)?je("ignored-file"):it(e.symbol)?je("module-like-symbol"):Yc(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Yc(e.enclosingSymbol)?je("nested-non-callable-value"):!t.includeTests&&!go(e.relativePath)?je("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?je("excluded-file-region"):dr(e.symbol)?je("rust-trait-impl-member"):Kt(e.symbol)?je("rust-test-module"):!t.includeMembers&&!cy(e)?je("member"):e.endLine-e.startLine+1<t.minLoc?je("below-min-loc"):{accepted:!0}:je("non-value-symbol")}function go(e){return G(e)!=="test"}function je(e){return{accepted:!1,rejectionReason:e}}function Yc(e){return Y(e)||e.endsWith("().")||e.endsWith(".")}function cy(e){return ie(e.symbol)||gr(e.symbol).length===0}function B(e){return e.endLine-e.startLine+1}function Vr(e,t){return B(e)-B(t)||e.relativePath.localeCompare(t.relativePath)}function Ie(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function dn(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function Zc(){return new Map}function el(e,t,n){let r=new Map;for(let i of uc(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Wr(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function tl(e,t,n){let r=new Set;for(let i of mc(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function ho(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function nl(e){return e?.occurrences??0}function Wr(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=il(e,t,n);o.occurrences+=r,o.sources.add(i)}function rl(e,t,n,r,i){if(r<=0)return;let o=il(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function il(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}function Je(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=Ie(ly(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),m=o?new Set(ac(e)):new Set,d=a?Zc():el(e,m,u.map(C=>C.symbolId)),p=a?tl(e,u.map(C=>C.symbolId),m):new Set,h=a?u.filter(C=>!p.has(C.symbolId)):u;a?fy(e,h,d,m):py(e,h,d,m);let f=a?h.filter(C=>!ho(d,C.symbolId)):u;Sy(e,f,d,{includeTests:i,inactiveBarrelPaths:m,includeSemantic:!a&&l});let y=a?h.filter(C=>!ho(d,C.symbolId)):u;return dy(e,uy(y,d))}function ly(e,t){let n=Kc(e),r=[];for(let i of T(e,{scope:t.scope}))try{for(let o of H(e,i))Xc(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{fo(e,i,{definitions:!0})}return r}function uy(e,t){return e.map(n=>my(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function my(e,t){let n=t.get(e.symbolId)??new Map,r=nl(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=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:r,cross_file_refs:i}}function dy(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||le(e,s.relative_path)||ne(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:b(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function py(e,t,n,r){if(t.length===0)return;let i=new L(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of T(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.has(c)},c=>{o.has(c.target.symbolId)&&(yy(e,c)||Wr(n,c.target.symbolId,c.sourceFile,by(c),"source-fallback"))})}function fy(e,t,n,r){if(t.length===0)return;let i=new L(e),o=gy(t),s=new Set(i.sourceFiles());for(let u of T(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let m=c.get(u);return m||(m=Hr(e,u),c.set(u,m)),m};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.has(u),resolveTargets:({sourceFile:u,name:m,kind:d})=>{let p=o.get(m);return p?hy(u,m,p,l(u),{permissive:d!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),fo(e,u)}},u=>{let m=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&ol(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:m})||Wr(n,u.target.symbolId,u.sourceFile,m,"source-fallback")})}function gy(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function hy(e,t,n,r,i){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r.get(t);if(s)for(let c of s){let l=n.filter(u=>ut(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of r.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>ut(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function yy(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&ol(e,t)}function by(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function ol(e,t){return t.occurrences>1?!1:te(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Sy(e,t,n,r){for(let i of t){let o=Re(e,i,{semantic:r.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===i.relativePath||e.isIgnored(a)||r.inactiveBarrelPaths.has(a)||!r.includeTests&&!go(a)||rl(n,i.symbolId,a,1,"caller-map")}}}function yo(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
320
+ ORDER BY d1.relative_path`,...t,...t,...t)}function Wh(e,t){let n=new L(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>ie(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function Uh(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function Gh(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:b(e.symbol)}}var Hn=new WeakMap;function Gc(e,t){let n=$(t);return n==="rust"?Yh(e,t):n==="typescript"||n==="tsx"||n==="javascript"?zh(e,t):[]}var Jh=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function zh(e,t){let n=ce(e,t);if(!n)return[];let r=Hn.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),o=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),s=!1,a=n.rootNode;for(let l of a.namedChildren){if(l.type!=="expression_statement")continue;let u=l.namedChild(0);if(!u||u.type!=="call_expression")continue;let m=u.namedChild(0);if(!m)continue;let d=m.type==="member_expression"?m.namedChild(m.namedChildCount-1)?.text:m.text;if(d&&Jh.has(d)){s=!0;break}}let c=[];s&&c.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||o)&&c.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let l of a.namedChildren){let u=null,m=null;if(l.type==="function_declaration")u=l.namedChild(0)?.text??null,m=l;else if(l.type==="export_statement"){let d=l.namedChild(0);d?.type==="function_declaration"&&(u=d.namedChild(0)?.text??null,m=d)}else if(l.type==="lexical_declaration"){let d=l.namedChild(0);if(d?.type==="variable_declarator"){let p=d.namedChild(0)?.text,h=d.namedChild(1);p&&(h?.type==="arrow_function"||h?.type==="function_expression")&&(u=p,m=d)}}u&&/^use[A-Z]/.test(u)&&m&&c.push({startLine:m.startPosition.row,endLine:m.endPosition.row,reason:"React custom hook (use*)"})}return c.push(...Jc(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Hn.set(n,c),c}var Qh=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function Kh(e){return Qh.test(e)}function Jc(e,t,n){let r=[],i=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(Kh(u.text)){r.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)i(s)};return i(e.rootNode),r}function Yh(e,t){let n=ce(e,t);if(!n)return[];let r=Hn.get(n);if(r)return r;let i=[],o=Xh(n);return o?(Hn.set(n,o),o):(zc(n.rootNode,i,!1,!1),i.push(...Jc(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"]))),i.push(...sy(n.rootNode)),Hn.set(n,i),i)}function Xh(e){return ay(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function zc(e,t,n,r){let i=n,o=r;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"?Zh(e,t,n,r):r&&oy(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"?ey(e,t,n):e.type==="mod_item"&&mo(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)zc(s,t,i,o)}function Zh(e,t,n,r){let i=mo(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=ny(s);if(a){o=a;break}if(Qc(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function ey(e,t,n){let r=mo(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(iy)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(Qc)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function mo(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var ty=[{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 ny(e){return ty.find(({re:t})=>t.test(e))?.reason??null}var ry=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function iy(e){return/#\[\s*derive\s*\(/.test(e)?ry.some(t=>t.test(e)):!1}function Qc(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function oy(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function sy(e){let t=ly(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function ay(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 cy=/^#!?\[\s*serde\s*\(/,Uc=/\bwith\s*=\s*"([^"]+)"/g;function ly(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!cy.test(n.text))continue;Uc.lastIndex=0;let r;for(;(r=Uc.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function Kc(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Gc(e,r);return i={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r);for(let c of a.ranges)if(i>=c.startLine&&i<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of gr(o))if(a.containers.has(c))return!0;return!1}}function po(e,t={}){Li(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function fo(e,t,n={}){Li(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Xc(e,t){return t.isIgnoredPath(e.relativePath)?Be("ignored-file"):ot(e.symbol)?Be("module-like-symbol"):Yc(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Yc(e.enclosingSymbol)?Be("nested-non-callable-value"):!t.includeTests&&!go(e.relativePath)?Be("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?Be("excluded-file-region"):dr(e.symbol)?Be("rust-trait-impl-member"):Kt(e.symbol)?Be("rust-test-module"):!t.includeMembers&&!uy(e)?Be("member"):e.endLine-e.startLine+1<t.minLoc?Be("below-min-loc"):{accepted:!0}:Be("non-value-symbol")}function go(e){return G(e)!=="test"}function Be(e){return{accepted:!1,rejectionReason:e}}function Yc(e){return Y(e)||e.endsWith("().")||e.endsWith(".")}function uy(e){return ie(e.symbol)||gr(e.symbol).length===0}function B(e){return e.endLine-e.startLine+1}function Vr(e,t){return B(e)-B(t)||e.relativePath.localeCompare(t.relativePath)}function Ie(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function dn(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function Zc(){return new Map}function el(e,t,n){let r=new Map;for(let i of uc(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Wr(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function tl(e,t,n){let r=new Set;for(let i of mc(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function ho(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function nl(e){return e?.occurrences??0}function Wr(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=il(e,t,n);o.occurrences+=r,o.sources.add(i)}function rl(e,t,n,r,i){if(r<=0)return;let o=il(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function il(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}function ze(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=Ie(my(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),m=o?new Set(ac(e)):new Set,d=a?Zc():el(e,m,u.map(C=>C.symbolId)),p=a?tl(e,u.map(C=>C.symbolId),m):new Set,h=a?u.filter(C=>!p.has(C.symbolId)):u;a?hy(e,h,d,m):gy(e,h,d,m);let f=a?h.filter(C=>!ho(d,C.symbolId)):u;Cy(e,f,d,{includeTests:i,inactiveBarrelPaths:m,includeSemantic:!a&&l});let y=a?h.filter(C=>!ho(d,C.symbolId)):u;return fy(e,dy(y,d))}function my(e,t){let n=Kc(e),r=[];for(let i of A(e,{scope:t.scope}))try{for(let o of H(e,i))Xc(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{fo(e,i,{definitions:!0})}return r}function dy(e,t){return e.map(n=>py(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function py(e,t){let n=t.get(e.symbolId)??new Map,r=nl(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=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:r,cross_file_refs:i}}function fy(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||le(e,s.relative_path)||ne(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:b(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function gy(e,t,n,r){if(t.length===0)return;let i=new L(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of A(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.has(c)},c=>{o.has(c.target.symbolId)&&(Sy(e,c)||Wr(n,c.target.symbolId,c.sourceFile,xy(c),"source-fallback"))})}function hy(e,t,n,r){if(t.length===0)return;let i=new L(e),o=yy(t),s=new Set(i.sourceFiles());for(let u of A(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let m=c.get(u);return m||(m=Hr(e,u),c.set(u,m)),m};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.has(u),resolveTargets:({sourceFile:u,name:m,kind:d})=>{let p=o.get(m);return p?by(u,m,p,l(u),{permissive:d!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),fo(e,u)}},u=>{let m=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&ol(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:m})||Wr(n,u.target.symbolId,u.sourceFile,m,"source-fallback")})}function yy(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function by(e,t,n,r,i){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r.get(t);if(s)for(let c of s){let l=n.filter(u=>mt(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of r.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>mt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function Sy(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&ol(e,t)}function xy(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function ol(e,t){return t.occurrences>1?!1:te(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Cy(e,t,n,r){for(let i of t){let o=Re(e,i,{semantic:r.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===i.relativePath||e.isIgnored(a)||r.inactiveBarrelPaths.has(a)||!r.includeTests&&!go(a)||rl(n,i.symbolId,a,1,"caller-map")}}}function yo(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
321
321
  gs.symbol,
322
322
  COUNT(*) AS ref_count,
323
323
  COUNT(DISTINCT ref_d.id) AS file_count,
@@ -340,14 +340,14 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
340
340
  ${i}
341
341
  GROUP BY gs.id
342
342
  ORDER BY ref_count DESC
343
- LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:b(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:xy(e,r,n)}function xy(e,t,n){return Me(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>Cy(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function Cy(e,t){let n=Re(e,t,{limit:500});return{symbol:t.symbol,shortName:b(t.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:t.relativePath}}function bo(e,t,n={}){return al(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function So(e,t){let n=Ry(e,t);return n.length>0?n:Iy(e,t)}function xo(e,t,n={}){return al(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function Ry(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
343
+ LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:b(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:Ry(e,r,n)}function Ry(e,t,n){return Oe(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>Iy(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function Iy(e,t){let n=Re(e,t,{limit:500});return{symbol:t.symbol,shortName:b(t.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:t.relativePath}}function bo(e,t,n={}){return al(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function So(e,t){let n=vy(e,t);return n.length>0?n:Dy(e,t)}function xo(e,t,n={}){return al(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function vy(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
344
344
  FROM mentions m
345
345
  JOIN chunks c ON m.chunk_id = c.id
346
346
  JOIN documents d ON c.document_id = d.id
347
347
  JOIN global_symbols gs ON m.symbol_id = gs.id
348
348
  WHERE gs.symbol LIKE ?
349
349
  AND m.role = 2
350
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:b(r.symbol),fromFile:r.importer}))}function Iy(e,t){let n=F(e,t),r=n?.relativePath??null,i=n?P(n.symbol):t.replace(/\(\)$/,""),o=n?it(n.symbol):!1,s=new Set;for(let a of T(e,{includeIgnored:!1}))for(let c of te(e,a))vy(c,a,{targetFile:r,targetLeaf:i,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??i,shortName:n?b(n.symbol):i,fromFile:a}))}function vy(e,t,n){return!e.sourcePath||n.targetFile&&sl(e.sourcePath)!==sl(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&_y(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function al(e,t,n={}){let r=me(e,t);return r?Dy(e,r,n)??(n.semantic===!1?null:Ny(e,r))??Ly(e,r):null}function Dy(e,t,n){let i=e.all(`SELECT DISTINCT
350
+ ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:b(r.symbol),fromFile:r.importer}))}function Dy(e,t){let n=F(e,t),r=n?.relativePath??null,i=n?P(n.symbol):t.replace(/\(\)$/,""),o=n?ot(n.symbol):!1,s=new Set;for(let a of A(e,{includeIgnored:!1}))for(let c of te(e,a))Ny(c,a,{targetFile:r,targetLeaf:i,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??i,shortName:n?b(n.symbol):i,fromFile:a}))}function Ny(e,t,n){return!e.sourcePath||n.targetFile&&sl(e.sourcePath)!==sl(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&Ey(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function al(e,t,n={}){let r=me(e,t);return r?Ly(e,r,n)??(n.semantic===!1?null:_y(e,r))??wy(e,r):null}function Ly(e,t,n){let i=e.all(`SELECT DISTINCT
351
351
  gs.symbol,
352
352
  def_d.relative_path AS from_file,
353
353
  imp_d.relative_path AS importer,
@@ -373,7 +373,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
373
373
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
374
374
  WHERE imp_d.relative_path = ?
375
375
  AND m.role = 2
376
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Tn(e,t);return i.map(s=>({symbol:s.symbol,shortName:b(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 Ny(e,t){let n=Tn(e,t);return n.length>0?n.map(r=>{let i=cl(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function Ly(e,t){return te(e,t).map(n=>{let r=cl(n.importedName,n.localName,n.kind),i=n.kind==="side-effect"?!0:n.used;return{symbol:r,shortName:r,fromFile:n.sourcePath??"(external)",importer:t,used:i}})}function cl(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 sl(e){return e.replace(/\\/g,"/")}function _y(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Co(e,t){let n=nn(e,t),r=pr(e,n,{sort:!0});if(r.length===0)return[];let i=r.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 i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,m=1/0;for(let d of i)if(d!==l&&d.startLine<=l.startLine&&d.endLine>=l.endLine){if(d.startLine===l.startLine&&d.endLine===l.endLine&&!Ca(d.symbol,l.symbol))continue;let h=d.endLine-d.startLine;h<m&&(m=h,u=d)}u?u.children.push(l):s.push(l)}return s}function Ro(e,t){let n=F(e,t);return n?new L(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>xa(n.symbol,i.symbol)).sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine).map(i=>({symbol:i.symbol,shortName:b(i.symbol),startLine:i.startLine,endLine:i.endLine,kind:ee(i.symbol)??"unknown"})):[]}function Io(e,t){let n=F(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
376
+ ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:An(e,t);return i.map(s=>({symbol:s.symbol,shortName:b(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 _y(e,t){let n=An(e,t);return n.length>0?n.map(r=>{let i=cl(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function wy(e,t){return te(e,t).map(n=>{let r=cl(n.importedName,n.localName,n.kind),i=n.kind==="side-effect"?!0:n.used;return{symbol:r,shortName:r,fromFile:n.sourcePath??"(external)",importer:t,used:i}})}function cl(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 sl(e){return e.replace(/\\/g,"/")}function Ey(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Co(e,t){let n=nn(e,t),r=pr(e,n,{sort:!0});if(r.length===0)return[];let i=r.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 i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,m=1/0;for(let d of i)if(d!==l&&d.startLine<=l.startLine&&d.endLine>=l.endLine){if(d.startLine===l.startLine&&d.endLine===l.endLine&&!Ca(d.symbol,l.symbol))continue;let h=d.endLine-d.startLine;h<m&&(m=h,u=d)}u?u.children.push(l):s.push(l)}return s}function Ro(e,t){let n=F(e,t);return n?new L(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>xa(n.symbol,i.symbol)).sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine).map(i=>({symbol:i.symbol,shortName:b(i.symbol),startLine:i.startLine,endLine:i.endLine,kind:ee(i.symbol)??"unknown"})):[]}function Io(e,t){let n=F(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
377
377
  FROM mentions m
378
378
  JOIN chunks c ON m.chunk_id = c.id
379
379
  WHERE m.symbol_id = ?
@@ -394,7 +394,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
394
394
  AND m.role != 1
395
395
  AND def_d.id != d.id
396
396
  GROUP BY d.id
397
- ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=oe(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Do(e,t={}){return wy(e,t).map(n=>({name:b(n.symbol),count:n.file_count}))}function wy(e,t){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
397
+ ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=oe(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Do(e,t={}){return ky(e,t).map(n=>({name:b(n.symbol),count:n.file_count}))}function ky(e,t){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
398
398
  FROM mentions m
399
399
  JOIN chunks c ON m.chunk_id = c.id
400
400
  JOIN global_symbols gs ON m.symbol_id = gs.id
@@ -487,12 +487,12 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
487
487
  ${i}
488
488
  GROUP BY def_d.id, ref_d.id
489
489
  ORDER BY shared DESC
490
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>({file1:s.file1,file2:s.file2,sharedSymbols:s.shared}))}function Et(e,t={}){let{scope:n,maxDepth:r=10}=t,i=oe(e,n),o=[],s=new Set,a=new Set,c=[];function l(m,d){if(d>r)return;if(a.has(m)){let h=c.indexOf(m);if(h!==-1){let f=c.slice(h).concat(m),y=f.indexOf(f.reduce((N,I)=>N<I?N:I)),C=[...f.slice(y,-1),...f.slice(0,y),f[y]],E=C.join(" -> ");u.has(E)||(u.add(E),o.push({path:C,kind:Ey(C)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let h of p)l(h,d+1);c.pop(),a.delete(m)}let u=new Set;for(let m of i.keys())s.has(m)||l(m,0);return o.sort((m,d)=>m.kind!==d.kind?m.kind==="real"?-1:1:m.path.length-d.path.length),o}function Ey(e){for(let r of e){let i=G(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Er(t)||Er(n)||ll(t,n)||ll(n,t)||ul(t,n)||ul(n,t)||G(t)==="entry"||G(n)==="entry"?"module-hierarchy":"real"}function ll(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 ul(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function wo(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new L(e);return Ie(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>ky(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,m)=>m.score-u.score||m.fanIn-u.fanIn).slice(0,n)}function ky(e,t,n){let r=new Set(Re(e,t,{limit:500,semantic:n}).map(o=>o.file)).size,i=new Set(he(e,t,{limit:500,semantic:n}).filter(o=>o.file!==t.relativePath).map(o=>`${o.symbol}|${o.file}`)).size;return{symbol:t.symbol,shortName:b(t.symbol),fanIn:r,fanOut:i,score:r*i,definedIn:t.relativePath}}function kt(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new L(e),s=t.semantic!==!1,a=Ie(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let f of o.frameworkReferencedSymbolIds(a))l.add(f);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),m=a.filter(f=>!l.has(f.symbolId)).filter(f=>!u.has(f.symbolId)),d=o.sourceFallbackCallerFiles(m);for(let f of d.keys())l.add(f);let p=m.filter(f=>!l.has(f.symbolId)),h=o.symbolsWithNonSelfCallees(p,{additive:!0,semantic:s});for(let f of h)u.add(f);return p.filter(f=>!u.has(f.symbolId)).sort((f,y)=>B(y)-B(f)||f.relativePath.localeCompare(y.relativePath)||f.startLine-y.startLine).map(f=>({symbol:f.symbol,shortName:b(f.symbol),relativePath:f.relativePath,startLine:f.startLine,endLine:f.endLine,loc:B(f)}))}var ko={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"},Eo=new Map;for(let[e,t]of Object.entries(ko))Eo.set(t.toLowerCase(),Number(e));function Py(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Eo.get(n);if(r!==void 0)return r;for(let[i,o]of Eo)if(i.includes(n))return o;return null}function Po(e,t,n={}){let{scope:r,limit:i=100}=n,o=Py(t);return o===null?[]:ml(e,r).map(a=>({row:a,resolvedKind:dl(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:b(a.symbol),kind:c,kindName:ko[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function Fo(e,t={}){let n=new Map;for(let r of ml(e,t.scope)){let i=dl(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:ko[r]??"Unknown",count:i}))}function ml(e,t){return Me(e,{scope:t}).map(Fy)}function Fy(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 dl(e){return e.kind!==null&&e.kind!==0?Ty(e.kind,e.symbol,e.documentation):Ay(e.symbol,e.documentation,e.enclosing_symbol)}function Ty(e,t,n){let r=(n??"").toLowerCase();if(ee(t)==="type"){if(r.includes("type "))return 76;if(r.includes("interface "))return 27;if(r.includes("struct "))return 68;if(r.includes("trait "))return 73;if(r.includes("class "))return 9}return e}function Ay(e,t,n){let r=Z(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=ee(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?ee(n):o?.suffix??null)==="type"?21:83}function To(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=oe(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,m=[],d=0;for(let v of o.keys()){if(c.has(v))continue;let w=[],V=(o.get(v)??new Set).values();for(c.set(v,d),l.set(v,d),d+=1,m.push(v),u.add(v),w.push({node:v,iter:V,pendingChild:null});w.length>0;){let O=w[w.length-1];if(O.pendingChild!==null){let Jt=O.pendingChild;O.pendingChild=null,l.set(O.node,Math.min(l.get(O.node),l.get(Jt)))}let Fe=O.iter.next();if(Fe.done){if(l.get(O.node)===c.get(O.node)){let Jt=[];for(;;){let lr=m.pop();if(u.delete(lr),Jt.push(lr),s.set(lr,a.length),lr===O.node)break}a.push(Jt)}w.pop();continue}let Te=Fe.value;if(c.has(Te))u.has(Te)&&l.set(O.node,Math.min(l.get(O.node),c.get(Te)));else{c.set(Te,d),l.set(Te,d),d+=1,m.push(Te),u.add(Te);let Jt=(o.get(Te)??new Set).values();O.pendingChild=Te,w.push({node:Te,iter:Jt,pendingChild:null})}}}let p=new Map,h=new Array(a.length);for(let v=0;v<a.length;v++)h[v]=a[v].length,p.set(v,new Set);for(let[v,w]of o){let V=s.get(v);for(let O of w){let Fe=s.get(O);Fe!==V&&p.get(V).add(Fe)}}let f=new Array(a.length),y=new Array(a.length);for(let v=0;v<a.length;v++){let w=[],V=0;for(let O of p.get(v)){let Fe=y[O];Fe>V&&(V=Fe,w=f[O])}f[v]=[v,...w],y[v]=h[v]+V}function C(v){return f[v]}let E=a.map(v=>[...v].sort()),N=new Set,I=[];for(let v=0;v<a.length;v++){let w=C(v),V=[];for(let Fe of w)V.push(...E[Fe]);if(V.length<i)continue;let O=V.join(" ");N.has(O)||(N.add(O),I.push({chain:V,depth:V.length}))}return I.sort((v,w)=>w.depth-v.depth),I.slice(0,n)}function Ao(e,t){let n=F(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
491
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:b(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let m=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!m)break;i.push({symbol:m.symbol,shortName:b(m.symbol),depth:s}),o=m.enclosing_symbol,s++}if(i.length>1)return i;let c=Z(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let m=l.length-2,d=1;m>=0;m--,d++){let h=l.slice(0,m+1).map(f=>f.suffix==="method"?`${f.name}()`:f.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:d})}return u}function qn(e,t,n={}){let r=F(e,t);if(!r)return null;let i=n.semantic!==!1,o=Re(e,r,{limit:50,semantic:i}),s=dn(he(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:b(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file}))}}function Vn(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Wn(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function pl(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function Mo(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let o of i)n.set(o,(n.get(o)??0)+1);let r=new Map;for(let[i,o]of n)r.set(i,Math.log(t/o));return r}function My(e){let t=[...e.values()].sort((r,i)=>r-i);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 fl(e,t,n){let r=Vn(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,o=0,s=0,a=new Set([...e,...t]);for(let p of a){let h=n.get(p)??0,f=e.has(p)?h:0,y=t.has(p)?h:0;i+=f*y,o+=f*f,s+=y*y}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?i/c:0,u=My(n),m=[],d=[];for(let p of r)(n.get(p)??0)>=u?m.push(p):d.push(p);return m.sort((p,h)=>(n.get(h)??0)-(n.get(p)??0)),{similarity:l,significantShared:m,trivialShared:d}}function Gn(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=jy(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Y(o.symbol))return[];let s=Oy(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):Hy(e,t,{minSimilarity:r,limit:i})}function Oy(e,t,n,r){let i=hl(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),o=Mo([t,...i].map(a=>a.callees)),s=[];for(let a of i){if(a.callees.size<3)continue;let c=gl(t,a,o,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});c&&s.push(c)}return s.sort((a,c)=>c.similarity-a.similarity),s}function gl(e,t,n,r){let{similarity:i,significantShared:o}=fl(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let s=Vn(e.callees,t.callees).size;if(o.length<r.requireSignificantShared&&s<r.requireSharedCount)return null;let a=o.length>0?o:[...Vn(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:b(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:b(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(b),uniqueToA:[...Wn(e.callees,t.callees)].map(b),uniqueToB:[...Wn(t.callees,e.callees)].map(b)}}function ze(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=hl(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=Mo(c.map(f=>f.callees)),u=new Map;for(let f of c)for(let y of f.callees)u.set(y,(u.get(y)??0)+1);let m=Math.max(8,Math.ceil(Math.sqrt(c.length))),d=new Map;for(let f=0;f<c.length;f+=1)for(let y of c[f].callees){if((u.get(y)??0)>m)continue;let C=d.get(y);C||(C=[],d.set(y,C)),C.push(f)}let p=[],h=new Set;e:for(let f=0;f<c.length;f+=1){let y=c[f],C=new Set;for(let E of y.callees){let N=d.get(E);if(N)for(let I of N)I>f&&C.add(I)}for(let E of C){let N=`${f}|${E}`;if(h.has(N))continue;h.add(N);let I=c[E];if(s&&y.file===I.file)continue;if(y.paramCount>=0&&I.paramCount>=0){let w=Math.abs(y.paramCount-I.paramCount),V=Math.max(2,Math.ceil(Math.max(y.paramCount,I.paramCount)*.5));if(w>V)continue}let v=gl(y,I,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});if(v&&(p.push(v),p.length>r*5))break e}}return p.sort((f,y)=>y.similarity-f.similarity),p.slice(0,r)}var $y=["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 jy(e,t,n){let r=F(e,t),i=new L(e);if(!r)return null;let o=he(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:yl(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}function hl(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=new L(e),a=Ie(s.productionCallableDefinitions({scope:r,minLoc:5,excludeSymbol:i,sortByLocDesc:typeof o=="number"&&o>0}),o),c=s.calleeMap(a,{semantic:t.semantic!==!1});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:yl((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function yl(e){return new Set([...e].filter(t=>!By(t)))}function By(e){return $y.some(t=>e.includes(t))}function Hy(e,t,n){let r=qy(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[];for(let s of Wy(e)){if(s.symbol===r.symbol||s.tokens.size<3)continue;let a=Vn(r.tokens,s.tokens);if(a.size<2)continue;let c=new Set([...r.tokens,...s.tokens]),l=c.size>0?a.size/c.size:0;l<i||o.push({symbolA:r.symbol,shortNameA:b(r.symbol),fileA:r.file,symbolB:s.symbol,shortNameB:b(s.symbol),fileB:s.file,similarity:l,similarityBasis:"source-tokens",sharedCallees:[...a].sort(),uniqueToA:[...Wn(r.tokens,s.tokens)].sort(),uniqueToB:[...Wn(s.tokens,r.tokens)].sort()})}return o.sort((s,a)=>a.similarity-s.similarity||s.shortNameB.localeCompare(a.shortNameB)),o.slice(0,n.limit)}function qy(e,t){let n=F(e,t);if(!n||!Y(n.symbol))return null;let r=Vy(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function Vy(e,t){let n=P(t.symbol),r=bl(e,t.relativePath,t.startLine,t.endLine,n),i=Sl(r,n);return i.size>0?i:null}function Wy(e){return new L(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Sl(bl(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function bl(e,t,n,r,i){let o=A(e,t);if(!o)return"";let s=o.split(`
490
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>({file1:s.file1,file2:s.file2,sharedSymbols:s.shared}))}function kt(e,t={}){let{scope:n,maxDepth:r=10}=t,i=oe(e,n),o=[],s=new Set,a=new Set,c=[];function l(m,d){if(d>r)return;if(a.has(m)){let h=c.indexOf(m);if(h!==-1){let f=c.slice(h).concat(m),y=f.indexOf(f.reduce((N,I)=>N<I?N:I)),C=[...f.slice(y,-1),...f.slice(0,y),f[y]],E=C.join(" -> ");u.has(E)||(u.add(E),o.push({path:C,kind:Py(C)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let h of p)l(h,d+1);c.pop(),a.delete(m)}let u=new Set;for(let m of i.keys())s.has(m)||l(m,0);return o.sort((m,d)=>m.kind!==d.kind?m.kind==="real"?-1:1:m.path.length-d.path.length),o}function Py(e){for(let r of e){let i=G(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Er(t)||Er(n)||ll(t,n)||ll(n,t)||ul(t,n)||ul(n,t)||G(t)==="entry"||G(n)==="entry"?"module-hierarchy":"real"}function ll(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 ul(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function wo(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new L(e);return Ie(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>Fy(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,m)=>m.score-u.score||m.fanIn-u.fanIn).slice(0,n)}function Fy(e,t,n){let r=new Set(Re(e,t,{limit:500,semantic:n}).map(o=>o.file)).size,i=new Set(he(e,t,{limit:500,semantic:n}).filter(o=>o.file!==t.relativePath).map(o=>`${o.symbol}|${o.file}`)).size;return{symbol:t.symbol,shortName:b(t.symbol),fanIn:r,fanOut:i,score:r*i,definedIn:t.relativePath}}function Pt(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new L(e),s=t.semantic!==!1,a=Ie(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let f of o.frameworkReferencedSymbolIds(a))l.add(f);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),m=a.filter(f=>!l.has(f.symbolId)).filter(f=>!u.has(f.symbolId)),d=o.sourceFallbackCallerFiles(m);for(let f of d.keys())l.add(f);let p=m.filter(f=>!l.has(f.symbolId)),h=o.symbolsWithNonSelfCallees(p,{additive:!0,semantic:s});for(let f of h)u.add(f);return p.filter(f=>!u.has(f.symbolId)).sort((f,y)=>B(y)-B(f)||f.relativePath.localeCompare(y.relativePath)||f.startLine-y.startLine).map(f=>({symbol:f.symbol,shortName:b(f.symbol),relativePath:f.relativePath,startLine:f.startLine,endLine:f.endLine,loc:B(f)}))}var ko={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"},Eo=new Map;for(let[e,t]of Object.entries(ko))Eo.set(t.toLowerCase(),Number(e));function Ay(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Eo.get(n);if(r!==void 0)return r;for(let[i,o]of Eo)if(i.includes(n))return o;return null}function Po(e,t,n={}){let{scope:r,limit:i=100}=n,o=Ay(t);return o===null?[]:ml(e,r).map(a=>({row:a,resolvedKind:dl(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:b(a.symbol),kind:c,kindName:ko[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function Fo(e,t={}){let n=new Map;for(let r of ml(e,t.scope)){let i=dl(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:ko[r]??"Unknown",count:i}))}function ml(e,t){return Oe(e,{scope:t}).map(Ty)}function Ty(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 dl(e){return e.kind!==null&&e.kind!==0?My(e.kind,e.symbol,e.documentation):Oy(e.symbol,e.documentation,e.enclosing_symbol)}function My(e,t,n){let r=(n??"").toLowerCase();if(ee(t)==="type"){if(r.includes("type "))return 76;if(r.includes("interface "))return 27;if(r.includes("struct "))return 68;if(r.includes("trait "))return 73;if(r.includes("class "))return 9}return e}function Oy(e,t,n){let r=Z(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=ee(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?ee(n):o?.suffix??null)==="type"?21:83}function Ao(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=oe(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,m=[],d=0;for(let v of o.keys()){if(c.has(v))continue;let w=[],V=(o.get(v)??new Set).values();for(c.set(v,d),l.set(v,d),d+=1,m.push(v),u.add(v),w.push({node:v,iter:V,pendingChild:null});w.length>0;){let O=w[w.length-1];if(O.pendingChild!==null){let Jt=O.pendingChild;O.pendingChild=null,l.set(O.node,Math.min(l.get(O.node),l.get(Jt)))}let Ae=O.iter.next();if(Ae.done){if(l.get(O.node)===c.get(O.node)){let Jt=[];for(;;){let lr=m.pop();if(u.delete(lr),Jt.push(lr),s.set(lr,a.length),lr===O.node)break}a.push(Jt)}w.pop();continue}let Te=Ae.value;if(c.has(Te))u.has(Te)&&l.set(O.node,Math.min(l.get(O.node),c.get(Te)));else{c.set(Te,d),l.set(Te,d),d+=1,m.push(Te),u.add(Te);let Jt=(o.get(Te)??new Set).values();O.pendingChild=Te,w.push({node:Te,iter:Jt,pendingChild:null})}}}let p=new Map,h=new Array(a.length);for(let v=0;v<a.length;v++)h[v]=a[v].length,p.set(v,new Set);for(let[v,w]of o){let V=s.get(v);for(let O of w){let Ae=s.get(O);Ae!==V&&p.get(V).add(Ae)}}let f=new Array(a.length),y=new Array(a.length);for(let v=0;v<a.length;v++){let w=[],V=0;for(let O of p.get(v)){let Ae=y[O];Ae>V&&(V=Ae,w=f[O])}f[v]=[v,...w],y[v]=h[v]+V}function C(v){return f[v]}let E=a.map(v=>[...v].sort()),N=new Set,I=[];for(let v=0;v<a.length;v++){let w=C(v),V=[];for(let Ae of w)V.push(...E[Ae]);if(V.length<i)continue;let O=V.join(" ");N.has(O)||(N.add(O),I.push({chain:V,depth:V.length}))}return I.sort((v,w)=>w.depth-v.depth),I.slice(0,n)}function To(e,t){let n=F(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
491
+ WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:b(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let m=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!m)break;i.push({symbol:m.symbol,shortName:b(m.symbol),depth:s}),o=m.enclosing_symbol,s++}if(i.length>1)return i;let c=Z(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let m=l.length-2,d=1;m>=0;m--,d++){let h=l.slice(0,m+1).map(f=>f.suffix==="method"?`${f.name}()`:f.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:d})}return u}function qn(e,t,n={}){let r=F(e,t);if(!r)return null;let i=n.semantic!==!1,o=Re(e,r,{limit:50,semantic:i}),s=dn(he(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:b(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file}))}}function Vn(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Wn(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function pl(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function Mo(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let o of i)n.set(o,(n.get(o)??0)+1);let r=new Map;for(let[i,o]of n)r.set(i,Math.log(t/o));return r}function $y(e){let t=[...e.values()].sort((r,i)=>r-i);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 fl(e,t,n){let r=Vn(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,o=0,s=0,a=new Set([...e,...t]);for(let p of a){let h=n.get(p)??0,f=e.has(p)?h:0,y=t.has(p)?h:0;i+=f*y,o+=f*f,s+=y*y}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?i/c:0,u=$y(n),m=[],d=[];for(let p of r)(n.get(p)??0)>=u?m.push(p):d.push(p);return m.sort((p,h)=>(n.get(h)??0)-(n.get(p)??0)),{similarity:l,significantShared:m,trivialShared:d}}function Gn(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=Hy(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Y(o.symbol))return[];let s=jy(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):Vy(e,t,{minSimilarity:r,limit:i})}function jy(e,t,n,r){let i=hl(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),o=Mo([t,...i].map(a=>a.callees)),s=[];for(let a of i){if(a.callees.size<3)continue;let c=gl(t,a,o,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});c&&s.push(c)}return s.sort((a,c)=>c.similarity-a.similarity),s}function gl(e,t,n,r){let{similarity:i,significantShared:o}=fl(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let s=Vn(e.callees,t.callees).size;if(o.length<r.requireSignificantShared&&s<r.requireSharedCount)return null;let a=o.length>0?o:[...Vn(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:b(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:b(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(b),uniqueToA:[...Wn(e.callees,t.callees)].map(b),uniqueToB:[...Wn(t.callees,e.callees)].map(b)}}function Qe(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=hl(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=Mo(c.map(f=>f.callees)),u=new Map;for(let f of c)for(let y of f.callees)u.set(y,(u.get(y)??0)+1);let m=Math.max(8,Math.ceil(Math.sqrt(c.length))),d=new Map;for(let f=0;f<c.length;f+=1)for(let y of c[f].callees){if((u.get(y)??0)>m)continue;let C=d.get(y);C||(C=[],d.set(y,C)),C.push(f)}let p=[],h=new Set;e:for(let f=0;f<c.length;f+=1){let y=c[f],C=new Set;for(let E of y.callees){let N=d.get(E);if(N)for(let I of N)I>f&&C.add(I)}for(let E of C){let N=`${f}|${E}`;if(h.has(N))continue;h.add(N);let I=c[E];if(s&&y.file===I.file)continue;if(y.paramCount>=0&&I.paramCount>=0){let w=Math.abs(y.paramCount-I.paramCount),V=Math.max(2,Math.ceil(Math.max(y.paramCount,I.paramCount)*.5));if(w>V)continue}let v=gl(y,I,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});if(v&&(p.push(v),p.length>r*5))break e}}return p.sort((f,y)=>y.similarity-f.similarity),p.slice(0,r)}var By=["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 Hy(e,t,n){let r=F(e,t),i=new L(e);if(!r)return null;let o=he(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:yl(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}function hl(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=new L(e),a=Ie(s.productionCallableDefinitions({scope:r,minLoc:5,excludeSymbol:i,sortByLocDesc:typeof o=="number"&&o>0}),o),c=s.calleeMap(a,{semantic:t.semantic!==!1});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:yl((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function yl(e){return new Set([...e].filter(t=>!qy(t)))}function qy(e){return By.some(t=>e.includes(t))}function Vy(e,t,n){let r=Wy(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[];for(let s of Gy(e)){if(s.symbol===r.symbol||s.tokens.size<3)continue;let a=Vn(r.tokens,s.tokens);if(a.size<2)continue;let c=new Set([...r.tokens,...s.tokens]),l=c.size>0?a.size/c.size:0;l<i||o.push({symbolA:r.symbol,shortNameA:b(r.symbol),fileA:r.file,symbolB:s.symbol,shortNameB:b(s.symbol),fileB:s.file,similarity:l,similarityBasis:"source-tokens",sharedCallees:[...a].sort(),uniqueToA:[...Wn(r.tokens,s.tokens)].sort(),uniqueToB:[...Wn(s.tokens,r.tokens)].sort()})}return o.sort((s,a)=>a.similarity-s.similarity||s.shortNameB.localeCompare(a.shortNameB)),o.slice(0,n.limit)}function Wy(e,t){let n=F(e,t);if(!n||!Y(n.symbol))return null;let r=Uy(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function Uy(e,t){let n=P(t.symbol),r=bl(e,t.relativePath,t.startLine,t.endLine,n),i=Sl(r,n);return i.size>0?i:null}function Gy(e){return new L(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Sl(bl(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function bl(e,t,n,r,i){let o=T(e,t);if(!o)return"";let s=o.split(`
492
492
  `);if(r>=n&&r-n<=12)return s.slice(n,r+1).join(`
493
- `);let a=[new RegExp(`\\bdef\\s+${Un(i)}\\b`),new RegExp(`\\bfun\\s+${Un(i)}\\b`),new RegExp(`\\bfn\\s+${Un(i)}\\b`),new RegExp(`\\bfunction\\s+${Un(i)}\\b`),new RegExp(`\\b${Un(i)}\\s*\\(`)],c=s.findIndex(l=>a.some(u=>u.test(l)));if(c>=0){let l=c;for(let u=c+1;u<s.length&&u<=c+8;u++){let m=s[u]??"";if(u>c&&Gy(m)||(l=u,m.trim()===""&&u>c+1))break}return s.slice(c,l+1).join(`
493
+ `);let a=[new RegExp(`\\bdef\\s+${Un(i)}\\b`),new RegExp(`\\bfun\\s+${Un(i)}\\b`),new RegExp(`\\bfn\\s+${Un(i)}\\b`),new RegExp(`\\bfunction\\s+${Un(i)}\\b`),new RegExp(`\\b${Un(i)}\\s*\\(`)],c=s.findIndex(l=>a.some(u=>u.test(l)));if(c>=0){let l=c;for(let u=c+1;u<s.length&&u<=c+8;u++){let m=s[u]??"";if(u>c&&zy(m)||(l=u,m.trim()===""&&u>c+1))break}return s.slice(c,l+1).join(`
494
494
  `)}return s.slice(n,Math.min(s.length,n+8)).join(`
495
- `)}function Sl(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"]),r=Uy(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=>!r.has(s));return new Set(o)}function Uy(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 Gy(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Un(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=Jy(e,{scope:i,minDeps:s}),l=[];if(o){let u=a.find(m=>m.file.includes(o));if(!u)return[];for(let m of a){if(m.file===u.file)continue;let d=xl(u,m,n,c);d&&l.push(d)}}else for(let u=0;u<a.length;u++){for(let m=u+1;m<a.length;m++){let d=xl(a[u],a[m],n,c);d&&l.push(d)}if(l.length>r*5)break}return l.sort((u,m)=>m.similarity-u.similarity),l.slice(0,r)}function Jy(e,t){let{scope:n,minDeps:r}=t,i=oe(e,n),{universalDeps:o,distinctiveDeps:s}=zy(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function zy(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function xl(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=pl(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:[...i],uniqueToA:a,uniqueToB:c}}function $o(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=oe(e,i),c=nb(a,o,s);if(c.length===0)return[];let l=Qy(c);return l.length<2?[]:tb(Xy(l,n,r),r)}function Qy(e){let t=Ky(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function Ky(e){let{nodeFreq:t,tailFreq:n}=Yy(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&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 Yy(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function Xy(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=Zy(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function Zy(e,t,n){if(!eb(e.filtered,t.filtered))return null;let{distance:r,ops:i}=rb(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:ib(e.original,t.original),commonSuffix:ob(e.original,t.original)}}function eb(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function tb(e,t){let n=[];for(let r of e)if(n.some(o=>Cl(r.chainA,o.chainA)&&Cl(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function nb(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Rl(e,o,[o],new Set([o]),t,n,r,500)}return r}function Rl(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),Rl(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function rb(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;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&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[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:i[n][r],ops:o}}function ib(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function ob(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function Cl(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function ve(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Ie(t,e.scanLimit),r=e.prepare?.(n)??void 0,i=[];for(let o of n){let s=e.evaluate(o,r);s&&i.push(s)}return e.orderResults&&i.sort(e.orderResults),typeof e.limit=="number"?i.slice(0,e.limit):i}function Pt(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new L(e);return ve({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>sb(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function sb(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=ab(r,t),o=cb(r,i);if(o.length<2)return null;let s=lb(o,i);return s.length===0?null:{symbol:e.symbol,shortName:b(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:B(e),totalCallees:r.size,clusters:s}}function ab(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];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 cb(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];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)}}r.push(o)}return r}function lb(e,t){return e.filter(n=>n.size>=3).map(n=>ub(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function ub(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(b),isolation:s}}function Jn(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=F(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let m=[];for(let d of l)for(let p of mb(e,d,i)){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&&m.push(p.symbolMatch)}l=m}return s.sort((u,m)=>u.depth-m.depth||u.file.localeCompare(m.file)),s}function mb(e,t,n){let r=Re(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),i=new Set(r.map(l=>l.file)),o=[];for(let l of db(e,t,n)){if(i.has(l))continue;let u=H(e,l),m=u.length>0?be(u,u[0].startLine):null;o.push({symbol:m?.symbol??l,file:l})}let s=[...r,...o],a=[],c=new Set;for(let l of s){let u=tn(e,l.symbol);if(!u){let d=`${l.file}|${l.symbol}`;if(c.has(d))continue;c.add(d),a.push({symbolId:null,symbol:l.symbol,shortName:b(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!pb(u.symbol))continue;let m=`${u.symbolId}|${u.relativePath}`;c.has(m)||(c.add(m),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:b(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function db(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
495
+ `)}function Sl(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"]),r=Jy(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=>!r.has(s));return new Set(o)}function Jy(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 zy(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Un(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=Qy(e,{scope:i,minDeps:s}),l=[];if(o){let u=a.find(m=>m.file.includes(o));if(!u)return[];for(let m of a){if(m.file===u.file)continue;let d=xl(u,m,n,c);d&&l.push(d)}}else for(let u=0;u<a.length;u++){for(let m=u+1;m<a.length;m++){let d=xl(a[u],a[m],n,c);d&&l.push(d)}if(l.length>r*5)break}return l.sort((u,m)=>m.similarity-u.similarity),l.slice(0,r)}function Qy(e,t){let{scope:n,minDeps:r}=t,i=oe(e,n),{universalDeps:o,distinctiveDeps:s}=Ky(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function Ky(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function xl(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=pl(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:[...i],uniqueToA:a,uniqueToB:c}}function $o(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=oe(e,i),c=ib(a,o,s);if(c.length===0)return[];let l=Yy(c);return l.length<2?[]:rb(eb(l,n,r),r)}function Yy(e){let t=Xy(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function Xy(e){let{nodeFreq:t,tailFreq:n}=Zy(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&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 Zy(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function eb(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=tb(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function tb(e,t,n){if(!nb(e.filtered,t.filtered))return null;let{distance:r,ops:i}=ob(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:sb(e.original,t.original),commonSuffix:ab(e.original,t.original)}}function nb(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function rb(e,t){let n=[];for(let r of e)if(n.some(o=>Cl(r.chainA,o.chainA)&&Cl(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function ib(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Rl(e,o,[o],new Set([o]),t,n,r,500)}return r}function Rl(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),Rl(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function ob(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;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&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[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:i[n][r],ops:o}}function sb(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function ab(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function Cl(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function ve(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Ie(t,e.scanLimit),r=e.prepare?.(n)??void 0,i=[];for(let o of n){let s=e.evaluate(o,r);s&&i.push(s)}return e.orderResults&&i.sort(e.orderResults),typeof e.limit=="number"?i.slice(0,e.limit):i}function Ft(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new L(e);return ve({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>cb(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function cb(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=lb(r,t),o=ub(r,i);if(o.length<2)return null;let s=mb(o,i);return s.length===0?null:{symbol:e.symbol,shortName:b(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:B(e),totalCallees:r.size,clusters:s}}function lb(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];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 ub(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];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)}}r.push(o)}return r}function mb(e,t){return e.filter(n=>n.size>=3).map(n=>db(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function db(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(b),isolation:s}}function Jn(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=F(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let m=[];for(let d of l)for(let p of pb(e,d,i)){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&&m.push(p.symbolMatch)}l=m}return s.sort((u,m)=>u.depth-m.depth||u.file.localeCompare(m.file)),s}function pb(e,t,n){let r=Re(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),i=new Set(r.map(l=>l.file)),o=[];for(let l of fb(e,t,n)){if(i.has(l))continue;let u=H(e,l),m=u.length>0?be(u,u[0].startLine):null;o.push({symbol:m?.symbol??l,file:l})}let s=[...r,...o],a=[],c=new Set;for(let l of s){let u=tn(e,l.symbol);if(!u){let d=`${l.file}|${l.symbol}`;if(c.has(d))continue;c.add(d),a.push({symbolId:null,symbol:l.symbol,shortName:b(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!gb(u.symbol))continue;let m=`${u.symbolId}|${u.relativePath}`;c.has(m)||(c.add(m),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:b(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function fb(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
496
496
  FROM mentions m
497
497
  JOIN chunks c ON m.chunk_id = c.id
498
498
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -500,40 +500,40 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
500
500
  AND m.role != 1
501
501
  AND c.document_id != ?
502
502
  ${e.pathExclusionsFor("consumer_d")}
503
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function pb(e){let t=ee(e);return t==="method"||t==="type"||e.endsWith("().")}function zn(e,t,n={}){let r=me(e,t);if(!r)return null;let i=fb(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=gb(e,i.relative_path),c=n.semantic===!1?new Map:un(e,a);for(let l of a){let u=hb(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:b(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:yb(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function fb(e,t){return e.get(`SELECT id, relative_path FROM documents
503
+ ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function gb(e){let t=ee(e);return t==="method"||t==="type"||e.endsWith("().")}function zn(e,t,n={}){let r=me(e,t);if(!r)return null;let i=hb(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=yb(e,i.relative_path),c=n.semantic===!1?new Map:un(e,a);for(let l of a){let u=bb(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:b(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:Sb(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function hb(e,t){return e.get(`SELECT id, relative_path FROM documents
504
504
  WHERE relative_path = ?
505
505
  ${e.pathExclusionsFor("documents")}
506
- LIMIT 1`,t)??null}function gb(e,t){return new L(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function hb(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
506
+ LIMIT 1`,t)??null}function yb(e,t){return new L(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function bb(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
507
507
  FROM mentions m
508
508
  JOIN chunks c ON m.chunk_id = c.id
509
509
  JOIN documents consumer_d ON consumer_d.id = c.document_id
510
510
  WHERE m.symbol_id = ?
511
511
  AND m.role != 1
512
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function yb(e){return e>10?"high":e>0?"medium":"low"}function Bo(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new L(e),a=bb(e,n,r,o),c=new jo;for(let f of a)c.add(f);let l=[],u=[];a.length>0&&l.push(Il(e,0,a,c));let m=a.map(f=>f.definition).filter(f=>f!==null),d=new Set(a.map(f=>f.symbol));for(let f=1;f<=i&&m.length>0;f++){let y=s.calleeMap(m,{semantic:!1}),C=new Set;for(let N of m)for(let I of y.get(N.symbolId)??[])d.has(I.symbol)||C.add(I.symbol);let E=[];for(let N of C){d.add(N);let I=vl(e,N);if(!I||e.isIgnored(I.relativePath)||le(e,I.relativePath)||ne(e,I.symbol,I.relativePath)||s.fileKind(I.relativePath)==="test"||s.hasSuppressionComment(I))continue;let v=xb(e,I,c);v.removable?E.push(Sb(I,"cascade")):v.blockingFiles.length>0&&u.push({shortName:b(I.symbol),file:I.relativePath,blockingFiles:v.blockingFiles.slice(0,3)})}if(E.length===0)break;for(let N of E)c.add(N);l.push(Il(e,f,E,c)),m=E.map(N=>N.definition).filter(N=>N!==null)}let p=l.reduce((f,y)=>f+y.loc,0),h=l.reduce((f,y)=>f+y.entries.length,0);return{batches:l,totalSymbols:h,totalLoc:p,blocked:u}}function bb(e,t,n,r){let i=Je(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(le(e,s.relativePath)||ne(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:vl(e,s.symbol)}));return o}function Sb(e,t){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function vl(e,t){let n=e.get(`SELECT d.relative_path
512
+ AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function Sb(e){return e>10?"high":e>0?"medium":"low"}function Bo(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new L(e),a=xb(e,n,r,o),c=new jo;for(let f of a)c.add(f);let l=[],u=[];a.length>0&&l.push(Il(e,0,a,c));let m=a.map(f=>f.definition).filter(f=>f!==null),d=new Set(a.map(f=>f.symbol));for(let f=1;f<=i&&m.length>0;f++){let y=s.calleeMap(m,{semantic:!1}),C=new Set;for(let N of m)for(let I of y.get(N.symbolId)??[])d.has(I.symbol)||C.add(I.symbol);let E=[];for(let N of C){d.add(N);let I=vl(e,N);if(!I||e.isIgnored(I.relativePath)||le(e,I.relativePath)||ne(e,I.symbol,I.relativePath)||s.fileKind(I.relativePath)==="test"||s.hasSuppressionComment(I))continue;let v=Rb(e,I,c);v.removable?E.push(Cb(I,"cascade")):v.blockingFiles.length>0&&u.push({shortName:b(I.symbol),file:I.relativePath,blockingFiles:v.blockingFiles.slice(0,3)})}if(E.length===0)break;for(let N of E)c.add(N);l.push(Il(e,f,E,c)),m=E.map(N=>N.definition).filter(N=>N!==null)}let p=l.reduce((f,y)=>f+y.loc,0),h=l.reduce((f,y)=>f+y.entries.length,0);return{batches:l,totalSymbols:h,totalLoc:p,blocked:u}}function xb(e,t,n,r){let i=ze(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(le(e,s.relativePath)||ne(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:vl(e,s.symbol)}));return o}function Cb(e,t){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function vl(e,t){let n=e.get(`SELECT d.relative_path
513
513
  FROM global_symbols gs
514
514
  JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
515
515
  JOIN documents d ON d.id = der.document_id
516
516
  WHERE gs.symbol = ?
517
- LIMIT 1`,t);return n?H(e,n.relative_path).find(r=>r.symbol===t)??null:null}function xb(e,t,n){let r=wt(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function Il(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=H(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var jo=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 r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{existsSync as Hl}from"fs";import{execFileSync as Cb}from"child_process";var Nl=2e3,Rb=50,Ib=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,Ur=re("git-commit-history",{clearGroups:["whole-project"]});function Ft(e){let t=Ho(e.config.projectRoot);if(!t)return null;let n=Ur.has(e)?Ur.get(e,()=>({head:"",history:null})):null;return n&&n.head===t?n.history:(Ur.invalidate(e),Ur.get(e,()=>({head:t,history:vb(e.config.projectRoot,t)})).history)}function Ho(e){try{return zr(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function zr(e,t){return Cb("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function vb(e,t){let n;try{n=zr(e,["log","--no-merges","--name-only","-n",String(Nl),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=[],i=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
517
+ LIMIT 1`,t);return n?H(e,n.relative_path).find(r=>r.symbol===t)??null:null}function Rb(e,t,n){let r=Et(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function Il(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=H(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var jo=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 r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{existsSync as Hl}from"fs";import{execFileSync as Ib}from"child_process";var Nl=2e3,vb=50,Db=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,Ur=re("git-commit-history",{clearGroups:["whole-project"]});function At(e){let t=Ho(e.config.projectRoot);if(!t)return null;let n=Ur.has(e)?Ur.get(e,()=>({head:"",history:null})):null;return n&&n.head===t?n.history:(Ur.invalidate(e),Ur.get(e,()=>({head:t,history:Nb(e.config.projectRoot,t)})).history)}function Ho(e){try{return zr(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function zr(e,t){return Ib("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function Nb(e,t){let n;try{n=zr(e,["log","--no-merges","--name-only","-n",String(Nl),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=[],i=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
518
518
  `),a=s>=0?o.slice(0,s):o,[c,l,u]=a.split("\0");if(!c||!l)continue;let m=s>=0?o.slice(s+1).split(`
519
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(m.length>Rb){i+=1;continue}r.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:m})}return{head:t,commits:r,skippedBulkCommits:i}}function Db(e){return Ib.test(e.subject)}function Qr(e){let t=Ft(e);if(!t)return null;let n=new Map;for(let r of t.commits){let i=Db(r);for(let o of r.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,i&&(s.fixChanges+=1),r.timestamp>s.lastChangedAt&&(s.lastChangedAt=r.timestamp),n.set(o,s)}}return n}function Ll(e){let t=Ft(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(r=>r.files.length).filter(r=>r>0).sort((r,i)=>r-i);return n.length===0?null:{medianFilesPerCommit:Dl(n,.5),p90FilesPerCommit:Dl(n,.9),commitsAnalyzed:n.length}}function Dl(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var Gr=re("git-tracked-files",{clearGroups:["whole-project"]});function qo(e){let t=Ho(e.config.projectRoot);if(!t)return null;let n=Gr.has(e)?Gr.get(e,()=>({head:"",files:null})):null;return n&&n.head===t?n.files:(Gr.invalidate(e),Gr.get(e,()=>{try{let r=zr(e.config.projectRoot,["ls-files"]);return{head:t,files:new Set(r.split(`
520
- `).map(i=>i.trim()).filter(i=>i!==""))}}catch{return{head:t,files:null}}}).files)}var Jr=re("git-file-adds",{clearGroups:["whole-project"]});function _l(e){let t=Ho(e.config.projectRoot);if(!t)return null;let n=Jr.has(e)?Jr.get(e,()=>({head:"",adds:null})):null;return n&&n.head===t?n.adds:(Jr.invalidate(e),Jr.get(e,()=>({head:t,adds:Nb(e.config.projectRoot)})).adds)}function Nb(e){let t;try{t=zr(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(Nl),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,r=-1;for(let i of t.split("")){if(i.trim()==="")continue;r+=1;let o=i.indexOf(`
519
+ `).map(d=>d.trim()).filter(d=>d!==""):[];if(m.length>vb){i+=1;continue}r.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:m})}return{head:t,commits:r,skippedBulkCommits:i}}function Lb(e){return Db.test(e.subject)}function Qr(e){let t=At(e);if(!t)return null;let n=new Map;for(let r of t.commits){let i=Lb(r);for(let o of r.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,i&&(s.fixChanges+=1),r.timestamp>s.lastChangedAt&&(s.lastChangedAt=r.timestamp),n.set(o,s)}}return n}function Ll(e){let t=At(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(r=>r.files.length).filter(r=>r>0).sort((r,i)=>r-i);return n.length===0?null:{medianFilesPerCommit:Dl(n,.5),p90FilesPerCommit:Dl(n,.9),commitsAnalyzed:n.length}}function Dl(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var Gr=re("git-tracked-files",{clearGroups:["whole-project"]});function qo(e){let t=Ho(e.config.projectRoot);if(!t)return null;let n=Gr.has(e)?Gr.get(e,()=>({head:"",files:null})):null;return n&&n.head===t?n.files:(Gr.invalidate(e),Gr.get(e,()=>{try{let r=zr(e.config.projectRoot,["ls-files"]);return{head:t,files:new Set(r.split(`
520
+ `).map(i=>i.trim()).filter(i=>i!==""))}}catch{return{head:t,files:null}}}).files)}var Jr=re("git-file-adds",{clearGroups:["whole-project"]});function _l(e){let t=Ho(e.config.projectRoot);if(!t)return null;let n=Jr.has(e)?Jr.get(e,()=>({head:"",adds:null})):null;return n&&n.head===t?n.adds:(Jr.invalidate(e),Jr.get(e,()=>({head:t,adds:_b(e.config.projectRoot)})).adds)}function _b(e){let t;try{t=zr(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(Nl),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,r=-1;for(let i of t.split("")){if(i.trim()==="")continue;r+=1;let o=i.indexOf(`
521
521
  `),s=o>=0?i.slice(0,o):i,[,a]=s.split("\0"),c=Number(a)||0;if(!(o<0))for(let l of i.slice(o+1).split(`
522
- `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function Kr(e,t={}){let{minTogether:n=4,minConfidence:r=.6}=t,i=Ft(e);if(!i)return null;let o=new Map,s=new Map;for(let c of i.commits){let l=[...new Set(c.files)].sort();for(let u of l)o.set(u,(o.get(u)??0)+1);for(let u=0;u<l.length;u++)for(let m=u+1;m<l.length;m++){let d=`${l[u]}\0${l[m]}`;s.set(d,(s.get(d)??0)+1)}}let a=[];for(let[c,l]of s){if(l<n)continue;let[u,m]=c.split("\0"),d=o.get(u)??l,p=o.get(m)??l,h=Math.max(l/d,l/p);h<r||a.push({fileA:u,fileB:m,together:l,confidence:h,changesA:d,changesB:p})}return a.sort((c,l)=>l.together-c.together||l.confidence-c.confidence||c.fileA.localeCompare(l.fileA)),a}import{existsSync as Lb}from"fs";import{join as _b}from"path";function Wo(e){return Vo.test(e)}var Vo=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules)\//i;function Tt(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30}=n,s=Ft(e),a=t!==void 0,c=Kr(e,{minTogether:a?Math.min(r,2):r,minConfidence:a?0:i});if(!s||!c)return{available:!1,commitsAnalyzed:0,findings:[]};let l=oe(e),u=n.includeLinked===!0||a,m=[];for(let d of c){if(Vo.test(d.fileA)||Vo.test(d.fileB)||!wl(e,d.fileA)||!wl(e,d.fileB)||a&&!d.fileA.includes(t)&&!d.fileB.includes(t)||!a&&(G(d.fileA)==="test"||G(d.fileB)==="test"||wb(d.fileA,d.fileB)))continue;let p=Eb(l,d.fileA,d.fileB);if(!(!u&&p)&&(m.push({...d,structurallyLinked:p}),m.length>=o))break}return{available:!0,commitsAnalyzed:s.commits.length,findings:m}}function wl(e,t){return Lb(_b(e.config.projectRoot,t))}function wb(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function Eb(e,t,n){return e.get(t)?.has(n)===!0||e.get(n)?.has(t)===!0}import{execFileSync as Uo}from"child_process";function pn(e,t={}){let n=fn(e,t);return n.note?kb(n.note,n.changedFileLines):n.changedFiles.length===0?Pb(n.changedFileLines):Xr(n.changedFiles,[Yr(e,n.changedFiles,n.changedFiles)])}function fn(e,t={}){let{base:n="HEAD"}=t;try{let r=Fb(e.config.projectRoot,n);return{changedFileLines:r,changedFiles:Tb(e,r),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],note:"Unable to compute git diff."}}}function Yr(e,t,n){let r=new L(e),i=new Set(n),o=[],s=new Map,a=t.flatMap(l=>r.definitionsForFile(l)).filter(jb).sort((l,u)=>l.relativePath.localeCompare(u.relativePath)||l.startLine-u.startLine),c=un(e,a);for(let l of a)Ab(e,l,n,i,o,s,c.get(l.symbolId)??new Set);return{changedSymbols:o,consumerEntries:[...s.entries()].map(([l,u])=>({file:l,symbols:[...u].sort()}))}}function Xr(e,t){let n=new Map,r=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 i=$b(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function kb(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function Pb(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 Fb(e,t){let n=Uo("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=Uo("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=Uo("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
523
- `)).map(o=>o.trim()).filter(o=>o.length>0))]}function Tb(e,t){let n=[];for(let r of t){let i=e.get(`SELECT relative_path FROM documents
522
+ `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function Kr(e,t={}){let{minTogether:n=4,minConfidence:r=.6}=t,i=At(e);if(!i)return null;let o=new Map,s=new Map;for(let c of i.commits){let l=[...new Set(c.files)].sort();for(let u of l)o.set(u,(o.get(u)??0)+1);for(let u=0;u<l.length;u++)for(let m=u+1;m<l.length;m++){let d=`${l[u]}\0${l[m]}`;s.set(d,(s.get(d)??0)+1)}}let a=[];for(let[c,l]of s){if(l<n)continue;let[u,m]=c.split("\0"),d=o.get(u)??l,p=o.get(m)??l,h=Math.max(l/d,l/p);h<r||a.push({fileA:u,fileB:m,together:l,confidence:h,changesA:d,changesB:p})}return a.sort((c,l)=>l.together-c.together||l.confidence-c.confidence||c.fileA.localeCompare(l.fileA)),a}import{existsSync as wb}from"fs";import{join as Eb}from"path";function Wo(e){return Vo.test(e)}var Vo=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules)\//i;function Tt(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30}=n,s=At(e),a=t!==void 0,c=Kr(e,{minTogether:a?Math.min(r,2):r,minConfidence:a?0:i});if(!s||!c)return{available:!1,commitsAnalyzed:0,findings:[]};let l=oe(e),u=n.includeLinked===!0||a,m=[];for(let d of c){if(Vo.test(d.fileA)||Vo.test(d.fileB)||!wl(e,d.fileA)||!wl(e,d.fileB)||a&&!d.fileA.includes(t)&&!d.fileB.includes(t)||!a&&(G(d.fileA)==="test"||G(d.fileB)==="test"||kb(d.fileA,d.fileB)))continue;let p=Pb(l,d.fileA,d.fileB);if(!(!u&&p)&&(m.push({...d,structurallyLinked:p}),m.length>=o))break}return{available:!0,commitsAnalyzed:s.commits.length,findings:m}}function wl(e,t){return wb(Eb(e.config.projectRoot,t))}function kb(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function Pb(e,t,n){return e.get(t)?.has(n)===!0||e.get(n)?.has(t)===!0}import{execFileSync as Uo}from"child_process";function pn(e,t={}){let n=fn(e,t);return n.note?Fb(n.note,n.changedFileLines):n.changedFiles.length===0?Ab(n.changedFileLines):Xr(n.changedFiles,[Yr(e,n.changedFiles,n.changedFiles)])}function fn(e,t={}){let{base:n="HEAD"}=t;try{let r=Tb(e.config.projectRoot,n);return{changedFileLines:r,changedFiles:Mb(e,r),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],note:"Unable to compute git diff."}}}function Yr(e,t,n){let r=new L(e),i=new Set(n),o=[],s=new Map,a=t.flatMap(l=>r.definitionsForFile(l)).filter(Hb).sort((l,u)=>l.relativePath.localeCompare(u.relativePath)||l.startLine-u.startLine),c=un(e,a);for(let l of a)Ob(e,l,n,i,o,s,c.get(l.symbolId)??new Set);return{changedSymbols:o,consumerEntries:[...s.entries()].map(([l,u])=>({file:l,symbols:[...u].sort()}))}}function Xr(e,t){let n=new Map,r=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 i=Bb(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function Fb(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function Ab(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 Tb(e,t){let n=Uo("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=Uo("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=Uo("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
523
+ `)).map(o=>o.trim()).filter(o=>o.length>0))]}function Mb(e,t){let n=[];for(let r of t){let i=e.get(`SELECT relative_path FROM documents
524
524
  WHERE relative_path LIKE ?
525
- LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function Ab(e,t,n,r,i,o,s){let a=Math.max(Mb(e,t.symbolId),s.size);if(!Bb(t,a))return;let c=b(t.symbol);i.push({symbol:t.symbol,shortName:c,file:t.relativePath,fanIn:a});for(let l of Ob(e,t.symbolId,n))El(e,r,o,l,c);for(let l of s)El(e,r,o,l,c)}function Mb(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS fan_in
525
+ LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function Ob(e,t,n,r,i,o,s){let a=Math.max($b(e,t.symbolId),s.size);if(!qb(t,a))return;let c=b(t.symbol);i.push({symbol:t.symbol,shortName:c,file:t.relativePath,fanIn:a});for(let l of jb(e,t.symbolId,n))El(e,r,o,l,c);for(let l of s)El(e,r,o,l,c)}function $b(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS fan_in
526
526
  FROM mentions m
527
527
  JOIN chunks c ON m.chunk_id = c.id
528
528
  WHERE m.symbol_id = ?
529
- AND m.role != 1`,t)?.fan_in??0}function Ob(e,t,n){return n.length===0?[]:e.all(`SELECT DISTINCT ref_d.relative_path
529
+ AND m.role != 1`,t)?.fan_in??0}function jb(e,t,n){return n.length===0?[]:e.all(`SELECT DISTINCT ref_d.relative_path
530
530
  FROM mentions m
531
531
  JOIN chunks c ON m.chunk_id = c.id
532
532
  JOIN documents ref_d ON c.document_id = ref_d.id
533
533
  WHERE m.symbol_id = ?
534
534
  AND m.role != 1
535
535
  AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
536
- ${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function El(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function $b(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function jb(e){return!(it(e.symbol)||e.parentTypeName!==null&&!ie(e.symbol))}function Bb(e,t){return ie(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}import{existsSync as kl,readFileSync as Hb}from"fs";import{join as Go}from"path";var Qn=/\.(?:md|mdx|rst|txt)$/i;function Pl(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var qb=3,Vb=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function Jo(e,t={}){let{doc:n,limit:r=20,minCoupling:i=qb}=t,o=Ft(e);if(!o)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let s=qo(e)??new Set,a=new Map,c=new Map,l=new Set;for(let p of o.commits){let h=[...new Set(p.files)],f=h.filter(C=>Qn.test(C)),y=h.filter(C=>!Qn.test(C));for(let C of h){l.add(C);let E=a.get(C)??[];E.push(p.timestamp),a.set(C,E)}for(let C of f){let E=c.get(C);E||(E=new Map,c.set(C,E));for(let N of y)E.set(N,(E.get(N)??0)+1)}}let u=[...s].filter(p=>Qn.test(p)),m=Tl(s),d=[];for(let p of u){if(n!==void 0&&!p.includes(n)||n===void 0&&Pl(p)||!kl(Go(e.config.projectRoot,p)))continue;let h=Math.max(0,...a.get(p)??[]),f=new Map,{resolved:y,broken:C}=Al(e,p,s,m,l);for(let N of y){if(N===p||Qn.test(N))continue;let I=(a.get(N)??[]).filter(v=>v>h).length;I!==0&&f.set(N,{file:N,evidence:"reference",coChanges:0,changesSinceDocUpdate:I})}for(let[N,I]of c.get(p)??[]){if(I<i||!s.has(N))continue;let v=(a.get(N)??[]).filter(V=>V>h).length;if(v===0)continue;let w=f.get(N);w?(w.evidence="both",w.coChanges=I):f.set(N,{file:N,evidence:"co-change",coChanges:I,changesSinceDocUpdate:v})}if(f.size===0&&C.length===0)continue;let E=[...f.values()].sort((N,I)=>I.changesSinceDocUpdate-N.changesSinceDocUpdate);d.push({doc:p,docLastChangedAt:h,staleness:E.reduce((N,I)=>N+I.changesSinceDocUpdate,0)+C.length*10,subjects:E.slice(0,8),brokenReferences:C})}return d.sort((p,h)=>h.staleness-p.staleness),{available:!0,commitsAnalyzed:o.commits.length,docsScanned:u.length,findings:d.slice(0,r)}}function Fl(e,t){let n=qo(e)??new Set,r=Tl(n),i=[];for(let o of n){if(!Qn.test(o)||Pl(o)||!kl(Go(e.config.projectRoot,o)))continue;let{resolved:s}=Al(e,o,n,r,new Set),a=[...s].filter(c=>t.has(c));a.length>0&&i.push({doc:o,cited:a.sort()})}return i}function Tl(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function Al(e,t,n,r,i){let o=new Set,s=new Set,a;try{a=Hb(Go(e.config.projectRoot,t),"utf-8")}catch{return{resolved:o,broken:[]}}for(let c of a.matchAll(Vb)){let l=c[0].replace(/^\.?\//,"");if(n.has(l)){o.add(l);continue}let u=r.get(l);if(u&&u.length===1){o.add(u[0]);continue}u&&u.length>1||i.has(l)&&s.add(l)}return{resolved:o,broken:[...s]}}import{existsSync as qS,readFileSync as VS,writeFileSync as WS}from"fs";import{isAbsolute as US,join as GS}from"path";import Kn from"path";function At(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 zo(e,t){if(e===t)return"ok";let n=Zr(e),r=Zr(t);return n&&r?Wb(n,r)?"ok":"violation":Ub(e,t)}function Ml(e,t){let n=Zr(At(e)),r=Zr(At(t));return!!n&&!!r}function Zr(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function Wb(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 Ub(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 Mt(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,s=new L(e).fileDependencyGraph(n),a=Xb(e,n);return Qb([...Gb(e,s,a,{semantic:i}),...Jb(s),...zb(s,r)])}function Gb(e,t,n,r){let i=[];for(let[o,s]of t){if(Qe(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!Qe(c)&&!a.has(c)){if(r.semantic&&iS(e,o,c)||oS(e,o,c)||sS(e,o,c)||rS(c)||cS(e,o,c)||aS(c))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c})}}return i}function Jb(e){let t=[],n=nS(e);for(let[r,i]of e){if(Qe(r))continue;let o=At(r);for(let s of i){if(Qe(s))continue;let a=At(s);if(o===a)continue;(zo(o,a)??n.get(`${o}->${a}`))==="violation"&&t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`})}}return t}function zb(e,t){let n=[];for(let[r,i]of Kb(e)){let o=i.filter(a=>!Qe(a));if(o.length<t)continue;let s=Yb(e,o);for(let a of o)for(let c of e.get(a)??[])Qe(c)||(s.get(c)??0)===1&&Kn.dirname(c)!==r&&Kn.dirname(c)!==Kn.dirname(r)&&(Ml(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c}))}return n}function Qb(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 Kb(e){let t=new Map;for(let n of e.keys()){let r=Kn.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function Yb(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Qe(i)||n.set(i,(n.get(i)??0)+1);return n}function Xb(e,t){let n=new Map;return Zb(e,n,t),tS(e,n),n}function Zb(e,t,n){for(let r of eS(e,n))Ol(e,t,r.from_file,r.to_file)}function eS(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
536
+ ${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function El(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function Bb(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function Hb(e){return!(ot(e.symbol)||e.parentTypeName!==null&&!ie(e.symbol))}function qb(e,t){return ie(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}import{existsSync as kl,readFileSync as Vb}from"fs";import{join as Go}from"path";var Qn=/\.(?:md|mdx|rst|txt)$/i;function Pl(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var Wb=3,Ub=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function Jo(e,t={}){let{doc:n,limit:r=20,minCoupling:i=Wb}=t,o=At(e);if(!o)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let s=qo(e)??new Set,a=new Map,c=new Map,l=new Set;for(let p of o.commits){let h=[...new Set(p.files)],f=h.filter(C=>Qn.test(C)),y=h.filter(C=>!Qn.test(C));for(let C of h){l.add(C);let E=a.get(C)??[];E.push(p.timestamp),a.set(C,E)}for(let C of f){let E=c.get(C);E||(E=new Map,c.set(C,E));for(let N of y)E.set(N,(E.get(N)??0)+1)}}let u=[...s].filter(p=>Qn.test(p)),m=Al(s),d=[];for(let p of u){if(n!==void 0&&!p.includes(n)||n===void 0&&Pl(p)||!kl(Go(e.config.projectRoot,p)))continue;let h=Math.max(0,...a.get(p)??[]),f=new Map,{resolved:y,broken:C}=Tl(e,p,s,m,l);for(let N of y){if(N===p||Qn.test(N))continue;let I=(a.get(N)??[]).filter(v=>v>h).length;I!==0&&f.set(N,{file:N,evidence:"reference",coChanges:0,changesSinceDocUpdate:I})}for(let[N,I]of c.get(p)??[]){if(I<i||!s.has(N))continue;let v=(a.get(N)??[]).filter(V=>V>h).length;if(v===0)continue;let w=f.get(N);w?(w.evidence="both",w.coChanges=I):f.set(N,{file:N,evidence:"co-change",coChanges:I,changesSinceDocUpdate:v})}if(f.size===0&&C.length===0)continue;let E=[...f.values()].sort((N,I)=>I.changesSinceDocUpdate-N.changesSinceDocUpdate);d.push({doc:p,docLastChangedAt:h,staleness:E.reduce((N,I)=>N+I.changesSinceDocUpdate,0)+C.length*10,subjects:E.slice(0,8),brokenReferences:C})}return d.sort((p,h)=>h.staleness-p.staleness),{available:!0,commitsAnalyzed:o.commits.length,docsScanned:u.length,findings:d.slice(0,r)}}function Fl(e,t){let n=qo(e)??new Set,r=Al(n),i=[];for(let o of n){if(!Qn.test(o)||Pl(o)||!kl(Go(e.config.projectRoot,o)))continue;let{resolved:s}=Tl(e,o,n,r,new Set),a=[...s].filter(c=>t.has(c));a.length>0&&i.push({doc:o,cited:a.sort()})}return i}function Al(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function Tl(e,t,n,r,i){let o=new Set,s=new Set,a;try{a=Vb(Go(e.config.projectRoot,t),"utf-8")}catch{return{resolved:o,broken:[]}}for(let c of a.matchAll(Ub)){let l=c[0].replace(/^\.?\//,"");if(n.has(l)){o.add(l);continue}let u=r.get(l);if(u&&u.length===1){o.add(u[0]);continue}u&&u.length>1||i.has(l)&&s.add(l)}return{resolved:o,broken:[...s]}}import{existsSync as WS,readFileSync as US,writeFileSync as GS}from"fs";import{isAbsolute as JS,join as zS}from"path";import Kn from"path";function Mt(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 zo(e,t){if(e===t)return"ok";let n=Zr(e),r=Zr(t);return n&&r?Gb(n,r)?"ok":"violation":Jb(e,t)}function Ml(e,t){let n=Zr(Mt(e)),r=Zr(Mt(t));return!!n&&!!r}function Zr(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function Gb(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 Jb(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 Ot(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,s=new L(e).fileDependencyGraph(n),a=eS(e,n);return Yb([...zb(e,s,a,{semantic:i}),...Qb(s),...Kb(s,r)])}function zb(e,t,n,r){let i=[];for(let[o,s]of t){if(Ke(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!Ke(c)&&!a.has(c)){if(r.semantic&&sS(e,o,c)||aS(e,o,c)||cS(e,o,c)||oS(c)||uS(e,o,c)||lS(c))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c})}}return i}function Qb(e){let t=[],n=iS(e);for(let[r,i]of e){if(Ke(r))continue;let o=Mt(r);for(let s of i){if(Ke(s))continue;let a=Mt(s);if(o===a)continue;(zo(o,a)??n.get(`${o}->${a}`))==="violation"&&t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`})}}return t}function Kb(e,t){let n=[];for(let[r,i]of Xb(e)){let o=i.filter(a=>!Ke(a));if(o.length<t)continue;let s=Zb(e,o);for(let a of o)for(let c of e.get(a)??[])Ke(c)||(s.get(c)??0)===1&&Kn.dirname(c)!==r&&Kn.dirname(c)!==Kn.dirname(r)&&(Ml(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c}))}return n}function Yb(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 Xb(e){let t=new Map;for(let n of e.keys()){let r=Kn.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function Zb(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Ke(i)||n.set(i,(n.get(i)??0)+1);return n}function eS(e,t){let n=new Map;return tS(e,n,t),rS(e,n),n}function tS(e,t,n){for(let r of nS(e,n))Ol(e,t,r.from_file,r.to_file)}function nS(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
537
537
  FROM mentions m
538
538
  JOIN chunks c ON m.chunk_id = c.id
539
539
  JOIN documents d1 ON c.document_id = d1.id
@@ -549,25 +549,25 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
549
549
  WHERE d1.id != d2.id
550
550
  AND m.role != 1
551
551
  ${e.pathExclusionsFor("d1","d2")}
552
- ${n}`)}function tS(e,t){new L(e).scanSourceReferences({paths:T(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||Ol(e,t,r.sourceFile,r.target.relativePath))})}function Ol(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function nS(e){let t=new Map;for(let[r,i]of e){if(Qe(r))continue;let o=At(r);for(let s of i){if(Qe(s))continue;let a=At(s);if(o===a||zo(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[r,i]of t)n.set(r,i<=2?"violation":"ok");return n}function rS(e){return e.includes("types")||e.endsWith(".d.ts")}function iS(e,t,n){let r=Tn(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function oS(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function sS(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function aS(e){return e.endsWith(".vue")}function cS(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Qe(e){let t=G(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||lS(Kn.basename(e)))}function lS(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")}function Ot(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new L(e);return ve({candidates:()=>dS(s,n,r),orderCandidates:Vr,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>uS(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function uS(e,t,n){let r=mS(n);if(r.size!==1||!ki(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0];return{symbol:t.symbol,shortName:b(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:B(t),forwardsTo:i.symbol,forwardsToShort:b(i.symbol),forwardsToFile:i.file}}function mS(e){let t=e.some(r=>Y(r.symbol))?e.filter(r=>Y(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function dS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0})}var pS=W("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function Yn(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function ei(e,t,n){let r=[],i=0,o=0,s=P(t.symbol);for(let a of n)gS(e,a,t.relativePath,s)?i++:Qo(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function Qo(e,t,n){if(!n)return!1;let r=$(t);if(!r)return!1;let i=pS.get(e,t,()=>fS(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function fS(e,t,n){let r=new Set,i=new Set,o=ce(e,t);if(!o)return{importedLeaves:r,usedLeaves:i};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?r.add(c.text):i.add(c.text));for(let m of c.children)a(m,u)};return a(o.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function gS(e,t,n,r){if(!r)return!1;let i=A(e,t);if(!i)return!1;let o=Xa(e,t);if(o.length===0)return!1;let s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=i.split(`
553
- `),l=0;for(let u=0;u<c.length;u++){if(!a.test(c[u]??""))continue;if(l++,!o.find(d=>d.startLine<=u&&u<=d.endLine))return!1}return l>0}function $t(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new L(e),u=l.scopedDefinitions(n),m=LS(l,n),d={high:0,medium:1,low:2};return ve({candidates:()=>hS(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,h)=>B(h)-B(p)||p.relativePath.localeCompare(h.relativePath),scanLimit:a,prepare:p=>({consumerFileMap:yS(l,p,{semantic:c}),singletonBackedClassIds:CS(e,l,u,p,{semantic:c}),candidateIndex:bS(p)}),evaluate:(p,h)=>{if(h.singletonBackedClassIds.has(p.symbolId))return null;let f=SS(e,p,h.consumerFileMap,h.candidateIndex);if(f.transitivelyReachable||f.realConsumers.length>1||f.realConsumers.length===0&&f.barrelConsumers>0||!wS(f.definition,f.realConsumers.length,m))return null;let y=xS(e,f);return!s&&y.confidence==="low"?null:y},orderResults:(p,h)=>d[p.confidence]-d[h.confidence]||h.loc-p.loc||p.file.localeCompare(h.file)||p.startLine-h.startLine,limit:o})}function hS(e,t,n,r){return n.filter(i=>i.isTypeLike&&B(i)>=r.minLoc).filter(i=>B(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>G(i.relativePath)!=="test").filter(i=>!ne(e,i.symbol,i.relativePath)).filter(i=>!_S(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function yS(e,t,n){return Yn(e,t,{semantic:n.semantic})}function bS(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=P(n.symbol);i&&r.set(i,n)}return t}function SS(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=ei(e,t,o),l=ES(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function xS(e,t){let n=Bl(e,t.definition.relativePath,t.definition.startLine),r=jl(t.definition.relativePath)?!0:kS(e,t.definition),{confidence:i,reason:o}=PS(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:b(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:B(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o}}function CS(e,t,n,r,i){let o=IS(e,RS(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Yn(t,s,{semantic:i.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)DS(e,l,a)&&c.add(u);return c}function RS(e){let t=new Map;for(let n of e){let r=P(n.symbol);r&&t.set($l(n.relativePath,r),n)}return t}function IS(e,t,n){let r=[];for(let i of n){let o=vS(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function vS(e,t,n){if(Bl(e,n.relativePath,n.startLine)!=="class")return null;let r=P(n.symbol);if(!r)return null;let i=NS(e,n.relativePath,r);return i?t.get($l(n.relativePath,i))??null:null}function DS(e,t,n){let r=P(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Qo(e,o,r))}function $l(e,t){return`${e}\0${t}`}function NS(e,t,n){let r=A(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function LS(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function _S(e){let t=Z(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function jl(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 wS(e,t,n){return!(jl(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function ES(e,t,n,r){let i=Fi(e,t.relativePath),o=P(t.symbol);if(!o)return!1;let s=i.get(o);if(!s||s.size===0)return!1;let a=r.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 m of u)if(m!==t.relativePath&&!e.isIgnored(m))return!0}}return!1}function Bl(e,t,n){let r=A(e,t);if(!r)return"other";let i=r.split(`
554
- `),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[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 kS(e,t){let n=A(e,t.relativePath);if(!n)return!1;let r=P(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
555
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function PS(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 Xn,extname as ti}from"path";function jt(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new L(e),a=BS(s.fileDependencyGraph(n));return ve({candidates:()=>TS(s,n,r),orderCandidates:Vr,scanLimit:o,prepare:c=>({callerFileMap:Yn(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>FS(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function FS(e,t,n,r){let i=AS(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=MS(e,n.symbolId,o);if(!s)return null;let a=OS(t,e,o,n.symbol,s);if(a&&Kt(a.symbol))return null;let{fanIn:c,source:l}=$S(r.callerFileMap,r.reverseFanIn,o,a);return(l==="function"?c<=3:c<=5)?null:{symbol:n.symbol,shortName:b(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:B(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?b(a.symbol):Xn(o),callerFanIn:c}}function TS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function AS(e,t,n,r){let i=Xn(n.relativePath,ti(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Xn(s,ti(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return ei(e,n,o).realConsumers}function MS(e,t,n){return e.get(`SELECT c.start_line, c.end_line
552
+ ${n}`)}function rS(e,t){new L(e).scanSourceReferences({paths:A(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||Ol(e,t,r.sourceFile,r.target.relativePath))})}function Ol(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function iS(e){let t=new Map;for(let[r,i]of e){if(Ke(r))continue;let o=Mt(r);for(let s of i){if(Ke(s))continue;let a=Mt(s);if(o===a||zo(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[r,i]of t)n.set(r,i<=2?"violation":"ok");return n}function oS(e){return e.includes("types")||e.endsWith(".d.ts")}function sS(e,t,n){let r=An(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function aS(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function cS(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function lS(e){return e.endsWith(".vue")}function uS(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Ke(e){let t=G(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||mS(Kn.basename(e)))}function mS(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")}function $t(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new L(e);return ve({candidates:()=>fS(s,n,r),orderCandidates:Vr,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>dS(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function dS(e,t,n){let r=pS(n);if(r.size!==1||!ki(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0];return{symbol:t.symbol,shortName:b(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:B(t),forwardsTo:i.symbol,forwardsToShort:b(i.symbol),forwardsToFile:i.file}}function pS(e){let t=e.some(r=>Y(r.symbol))?e.filter(r=>Y(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function fS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0})}var gS=W("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function Yn(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function ei(e,t,n){let r=[],i=0,o=0,s=P(t.symbol);for(let a of n)yS(e,a,t.relativePath,s)?i++:Qo(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function Qo(e,t,n){if(!n)return!1;let r=$(t);if(!r)return!1;let i=gS.get(e,t,()=>hS(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function hS(e,t,n){let r=new Set,i=new Set,o=ce(e,t);if(!o)return{importedLeaves:r,usedLeaves:i};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?r.add(c.text):i.add(c.text));for(let m of c.children)a(m,u)};return a(o.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function yS(e,t,n,r){if(!r)return!1;let i=T(e,t);if(!i)return!1;let o=Xa(e,t);if(o.length===0)return!1;let s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=i.split(`
553
+ `),l=0;for(let u=0;u<c.length;u++){if(!a.test(c[u]??""))continue;if(l++,!o.find(d=>d.startLine<=u&&u<=d.endLine))return!1}return l>0}function jt(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new L(e),u=l.scopedDefinitions(n),m=wS(l,n),d={high:0,medium:1,low:2};return ve({candidates:()=>bS(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,h)=>B(h)-B(p)||p.relativePath.localeCompare(h.relativePath),scanLimit:a,prepare:p=>({consumerFileMap:SS(l,p,{semantic:c}),singletonBackedClassIds:IS(e,l,u,p,{semantic:c}),candidateIndex:xS(p)}),evaluate:(p,h)=>{if(h.singletonBackedClassIds.has(p.symbolId))return null;let f=CS(e,p,h.consumerFileMap,h.candidateIndex);if(f.transitivelyReachable||f.realConsumers.length>1||f.realConsumers.length===0&&f.barrelConsumers>0||!kS(f.definition,f.realConsumers.length,m))return null;let y=RS(e,f);return!s&&y.confidence==="low"?null:y},orderResults:(p,h)=>d[p.confidence]-d[h.confidence]||h.loc-p.loc||p.file.localeCompare(h.file)||p.startLine-h.startLine,limit:o})}function bS(e,t,n,r){return n.filter(i=>i.isTypeLike&&B(i)>=r.minLoc).filter(i=>B(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>G(i.relativePath)!=="test").filter(i=>!ne(e,i.symbol,i.relativePath)).filter(i=>!ES(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function SS(e,t,n){return Yn(e,t,{semantic:n.semantic})}function xS(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=P(n.symbol);i&&r.set(i,n)}return t}function CS(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=ei(e,t,o),l=PS(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function RS(e,t){let n=Bl(e,t.definition.relativePath,t.definition.startLine),r=jl(t.definition.relativePath)?!0:FS(e,t.definition),{confidence:i,reason:o}=AS(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:b(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:B(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o}}function IS(e,t,n,r,i){let o=DS(e,vS(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Yn(t,s,{semantic:i.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)LS(e,l,a)&&c.add(u);return c}function vS(e){let t=new Map;for(let n of e){let r=P(n.symbol);r&&t.set($l(n.relativePath,r),n)}return t}function DS(e,t,n){let r=[];for(let i of n){let o=NS(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function NS(e,t,n){if(Bl(e,n.relativePath,n.startLine)!=="class")return null;let r=P(n.symbol);if(!r)return null;let i=_S(e,n.relativePath,r);return i?t.get($l(n.relativePath,i))??null:null}function LS(e,t,n){let r=P(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Qo(e,o,r))}function $l(e,t){return`${e}\0${t}`}function _S(e,t,n){let r=T(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function wS(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function ES(e){let t=Z(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function jl(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 kS(e,t,n){return!(jl(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function PS(e,t,n,r){let i=Fi(e,t.relativePath),o=P(t.symbol);if(!o)return!1;let s=i.get(o);if(!s||s.size===0)return!1;let a=r.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 m of u)if(m!==t.relativePath&&!e.isIgnored(m))return!0}}return!1}function Bl(e,t,n){let r=T(e,t);if(!r)return"other";let i=r.split(`
554
+ `),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[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 FS(e,t){let n=T(e,t.relativePath);if(!n)return!1;let r=P(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
555
+ `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function AS(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 Xn,extname as ti}from"path";function Bt(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new L(e),a=qS(s.fileDependencyGraph(n));return ve({candidates:()=>MS(s,n,r),orderCandidates:Vr,scanLimit:o,prepare:c=>({callerFileMap:Yn(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>TS(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function TS(e,t,n,r){let i=OS(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=$S(e,n.symbolId,o);if(!s)return null;let a=jS(t,e,o,n.symbol,s);if(a&&Kt(a.symbol))return null;let{fanIn:c,source:l}=BS(r.callerFileMap,r.reverseFanIn,o,a);return(l==="function"?c<=3:c<=5)?null:{symbol:n.symbol,shortName:b(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:B(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?b(a.symbol):Xn(o),callerFanIn:c}}function MS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function OS(e,t,n,r){let i=Xn(n.relativePath,ti(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Xn(s,ti(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return ei(e,n,o).realConsumers}function $S(e,t,n){return e.get(`SELECT c.start_line, c.end_line
556
556
  FROM mentions m
557
557
  JOIN chunks c ON m.chunk_id = c.id
558
558
  JOIN documents d ON c.document_id = d.id
559
559
  WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
560
- LIMIT 1`,t,n)}function OS(e,t,n,r,i){let o=e.definitionsForFile(n),s=jS(t,n,r,i.start_line,i.end_line);return be(o,s)}function $S(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:HS(t,n),source:"file"}}function jS(e,t,n,r,i){let o=P(n);if(!o)return r;let s=Ge(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function BS(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function HS(e,t){let n=e.get(t)??0;if(n>0)return n;let r=Xn(t,ti(t)),i=0;for(let[o,s]of e)o!==t&&Xn(o,ti(o))===r&&s>i&&(i=s);return i}var JS=75e3,zS=5e3,QS=2500;function KS(e){let t=Ne(e);return t.symbols>=JS||t.documents>=zS?QS:void 0}var YS=".scipquery-baseline.json";function ni(e,t){return t&&US(t)?t:GS(e.config.projectRoot,t??YS)}function Ko(e,t={}){let{scope:n}=t,r=KS(e),i=[],o=Je(e,{scope:n,minLoc:3,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1});for(let s of o.symbols)le(e,s.relativePath)||ne(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of kt(e,{scope:n,minLoc:3,scanLimit:r,semantic:!1}))le(e,s.relativePath)||ne(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Et(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${XS(s.path)}`);for(let s of ze(e,{scope:n,minSimilarity:.6,limit:50,minCallees:4,scanLimit:r,semantic:!1}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Pt(e,{scope:n,minLoc:15,minCallees:5,limit:50,scanLimit:r,semantic:!1}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of jt(e,{scope:n,maxLoc:15,limit:50,scanLimit:r,semantic:!1}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Ot(e,{scope:n,maxLoc:15,limit:50,scanLimit:r,semantic:!1}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of $t(e,{scope:n,minLoc:3,limit:50,scanLimit:r,semantic:!1}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Mt(e,{scope:n,semantic:!1}).results)s.kind!=="pattern-deviation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function XS(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 Yo(e,t={}){let n=Ko(e,{scope:t.scope}),r=ni(e,t.path);return WS(r,JSON.stringify({version:1,findings:n},null,2)+`
561
- `),{path:r,findingCount:n.length}}function Zn(e,t={}){let n=ni(e,t.path);if(!qS(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(VS(n,"utf-8")),i=new Set(r.findings??[]),o=Ko(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:i.size,current:o,newFindings:o.filter(a=>!i.has(a)),fixedFindings:[...i].filter(a=>!s.has(a))}}function er(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=t.files===void 0?null:new Set(t.files),s=new L(e);return ve({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>ZS(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:i,evaluate:a=>{let c=K(e,a.relativePath)?.callables.find(m=>m.startLine===a.startLine&&m.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(m=>!m.simple)||c.paramsEndLine>=c.endLine)return null;let l=Ge(e,a.relativePath),u=[];for(let m=c.params.length-1;m>=0;m--){let d=c.params[m];if(d.name===""||d.name.startsWith("_")||ex(l.get(d.name),c.paramsEndLine,c.endLine))break;u.unshift(d.name)}return u.length===0?null:{symbol:a.symbol,shortName:b(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:r})}function ZS(e){let t=$(e);return t==="typescript"||t==="tsx"||t==="javascript"}function ex(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}function Xo(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=10,minSimilarity:s=.8}=t,a=pn(e,{base:n}),c=a.changedFiles,l=new Set(c),u={base:n,changedFiles:c,changedSymbols:a.changedSymbols.length,checksRun:[],skipped:[],findings:[],note:a.summary.note};return c.length===0||(tx(e,a.changedSymbols,l,o,s,u),nx(e,l,r,i,u),rx(e,l,u),ix(e,c,u),ox(e,a.changedSymbols,u),sx(e,u)),u}function tx(e,t,n,r,i,o){o.checksRun.push("echo");for(let s of t.slice(0,r)){let a=Gn(e,s.symbol,{minSimilarity:i,limit:3});for(let c of a){let l=c.fileA===s.file?c.fileB:c.fileA,u=c.fileA===s.file?c.shortNameB:c.shortNameA;n.has(l)||o.findings.push({check:"echo",message:`${s.shortName} (${s.file}) is ${Math.round(c.similarity*100)}% similar to established ${u} (${l})`,remediation:`Extend or reuse ${u} instead of keeping the re-implementation.`})}}t.length>r&&o.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function nx(e,t,n,r,i){let o=Kr(e,{minTogether:n,minConfidence:0});if(!o){i.skipped.push({check:"co-change-partner",reason:"no git history"});return}i.checksRun.push("co-change-partner");let s=new Set;for(let a of o){let c=t.has(a.fileA),l=t.has(a.fileB);if(c===l)continue;let u=c?a.fileA:a.fileB,m=c?a.fileB:a.fileA,d=c?a.changesA:a.changesB,p=d>0?a.together/d:0;if(p<r||Wo(m)||Wo(u)||!Hl(`${e.config.projectRoot}/${m}`))continue;let h=`${u}|${m}`;s.has(h)||(s.add(h),i.findings.push({check:"co-change-partner",message:`${u} changed, but ${m} did not \u2014 they change together ${a.together}x (${Math.round(p*100)}% of the time)`,remediation:`Update ${m} alongside this change, or confirm the coupling no longer holds.`}))}}function rx(e,t,n){n.checksRun.push("doc-reference");for(let r of Fl(e,t))t.has(r.doc)||n.findings.push({check:"doc-reference",message:`${r.doc} cites ${r.cited.join(", ")} \u2014 changed in this diff, doc untouched`,remediation:`Re-read ${r.doc} and update its claims, or update its citations.`})}function ix(e,t,n){n.checksRun.push("unused-params");for(let r of er(e,{files:t,limit:50}))n.findings.push({check:"unused-params",message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,remediation:"Drop the unused trailing parameters and their call-site arguments."})}function ox(e,t,n){n.checksRun.push("new-dead");let r=new L(e);for(let i of t)i.fanIn>0||r.fileKind(i.file)!=="test"&&(le(e,i.file)||ne(e,i.symbol,i.file)||n.findings.push({check:"new-dead",message:`${i.shortName} (${i.file}) was changed but has zero indexed consumers`,remediation:"Wire it up, or remove it before it becomes permanent dead code."}))}function sx(e,t){if(!Hl(ni(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=Zn(e);for(let r of n.newFindings)t.findings.push({check:"baseline",message:`new finding vs committed baseline: ${r}`,remediation:"Fix the finding, or knowingly accept it via health --write-baseline."})}function Zo(e,t={}){let{windowCommits:n=100,minSimilarity:r=.7,limit:i=30,scope:o,scanLimit:s}=t,a=_l(e);if(!a)return{available:!1,windowCommits:n,findings:[]};let c=ze(e,{scope:o,minSimilarity:r,limit:i*5,crossFileOnly:!0,scanLimit:s,semantic:t.semantic}),l=[];for(let u of c){let m=a.get(u.fileA)?.commitsAgo??null,d=a.get(u.fileB)?.commitsAgo??null,p=m!==null&&m<=n,h=d!==null&&d<=n;if(!(!p&&!h)){if(p&&h){let f=(m??0)<=(d??0);l.push({kind:"twin",echoSymbol:f?u.shortNameA:u.shortNameB,echoFile:f?u.fileA:u.fileB,echoAgeCommits:(f?m:d)??0,establishedSymbol:f?u.shortNameB:u.shortNameA,establishedFile:f?u.fileB:u.fileA,establishedAgeCommits:f?d:m,similarity:u.similarity,sharedCallees:u.sharedCallees})}else l.push({kind:"echo",echoSymbol:p?u.shortNameA:u.shortNameB,echoFile:p?u.fileA:u.fileB,echoAgeCommits:(p?m:d)??0,establishedSymbol:p?u.shortNameB:u.shortNameA,establishedFile:p?u.fileB:u.fileA,establishedAgeCommits:p?d:m,similarity:u.similarity,sharedCallees:u.sharedCallees});if(l.length>=i)break}}return l.sort((u,m)=>(u.kind===m.kind?0:u.kind==="echo"?-1:1)||m.similarity-u.similarity),{available:!0,windowCommits:n,findings:l}}var ax=/scip-query[\s:-]*ignore[\s:-]*(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar)?/gi,cx=re("suppression-inventory",{clearGroups:["whole-project"]});function ri(e){return cx.get(e,()=>lx(e))}function lx(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,r=0;for(let i of $e(e)){let o=A(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.matchAll(ax)){r+=1,n.set(i,(n.get(i)??0)+1);let a=ux(s[1]);t[a]+=1}}return{total:r,byCategory:t,byFile:n}}function ux(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as mx}from"fs";import{join as dx}from"path";function tr(e,t,n={}){let r=F(e,t);if(!r)return null;let i=new L(e),o=yx(fx(e,r.relativePath,r.startLine,r.endLine),px(e,r.relativePath)),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:b(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:gx(e,r.symbolId),fanOut:hx(c,r.relativePath)}}function px(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function fx(e,t,n,r){try{return mx(dx(e.config.projectRoot,t),"utf-8").split(`
560
+ LIMIT 1`,t,n)}function jS(e,t,n,r,i){let o=e.definitionsForFile(n),s=HS(t,n,r,i.start_line,i.end_line);return be(o,s)}function BS(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:VS(t,n),source:"file"}}function HS(e,t,n,r,i){let o=P(n);if(!o)return r;let s=Je(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function qS(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function VS(e,t){let n=e.get(t)??0;if(n>0)return n;let r=Xn(t,ti(t)),i=0;for(let[o,s]of e)o!==t&&Xn(o,ti(o))===r&&s>i&&(i=s);return i}var QS=75e3,KS=5e3,YS=2500;function XS(e){let t=Ne(e);return t.symbols>=QS||t.documents>=KS?YS:void 0}var ZS=".scipquery-baseline.json";function ni(e,t){return t&&JS(t)?t:zS(e.config.projectRoot,t??ZS)}function Ko(e,t={}){let{scope:n}=t,r=XS(e),i=[],o=ze(e,{scope:n,minLoc:3,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1});for(let s of o.symbols)le(e,s.relativePath)||ne(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Pt(e,{scope:n,minLoc:3,scanLimit:r,semantic:!1}))le(e,s.relativePath)||ne(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of kt(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${ex(s.path)}`);for(let s of Qe(e,{scope:n,minSimilarity:.6,limit:50,minCallees:4,scanLimit:r,semantic:!1}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Ft(e,{scope:n,minLoc:15,minCallees:5,limit:50,scanLimit:r,semantic:!1}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Bt(e,{scope:n,maxLoc:15,limit:50,scanLimit:r,semantic:!1}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of $t(e,{scope:n,maxLoc:15,limit:50,scanLimit:r,semantic:!1}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of jt(e,{scope:n,minLoc:3,limit:50,scanLimit:r,semantic:!1}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Ot(e,{scope:n,semantic:!1}).results)s.kind!=="pattern-deviation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function ex(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 Yo(e,t={}){let n=Ko(e,{scope:t.scope}),r=ni(e,t.path);return GS(r,JSON.stringify({version:1,findings:n},null,2)+`
561
+ `),{path:r,findingCount:n.length}}function Zn(e,t={}){let n=ni(e,t.path);if(!WS(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(US(n,"utf-8")),i=new Set(r.findings??[]),o=Ko(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:i.size,current:o,newFindings:o.filter(a=>!i.has(a)),fixedFindings:[...i].filter(a=>!s.has(a))}}function er(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=t.files===void 0?null:new Set(t.files),s=new L(e);return ve({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>tx(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:i,evaluate:a=>{let c=K(e,a.relativePath)?.callables.find(m=>m.startLine===a.startLine&&m.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(m=>!m.simple)||c.paramsEndLine>=c.endLine)return null;let l=Je(e,a.relativePath),u=[];for(let m=c.params.length-1;m>=0;m--){let d=c.params[m];if(d.name===""||d.name.startsWith("_")||nx(l.get(d.name),c.paramsEndLine,c.endLine))break;u.unshift(d.name)}return u.length===0?null:{symbol:a.symbol,shortName:b(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:r})}function tx(e){let t=$(e);return t==="typescript"||t==="tsx"||t==="javascript"}function nx(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}function Xo(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=10,minSimilarity:s=.8}=t,a=pn(e,{base:n}),c=a.changedFiles,l=new Set(c),u={base:n,changedFiles:c,changedSymbols:a.changedSymbols.length,checksRun:[],skipped:[],findings:[],note:a.summary.note};return c.length===0||(rx(e,a.changedSymbols,l,o,s,u),ix(e,l,r,i,u),ox(e,l,u),sx(e,c,u),ax(e,a.changedSymbols,u),cx(e,u)),u}function rx(e,t,n,r,i,o){o.checksRun.push("echo");for(let s of t.slice(0,r)){let a=Gn(e,s.symbol,{minSimilarity:i,limit:3});for(let c of a){let l=c.fileA===s.file?c.fileB:c.fileA,u=c.fileA===s.file?c.shortNameB:c.shortNameA;n.has(l)||o.findings.push({check:"echo",message:`${s.shortName} (${s.file}) is ${Math.round(c.similarity*100)}% similar to established ${u} (${l})`,remediation:`Extend or reuse ${u} instead of keeping the re-implementation.`})}}t.length>r&&o.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function ix(e,t,n,r,i){let o=Kr(e,{minTogether:n,minConfidence:0});if(!o){i.skipped.push({check:"co-change-partner",reason:"no git history"});return}i.checksRun.push("co-change-partner");let s=new Set;for(let a of o){let c=t.has(a.fileA),l=t.has(a.fileB);if(c===l)continue;let u=c?a.fileA:a.fileB,m=c?a.fileB:a.fileA,d=c?a.changesA:a.changesB,p=d>0?a.together/d:0;if(p<r||Wo(m)||Wo(u)||!Hl(`${e.config.projectRoot}/${m}`))continue;let h=`${u}|${m}`;s.has(h)||(s.add(h),i.findings.push({check:"co-change-partner",message:`${u} changed, but ${m} did not \u2014 they change together ${a.together}x (${Math.round(p*100)}% of the time)`,remediation:`Update ${m} alongside this change, or confirm the coupling no longer holds.`}))}}function ox(e,t,n){n.checksRun.push("doc-reference");for(let r of Fl(e,t))t.has(r.doc)||n.findings.push({check:"doc-reference",message:`${r.doc} cites ${r.cited.join(", ")} \u2014 changed in this diff, doc untouched`,remediation:`Re-read ${r.doc} and update its claims, or update its citations.`})}function sx(e,t,n){n.checksRun.push("unused-params");for(let r of er(e,{files:t,limit:50}))n.findings.push({check:"unused-params",message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,remediation:"Drop the unused trailing parameters and their call-site arguments."})}function ax(e,t,n){n.checksRun.push("new-dead");let r=new L(e);for(let i of t)i.fanIn>0||r.fileKind(i.file)!=="test"&&(le(e,i.file)||ne(e,i.symbol,i.file)||n.findings.push({check:"new-dead",message:`${i.shortName} (${i.file}) was changed but has zero indexed consumers`,remediation:"Wire it up, or remove it before it becomes permanent dead code."}))}function cx(e,t){if(!Hl(ni(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=Zn(e);for(let r of n.newFindings)t.findings.push({check:"baseline",message:`new finding vs committed baseline: ${r}`,remediation:"Fix the finding, or knowingly accept it via health --write-baseline."})}function Zo(e,t={}){let{windowCommits:n=100,minSimilarity:r=.7,limit:i=30,scope:o,scanLimit:s}=t,a=_l(e);if(!a)return{available:!1,windowCommits:n,findings:[]};let c=Qe(e,{scope:o,minSimilarity:r,limit:i*5,crossFileOnly:!0,scanLimit:s,semantic:t.semantic}),l=[];for(let u of c){let m=a.get(u.fileA)?.commitsAgo??null,d=a.get(u.fileB)?.commitsAgo??null,p=m!==null&&m<=n,h=d!==null&&d<=n;if(!(!p&&!h)){if(p&&h){let f=(m??0)<=(d??0);l.push({kind:"twin",echoSymbol:f?u.shortNameA:u.shortNameB,echoFile:f?u.fileA:u.fileB,echoAgeCommits:(f?m:d)??0,establishedSymbol:f?u.shortNameB:u.shortNameA,establishedFile:f?u.fileB:u.fileA,establishedAgeCommits:f?d:m,similarity:u.similarity,sharedCallees:u.sharedCallees})}else l.push({kind:"echo",echoSymbol:p?u.shortNameA:u.shortNameB,echoFile:p?u.fileA:u.fileB,echoAgeCommits:(p?m:d)??0,establishedSymbol:p?u.shortNameB:u.shortNameA,establishedFile:p?u.fileB:u.fileA,establishedAgeCommits:p?d:m,similarity:u.similarity,sharedCallees:u.sharedCallees});if(l.length>=i)break}}return l.sort((u,m)=>(u.kind===m.kind?0:u.kind==="echo"?-1:1)||m.similarity-u.similarity),{available:!0,windowCommits:n,findings:l}}var lx=/scip-query[\s:-]*ignore[\s:-]*(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar)?/gi,ux=re("suppression-inventory",{clearGroups:["whole-project"]});function ri(e){return ux.get(e,()=>mx(e))}function mx(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,r=0;for(let i of je(e)){let o=T(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.matchAll(lx)){r+=1,n.set(i,(n.get(i)??0)+1);let a=dx(s[1]);t[a]+=1}}return{total:r,byCategory:t,byFile:n}}function dx(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as px}from"fs";import{join as fx}from"path";function tr(e,t,n={}){let r=F(e,t);if(!r)return null;let i=new L(e),o=Sx(hx(e,r.relativePath,r.startLine,r.endLine),gx(e,r.relativePath)),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:b(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:yx(e,r.symbolId),fanOut:bx(c,r.relativePath)}}function gx(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function hx(e,t,n,r){try{return px(fx(e.config.projectRoot,t),"utf-8").split(`
562
562
  `).slice(n,r+1).join(`
563
- `)}catch{return""}}function gx(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
563
+ `)}catch{return""}}function yx(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
564
564
  FROM mentions m
565
565
  JOIN chunks c ON m.chunk_id = c.id
566
- WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function hx(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function yx(e,t){let n=It(e),r=0,i=[/\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 i){let s=n.match(o);s&&(r+=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&&(r+=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&&(r+=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&&(r+=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&&(r+=a.length)}}return r}function nr(e,t,n={}){let r=F(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=dt(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=bx(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:b(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:b(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)":b(c.symbol),file:c.file}))}}function bx(e,t,n,r){let i=dn(he(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=dn(Re(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:dn(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function gn(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=F(e,t);return o?r==="backward"?Sx(e,o,i,{semantic:n.semantic!==!1}):xx(e,o,{semantic:n.semantic!==!1}):null}function Sx(e,t,n,r){let i=[],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=he(e,l,{semantic:r.semantic});for(let m of u){if(o.has(m.symbol))continue;o.add(m.symbol),i.push({symbol:m.symbol,shortName:b(m.symbol),file:m.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let d=tn(e,m.symbol);d&&!e.isIgnored(d.relativePath)&&c.push(d)}}s=c}return{symbol:t.symbol,shortName:b(t.symbol),direction:"backward",connectedSymbols:i}}function xx(e,t,n){let r=new Set,i=[],o=new L(e);for(let s of dt(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??be(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=tn(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:b(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:b(t.symbol),direction:"forward",connectedSymbols:i}}function es(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!Rx(t),a=s?Mn(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?qn(e,t,{semantic:o}):null,l=s?tr(e,t,{semantic:o}):null,u=s?nr(e,t,{semantic:o}):null,m=s?gn(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,d=s?gn(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,p=s?Jn(e,t,{maxDepth:r,scope:n.scope}):[],h=zn(e,t,{semantic:o}),f=On(e,t),y=$n(e,t),C=jn(e,t),E=Bn(e,t),N={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||m!==null||d!==null||p.length>0,file:h!==null||f.length>0||y.length>0,module:C.files.length>0||C.symbols.length>0||E.length>0},I=[];!N.symbol&&!N.file&&!N.module&&I.push("No symbol, file, or module matched target.");let v=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:N,history:Cx(e,v),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:m,forwardSlice:d,affected:p,changeSurface:h,deps:f,rdeps:y,system:C,surface:E,warnings:I}}function Cx(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Qr(e);if(!r)return n;let i=Tt(e,t,{limit:5});return{available:!0,file:t,churn:r.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:i.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence})),suppressionsInFile:ri(e).byFile.get(t)??0}}function Rx(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function rr(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new L(e);return ve({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)=>Ix(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function Ix(e,t,n){let r=e.endLine-e.startLine+1;if(r<n)return null;let i=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:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:a,calleeCount:c,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function Vl(e){let t=Lx(e),{breakdown:n}=wx(e),r=ql(n,"risk"),i=ql(n,"hygiene");return{score:Math.min(r,i),riskScore:r,hygieneScore:i,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,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null},axes:vx(e),validation:Nx(e),suppressions:e.suppressions,actions:t,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function vx(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:Dx(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function Dx(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:hn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function Nx(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??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,m]of Object.entries(t))r.has(u)?i+=m.fixChanges:(o+=m.fixChanges,s+=1);let a=r.size>0?hn(i/r.size):0,c=s>0?hn(o/s):0,l={};for(let[u,m]of Object.entries(n)){let d=new Set(m);if(d.size===0)continue;let p=0;for(let f of d)p+=t[f]?.fixChanges??0;let h=hn(p/d.size);l[u]={flaggedFiles:d.size,fixDensity:h,lift:c>0?hn(h/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?hn(a/c):null,byCategory:l}}function hn(e){return Math.round(e*100)/100}function Lx(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.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 extract method opportunities`,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 that could be inlined`,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 i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${i.join(", ")} \u2014 premature abstraction`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:i.join(", "),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 i=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 dependency edge`+(i?` (e.g. ${i.fileA} \u2194 ${i.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},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var _x={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk",similar:"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene"};function ql(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function wx(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=(m,d,p)=>{d>0&&r.push({axis:m,points:d,detail:p,kind:_x[m]??"hygiene"})},o=e.dead.count/n;i("dead-code",Math.min(20,Math.round(o*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let s=e.isolated.count/n;i("isolated",Math.min(10,Math.round(s*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),i("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let a=e.similarCount/n*1e3;i("similar",Math.min(10,Math.round(a)),`${e.similarCount} similar function pair(s)`);let c=e.extractCount/n*1e3;i("extract",Math.min(5,Math.round(c/2)),`${e.extractCount} extraction candidate(s)`),i("wrappers",Math.min(3,e.wrappers.count),`${e.wrappers.count} wrapper candidate(s)`),i("passthroughs",Math.min(3,e.passthroughs.count),`${e.passthroughs.count} passthrough candidate(s)`);let l=e.stale.count/Math.max(n*.1,1);i("stale-abstractions",Math.min(8,Math.round(l*10)),`${e.stale.count} stale abstraction(s)`);let u=e.drift.count/t;return i("drift",Math.min(5,Math.round(u*50)),`${e.drift.count} drift finding(s)`),i("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence&&i("hidden-coupling",Math.min(5,e.gitEvidence.hiddenCoupling.pairCount),`${e.gitEvidence.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`),{breakdown:r}}import{getHeapStatistics as Ex}from"v8";var kx=64*1024*1024;function ts(){let e=globalThis.gc;if(!e)return;let t=Ex();t.heap_size_limit-t.used_heap_size<kx||e()}var Px=50,Fx=75e3,Tx=5e3,Wl=2500,ir=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions"],Ax={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:$x(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:jx(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:Bx(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:Hx(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:qx(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:Vx(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:Wx(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:Ux(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:zx(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:Qx(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:Gx(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:Jx(e,n)})};function ns(e,t,n={}){return Mx(e,n.full===!0,(r,i)=>Ax[t](e,n.scope,i,r))}function Mx(e,t,n){let r=Ne(e),i=Kx(r,t);try{return n(r,i)}finally{po(e,{semanticProvider:!0}),ts()}}function rs(e){return Vl(Ox(e))}function Ox(e){let t=ke(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:ke(e,"dead").dead,isolated:ke(e,"isolated").isolated,realCycleCount:ke(e,"cycles").realCycleCount,similarCount:ke(e,"similar").similarCount,extractCount:ke(e,"extract-candidates").extractCount,wrappers:ke(e,"wrapper-candidates").wrappers,passthroughs:ke(e,"passthrough-candidates").passthroughs,stale:ke(e,"stale-abstractions").stale,drift:ke(e,"drift").drift,complexity:ke(e,"complexity-hotspots").complexity,gitEvidence:Ul(e,"git-evidence")?.gitEvidence??null,suppressions:Ul(e,"suppressions")?.suppressions??null}}function Ul(e,t){return e.find(n=>n.phase===t)}function ke(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function $x(e,t,n){return Pe(e,n,"dead",()=>{let r=Je(e,{scope:t,minLoc:3,skipBarrels:!0,deadCodeOnly:!0,scanLimit:n.candidateScanLimit,semantic:!1});return is(Zx(e,r.symbols))})}function jx(e,t,n){return Pe(e,n,"isolated",()=>{let r=kt(e,{scope:t,minLoc:3,scanLimit:n.candidateScanLimit,semantic:!1});return is(eC(e,r))})}function Bx(e,t,n){return Pe(e,n,"cycles",()=>Et(e,{scope:t}).filter(i=>i.kind==="real").length)}function Hx(e,t,n){return Pe(e,n,"similar",()=>ze(e,{scope:t,minSimilarity:.6,limit:50,minCallees:4,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function qx(e,t,n){return Pe(e,n,"extract-candidates",()=>Pt(e,{scope:t,minLoc:15,minCallees:5,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function Vx(e,t,n){return Gl(e,n,"wrapper-candidates",()=>jt(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function Wx(e,t,n){return Gl(e,n,"passthrough-candidates",()=>Ot(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function Ux(e,t,n){return Pe(e,n,"stale-abstractions",()=>{let r=$t(e,{scope:t,minLoc:3,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function Gx(e,t){return Pe(e,t,"git-evidence",()=>{let n=Qr(e);if(!n)return null;let r=Tt(e,void 0,{limit:50}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Ll(e),hiddenCoupling:{pairCount:r.findings.length,top:r.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence}))},fileStats:i}})}function Jx(e,t){return Pe(e,t,"suppressions",()=>{let n=ri(e);return{total:n.total,byCategory:{...n.byCategory}}})}function zx(e,t,n){return Pe(e,n,"drift",()=>{let r=Mt(e,{scope:t,semantic:!1});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function Qx(e,t,n){return Pe(e,n,"complexity-hotspots",()=>{let r=rr(e,{scope:t,minLoc:10,limit:10,scanLimit:n.candidateScanLimit,semantic:!1});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>Px).length}})}function Kx(e,t){return e.symbols>=Fx||e.documents>=Tx?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:Wl,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Wl} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function Yx(e,t){t.releaseCachesBetweenPhases&&(po(e),ts())}function Pe(e,t,n,r){Xx(n);try{return r()}finally{Yx(e,t)}}function Gl(e,t,n,r){return Pe(e,t,n,()=>is(r()))}function Xx(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function Zx(e,t){return t.filter(n=>!le(e,n.relativePath)&&!ne(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function eC(e,t){return t.filter(n=>!le(e,n.relativePath)&&!ne(e,n.symbol,n.relativePath))}function is(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function os(e,t,n,r={}){let i=F(e,t),o=F(e,n);if(!i||!o)return null;let s=new Set(he(e,i,{semantic:r.semantic}).map(y=>y.symbol)),a=new Set(he(e,o,{semantic:r.semantic}).map(y=>y.symbol)),c=[];for(let y of s)a.has(y)&&c.push(y);let l=[];for(let y of s)a.has(y)||l.push(y);let u=[];for(let y of a)s.has(y)||u.push(y);let m=new Set([...s,...a]),d=m.size>0?c.length/m.size:0,p;m.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=i.endLine-i.startLine+1,f=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:b(i.symbol),file:i.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:b(o.symbol),file:o.relativePath,loc:f},similarity:d,sharedCallees:c.map(b),uniqueToA:l.map(b),uniqueToB:u.map(b),consolidationStrategy:p}}import{readFileSync as Jl}from"fs";import{extname as tC,join as zl}from"path";function ss(e,t,n={}){let{context:r=0}=n,i=nC(t);if(i)return iC(e,i.filePath,i.startLine,i.endLine,r);let o=F(e,t);return o?rC(e,o,r):null}function nC(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 rC(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=zl(e.config.projectRoot,t.relativePath),o;try{o=Jl(i,"utf-8")}catch{return null}let s=o.split(`
566
+ WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function bx(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function Sx(e,t){let n=vt(e),r=0,i=[/\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 i){let s=n.match(o);s&&(r+=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&&(r+=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&&(r+=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&&(r+=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&&(r+=a.length)}}return r}function nr(e,t,n={}){let r=F(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=pt(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=xx(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:b(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:b(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)":b(c.symbol),file:c.file}))}}function xx(e,t,n,r){let i=dn(he(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=dn(Re(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:dn(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function gn(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=F(e,t);return o?r==="backward"?Cx(e,o,i,{semantic:n.semantic!==!1}):Rx(e,o,{semantic:n.semantic!==!1}):null}function Cx(e,t,n,r){let i=[],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=he(e,l,{semantic:r.semantic});for(let m of u){if(o.has(m.symbol))continue;o.add(m.symbol),i.push({symbol:m.symbol,shortName:b(m.symbol),file:m.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let d=tn(e,m.symbol);d&&!e.isIgnored(d.relativePath)&&c.push(d)}}s=c}return{symbol:t.symbol,shortName:b(t.symbol),direction:"backward",connectedSymbols:i}}function Rx(e,t,n){let r=new Set,i=[],o=new L(e);for(let s of pt(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??be(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=tn(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:b(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:b(t.symbol),direction:"forward",connectedSymbols:i}}function es(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!vx(t),a=s?Mn(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?qn(e,t,{semantic:o}):null,l=s?tr(e,t,{semantic:o}):null,u=s?nr(e,t,{semantic:o}):null,m=s?gn(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,d=s?gn(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,p=s?Jn(e,t,{maxDepth:r,scope:n.scope}):[],h=zn(e,t,{semantic:o}),f=On(e,t),y=$n(e,t),C=jn(e,t),E=Bn(e,t),N={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||m!==null||d!==null||p.length>0,file:h!==null||f.length>0||y.length>0,module:C.files.length>0||C.symbols.length>0||E.length>0},I=[];!N.symbol&&!N.file&&!N.module&&I.push("No symbol, file, or module matched target.");let v=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:N,history:Ix(e,v),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:m,forwardSlice:d,affected:p,changeSurface:h,deps:f,rdeps:y,system:C,surface:E,warnings:I}}function Ix(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Qr(e);if(!r)return n;let i=Tt(e,t,{limit:5});return{available:!0,file:t,churn:r.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:i.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence})),suppressionsInFile:ri(e).byFile.get(t)??0}}function vx(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function rr(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new L(e);return ve({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)=>Dx(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function Dx(e,t,n){let r=e.endLine-e.startLine+1;if(r<n)return null;let i=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:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:a,calleeCount:c,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function Vl(e){let t=wx(e),{breakdown:n}=kx(e),r=ql(n,"risk"),i=ql(n,"hygiene");return{score:Math.min(r,i),riskScore:r,hygieneScore:i,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,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null},axes:Nx(e),validation:_x(e),suppressions:e.suppressions,actions:t,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function Nx(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:Lx(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function Lx(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:hn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function _x(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??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,m]of Object.entries(t))r.has(u)?i+=m.fixChanges:(o+=m.fixChanges,s+=1);let a=r.size>0?hn(i/r.size):0,c=s>0?hn(o/s):0,l={};for(let[u,m]of Object.entries(n)){let d=new Set(m);if(d.size===0)continue;let p=0;for(let f of d)p+=t[f]?.fixChanges??0;let h=hn(p/d.size);l[u]={flaggedFiles:d.size,fixDensity:h,lift:c>0?hn(h/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?hn(a/c):null,byCategory:l}}function hn(e){return Math.round(e*100)/100}function wx(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.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 extract method opportunities`,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 that could be inlined`,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 i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${i.join(", ")} \u2014 premature abstraction`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:i.join(", "),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 i=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 dependency edge`+(i?` (e.g. ${i.fileA} \u2194 ${i.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},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var Ex={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk",similar:"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene"};function ql(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function kx(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=(m,d,p)=>{d>0&&r.push({axis:m,points:d,detail:p,kind:Ex[m]??"hygiene"})},o=e.dead.count/n;i("dead-code",Math.min(20,Math.round(o*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let s=e.isolated.count/n;i("isolated",Math.min(10,Math.round(s*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),i("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let a=e.similarCount/n*1e3;i("similar",Math.min(10,Math.round(a)),`${e.similarCount} similar function pair(s)`);let c=e.extractCount/n*1e3;i("extract",Math.min(5,Math.round(c/2)),`${e.extractCount} extraction candidate(s)`),i("wrappers",Math.min(3,e.wrappers.count),`${e.wrappers.count} wrapper candidate(s)`),i("passthroughs",Math.min(3,e.passthroughs.count),`${e.passthroughs.count} passthrough candidate(s)`);let l=e.stale.count/Math.max(n*.1,1);i("stale-abstractions",Math.min(8,Math.round(l*10)),`${e.stale.count} stale abstraction(s)`);let u=e.drift.count/t;return i("drift",Math.min(5,Math.round(u*50)),`${e.drift.count} drift finding(s)`),i("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence&&i("hidden-coupling",Math.min(5,e.gitEvidence.hiddenCoupling.pairCount),`${e.gitEvidence.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`),{breakdown:r}}import{getHeapStatistics as Px}from"v8";var Fx=64*1024*1024;function ts(){let e=globalThis.gc;if(!e)return;let t=Px();t.heap_size_limit-t.used_heap_size<Fx||e()}var Ax=50,Tx=75e3,Mx=5e3,Wl=2500,ir=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions"],Ox={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:Bx(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:Hx(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:qx(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:Vx(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:Wx(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:Ux(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:Gx(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:Jx(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:Kx(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:Yx(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:zx(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:Qx(e,n)})};function ns(e,t,n={}){return $x(e,n.full===!0,(r,i)=>Ox[t](e,n.scope,i,r))}function $x(e,t,n){let r=Ne(e),i=Xx(r,t);try{return n(r,i)}finally{po(e,{semanticProvider:!0}),ts()}}function rs(e){return Vl(jx(e))}function jx(e){let t=ke(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:ke(e,"dead").dead,isolated:ke(e,"isolated").isolated,realCycleCount:ke(e,"cycles").realCycleCount,similarCount:ke(e,"similar").similarCount,extractCount:ke(e,"extract-candidates").extractCount,wrappers:ke(e,"wrapper-candidates").wrappers,passthroughs:ke(e,"passthrough-candidates").passthroughs,stale:ke(e,"stale-abstractions").stale,drift:ke(e,"drift").drift,complexity:ke(e,"complexity-hotspots").complexity,gitEvidence:Ul(e,"git-evidence")?.gitEvidence??null,suppressions:Ul(e,"suppressions")?.suppressions??null}}function Ul(e,t){return e.find(n=>n.phase===t)}function ke(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function Bx(e,t,n){return Pe(e,n,"dead",()=>{let r=ze(e,{scope:t,minLoc:3,skipBarrels:!0,deadCodeOnly:!0,scanLimit:n.candidateScanLimit,semantic:!1});return is(tC(e,r.symbols))})}function Hx(e,t,n){return Pe(e,n,"isolated",()=>{let r=Pt(e,{scope:t,minLoc:3,scanLimit:n.candidateScanLimit,semantic:!1});return is(nC(e,r))})}function qx(e,t,n){return Pe(e,n,"cycles",()=>kt(e,{scope:t}).filter(i=>i.kind==="real").length)}function Vx(e,t,n){return Pe(e,n,"similar",()=>Qe(e,{scope:t,minSimilarity:.6,limit:50,minCallees:4,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function Wx(e,t,n){return Pe(e,n,"extract-candidates",()=>Ft(e,{scope:t,minLoc:15,minCallees:5,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function Ux(e,t,n){return Gl(e,n,"wrapper-candidates",()=>Bt(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function Gx(e,t,n){return Gl(e,n,"passthrough-candidates",()=>$t(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function Jx(e,t,n){return Pe(e,n,"stale-abstractions",()=>{let r=jt(e,{scope:t,minLoc:3,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function zx(e,t){return Pe(e,t,"git-evidence",()=>{let n=Qr(e);if(!n)return null;let r=Tt(e,void 0,{limit:50}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Ll(e),hiddenCoupling:{pairCount:r.findings.length,top:r.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence}))},fileStats:i}})}function Qx(e,t){return Pe(e,t,"suppressions",()=>{let n=ri(e);return{total:n.total,byCategory:{...n.byCategory}}})}function Kx(e,t,n){return Pe(e,n,"drift",()=>{let r=Ot(e,{scope:t,semantic:!1});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function Yx(e,t,n){return Pe(e,n,"complexity-hotspots",()=>{let r=rr(e,{scope:t,minLoc:10,limit:10,scanLimit:n.candidateScanLimit,semantic:!1});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>Ax).length}})}function Xx(e,t){return e.symbols>=Tx||e.documents>=Mx?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:Wl,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Wl} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function Zx(e,t){t.releaseCachesBetweenPhases&&(po(e),ts())}function Pe(e,t,n,r){eC(n);try{return r()}finally{Zx(e,t)}}function Gl(e,t,n,r){return Pe(e,t,n,()=>is(r()))}function eC(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function tC(e,t){return t.filter(n=>!le(e,n.relativePath)&&!ne(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function nC(e,t){return t.filter(n=>!le(e,n.relativePath)&&!ne(e,n.symbol,n.relativePath))}function is(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function os(e,t,n,r={}){let i=F(e,t),o=F(e,n);if(!i||!o)return null;let s=new Set(he(e,i,{semantic:r.semantic}).map(y=>y.symbol)),a=new Set(he(e,o,{semantic:r.semantic}).map(y=>y.symbol)),c=[];for(let y of s)a.has(y)&&c.push(y);let l=[];for(let y of s)a.has(y)||l.push(y);let u=[];for(let y of a)s.has(y)||u.push(y);let m=new Set([...s,...a]),d=m.size>0?c.length/m.size:0,p;m.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=i.endLine-i.startLine+1,f=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:b(i.symbol),file:i.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:b(o.symbol),file:o.relativePath,loc:f},similarity:d,sharedCallees:c.map(b),uniqueToA:l.map(b),uniqueToB:u.map(b),consolidationStrategy:p}}import{readFileSync as Jl}from"fs";import{extname as rC,join as zl}from"path";function ss(e,t,n={}){let{context:r=0}=n,i=iC(t);if(i)return sC(e,i.filePath,i.startLine,i.endLine,r);let o=F(e,t);return o?oC(e,o,r):null}function iC(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 oC(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=zl(e.config.projectRoot,t.relativePath),o;try{o=Jl(i,"utf-8")}catch{return null}let s=o.split(`
567
567
  `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
568
- `);return{symbol:t.symbol,shortName:b(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??Ql(t.relativePath),source:l}}function iC(e,t,n,r,i){let o=me(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=zl(e.config.projectRoot,s.relative_path),c;try{c=Jl(a,"utf-8")}catch{return null}let l=c.split(`
568
+ `);return{symbol:t.symbol,shortName:b(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??Ql(t.relativePath),source:l}}function sC(e,t,n,r,i){let o=me(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=zl(e.config.projectRoot,s.relative_path),c;try{c=Jl(a,"utf-8")}catch{return null}let l=c.split(`
569
569
  `),u=Math.max(0,n-1-i),m=Math.min(l.length-1,r-1+i),d=l.slice(u,m+1).join(`
570
- `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:m,language:s.language??Ql(s.relative_path),source:d}}function Ql(e){switch(tC(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 as(e,t={}){let{scope:n,limit:r}=t,i=new L(e),o=pC([...oC(e,n),...cC(e,i,n)]);return fC(o),r?o.slice(0,r):o}function oC(e,t){let n=[];for(let r of sC(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Ki(e,r.barrel_path))continue;let i=aC(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:b(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s})}return n}function sC(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
570
+ `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:m,language:s.language??Ql(s.relative_path),source:d}}function Ql(e){switch(rC(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 as(e,t={}){let{scope:n,limit:r}=t,i=new L(e),o=gC([...aC(e,n),...uC(e,i,n)]);return hC(o),r?o.slice(0,r):o}function aC(e,t){let n=[];for(let r of cC(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Ki(e,r.barrel_path))continue;let i=lC(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:b(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s})}return n}function cC(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
571
571
  barrel_d.id AS barrel_doc_id,
572
572
  barrel_d.relative_path AS barrel_path,
573
573
  gs.id AS symbol_id,
@@ -597,7 +597,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
597
597
  -- Only function-level symbols (ending with ().), not module-level
598
598
  AND gs.symbol LIKE '%().'
599
599
  ${n}
600
- ORDER BY barrel_d.relative_path, gs.symbol`)}function aC(e,t){return e.get(`SELECT
600
+ ORDER BY barrel_d.relative_path, gs.symbol`)}function lC(e,t){return e.get(`SELECT
601
601
  SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
602
602
  SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
603
603
  FROM (
@@ -626,7 +626,7 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
626
626
  AND consumer_d.id != ?
627
627
  ${e.pathExclusionsFor("consumer_d")}
628
628
  GROUP BY consumer_d.id
629
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function cC(e,t,n){let r=[];for(let i of lC(e,n))Kl(e,i,i)>0||r.push(...uC(e,t,i));return r}function lC(e,t){return T(e,{scope:t,includeIgnored:!1}).filter(n=>Ji(e,n).length>0)}function uC(e,t,n){return Ji(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>mC(e,t,n,r.sourcePath))}function mC(e,t,n,r){let i=dC(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:b(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:Kl(e,r,n)}]:[]}function Kl(e,t,n){let r=new Set;for(let i of T(e,{includeIgnored:!1}))if(i!==n)for(let o of te(e,i))o.sourcePath===t&&r.add(i);return r.size}function dC(e,t){let n=e.definitionsForFile(t);return n.find(r=>ee(r.symbol)==="method")??n[0]??null}function pC(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function fC(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function ls(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new L(e),s=gC(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!hC(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:Yl(),callees:Yl()},c=[],l=0,u=jr(e,s);for(let m of s){let d=ii(m,_t(e,m).map(y=>y.file)),p=ii(m,(u.get(m.symbolId)??[]).map(y=>y.file));if(d.size===0&&p.size===0)continue;l+=1;let h=ii(m,wt(e,m).map(y=>y.file)),f=ii(m,(o.calleeMap([m],{semantic:!1}).get(m.symbolId)??[]).map(y=>y.file));Xl(a.references,m,"references",h,d,c),Xl(a.callees,m,"callees",f,p,c)}return c.sort((m,d)=>d.cheapOnly.length+d.oracleOnly.length-(m.cheapOnly.length+m.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?cs(l/s.length):0,scores:["references","callees"].map(m=>bC(m,a[m])),topDisagreements:c.slice(0,i)}}function Yl(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function gC(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function hC(e,t){let n=t[0];if(!n)return!1;try{return Fn(e,n.relativePath).availability().available}catch{return!1}}function ii(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function Xl(e,t,n,r,i,o){if(r.size===0&&i.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let s=[],a=[];for(let c of r)i.has(c)?e.agreed+=1:s.push(c);for(let c of i)r.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:b(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var yC={references:!0,callees:!1};function bC(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:yC[e]&&t.cheapTotal>0?cs(t.agreed/t.cheapTotal):null,recall:cs(n),unverified:r}}function cs(e){return Math.round(e*1e3)/1e3}function us(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=xC(e,SC(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),c=RC(a);return i?c.slice(0,i):c}function SC(e,t){let n=Me(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>B(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>B(i)-B(r)||r.relativePath.localeCompare(i.relativePath)),Ie(n,t.scanLimit)}function xC(e,t,n){let r=new Map;for(let i of t){let o=IC(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(CC(i)),r.set(o,s)}return r}function CC(e){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:B(e)}}function RC(e){let t=[];for(let[n,r]of e)r.length>=2&&t.push({signature:n,functions:r});return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function IC(e,t,n){if(n.semantic){let o=Tc(e,t);if(o)return o}let r=vC(t.documentation),i=r?LC(r):null;return i||_C(DC(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function vC(e){return bt(St(e))}function DC(e,t,n,r,i){let o=A(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=EC(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let m=c;m<=l;m+=1){let d=s[m]?.trim();if(d&&(u=u?`${u} ${d}`:d,NC(u)))return u}if(u&&u.includes("("))return u}return null}function NC(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Ln(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function LC(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 _C(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${Zl(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.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=wC(n.slice(r)).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=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function wC(e){let t=0,n=0,r=0,i=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==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===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&&r===0&&i===0)return e.slice(0,a)}return e}function EC(e,t,n,r){let i=Zl(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\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 m=l;m<=u;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}for(let m=0;m<e.length;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}return a}function Zl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as au}from"fs";import{join as JC}from"path";import kC from"better-sqlite3";var PC=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],oi=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new kC(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
629
+ )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function uC(e,t,n){let r=[];for(let i of mC(e,n))Kl(e,i,i)>0||r.push(...dC(e,t,i));return r}function mC(e,t){return A(e,{scope:t,includeIgnored:!1}).filter(n=>Ji(e,n).length>0)}function dC(e,t,n){return Ji(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>pC(e,t,n,r.sourcePath))}function pC(e,t,n,r){let i=fC(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:b(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:Kl(e,r,n)}]:[]}function Kl(e,t,n){let r=new Set;for(let i of A(e,{includeIgnored:!1}))if(i!==n)for(let o of te(e,i))o.sourcePath===t&&r.add(i);return r.size}function fC(e,t){let n=e.definitionsForFile(t);return n.find(r=>ee(r.symbol)==="method")??n[0]??null}function gC(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function hC(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function ls(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new L(e),s=yC(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!bC(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:Yl(),callees:Yl()},c=[],l=0,u=jr(e,s);for(let m of s){let d=ii(m,wt(e,m).map(y=>y.file)),p=ii(m,(u.get(m.symbolId)??[]).map(y=>y.file));if(d.size===0&&p.size===0)continue;l+=1;let h=ii(m,Et(e,m).map(y=>y.file)),f=ii(m,(o.calleeMap([m],{semantic:!1}).get(m.symbolId)??[]).map(y=>y.file));Xl(a.references,m,"references",h,d,c),Xl(a.callees,m,"callees",f,p,c)}return c.sort((m,d)=>d.cheapOnly.length+d.oracleOnly.length-(m.cheapOnly.length+m.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?cs(l/s.length):0,scores:["references","callees"].map(m=>xC(m,a[m])),topDisagreements:c.slice(0,i)}}function Yl(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function yC(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function bC(e,t){let n=t[0];if(!n)return!1;try{return Fn(e,n.relativePath).availability().available}catch{return!1}}function ii(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function Xl(e,t,n,r,i,o){if(r.size===0&&i.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let s=[],a=[];for(let c of r)i.has(c)?e.agreed+=1:s.push(c);for(let c of i)r.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:b(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var SC={references:!0,callees:!1};function xC(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:SC[e]&&t.cheapTotal>0?cs(t.agreed/t.cheapTotal):null,recall:cs(n),unverified:r}}function cs(e){return Math.round(e*1e3)/1e3}function us(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=RC(e,CC(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),c=vC(a);return i?c.slice(0,i):c}function CC(e,t){let n=Oe(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>B(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>B(i)-B(r)||r.relativePath.localeCompare(i.relativePath)),Ie(n,t.scanLimit)}function RC(e,t,n){let r=new Map;for(let i of t){let o=DC(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(IC(i)),r.set(o,s)}return r}function IC(e){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:B(e)}}function vC(e){let t=[];for(let[n,r]of e)r.length>=2&&t.push({signature:n,functions:r});return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function DC(e,t,n){if(n.semantic){let o=Ac(e,t);if(o)return o}let r=NC(t.documentation),i=r?wC(r):null;return i||EC(LC(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function NC(e){return St(xt(e))}function LC(e,t,n,r,i){let o=T(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=PC(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let m=c;m<=l;m+=1){let d=s[m]?.trim();if(d&&(u=u?`${u} ${d}`:d,_C(u)))return u}if(u&&u.includes("("))return u}return null}function _C(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Ln(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function wC(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 EC(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${Zl(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.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=kC(n.slice(r)).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=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function kC(e){let t=0,n=0,r=0,i=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==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===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&&r===0&&i===0)return e.slice(0,a)}return e}function PC(e,t,n,r){let i=Zl(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\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 m=l;m<=u;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}for(let m=0;m<e.length;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}return a}function Zl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as au}from"fs";import{join as QC}from"path";import FC from"better-sqlite3";var AC=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],oi=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new FC(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
630
630
  EXISTS (
631
631
  SELECT 1
632
632
  FROM defn_enclosing_ranges local_der
@@ -643,8 +643,8 @@ ${d}`,l+=1+d.length,u+=Ln(d),r+=d.length+1}let m=Tf(c);m&&n.push({...m,start:a,e
643
643
  AND local_m.role = 1
644
644
  ${this.pathExclusionsFor("local_d").trimStart()}
645
645
  )
646
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>PC.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
647
- `)}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 FC from"ignore";import{readFileSync as TC,existsSync as ms}from"fs";import{dirname as ds,isAbsolute as eu,join as ps,relative as AC,resolve as MC}from"path";function yn(e){let t=FC(),n=!1,r=OC(e);for(let i of r)try{let o=TC(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add($C),{isIgnored:i=>tu(t,e,i),filter:i=>i.filter(o=>!tu(t,e,o))}}function OC(e){let t=[],n=ps(e,".gitignore");ms(n)&&t.push(n);let r=ds(e),i=0;for(;r!==ds(r)&&i<5;){let o=ps(r,".gitignore");if(ms(o)&&t.push(o),ms(ps(r,".git")))break;r=ds(r),i++}return t}var $C=`
646
+ )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>AC.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
647
+ `)}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 TC from"ignore";import{readFileSync as MC,existsSync as ms}from"fs";import{dirname as ds,isAbsolute as eu,join as ps,relative as OC,resolve as $C}from"path";function yn(e){let t=TC(),n=!1,r=jC(e);for(let i of r)try{let o=MC(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add(BC),{isIgnored:i=>tu(t,e,i),filter:i=>i.filter(o=>!tu(t,e,o))}}function jC(e){let t=[],n=ps(e,".gitignore");ms(n)&&t.push(n);let r=ds(e),i=0;for(;r!==ds(r)&&i<5;){let o=ps(r,".gitignore");if(ms(o)&&t.push(o),ms(ps(r,".git")))break;r=ds(r),i++}return t}var BC=`
648
648
  # Dependencies
649
649
  node_modules/
650
650
  vendor/
@@ -701,27 +701,27 @@ Thumbs.db
701
701
 
702
702
  # Type definitions (often noise in queries)
703
703
  *.d.ts
704
- `;function tu(e,t,n){let r=jC(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function jC(e,t){if(!t||t===".")return null;if(!eu(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=eu(t)?t:MC(e,t),r=AC(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as BC,writeFileSync as HC,existsSync as ru,mkdirSync as qC}from"fs";import{join as Bt,resolve as nu}from"path";import{createHash as VC}from"crypto";import{homedir as WC}from"os";var iu=".scipquery.json",UC={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]};function bn(e){let t=Bt(e,iu);if(!ru(t))return{};try{let n=BC(t,"utf-8");return JSON.parse(n)}catch{return{}}}function ou(e){return{...UC,...e.watch}}function GC(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return fs(n);if(t?.dbPath)return fs(nu(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||Bt(WC(),".cache"),o=VC("sha256").update(nu(e)).digest("hex").slice(0,12),s=Bt(i,"scip-query","projects",o);return fs(s)}function Sn(e,t){let n=GC(e,t);return{cacheDir:n,dbPath:Bt(n,"index.db"),indexPath:Bt(n,"index.scip"),metaPath:Bt(n,"meta.json")}}function su(e,t){let n=Bt(e,iu);return ru(n)||HC(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
705
- `),n}function fs(e){return qC(e,{recursive:!0}),e}function Be(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function si(e=Be()){let t=bn(e),n=Sn(e,t),r=process.env.SCIP_QUERY_INDEX_DB??(au(n.dbPath)?n.dbPath:JC(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function gs(e){return si(e).dbPath}function zC(){let{projectRoot:e,config:t,paths:n,dbPath:r}=si();au(r)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let i={dbPath:r,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic},o=yn(e);return new oi(i,o)}function Ye(e){let t=zC();try{return e(t)}finally{t.close()}}function hs(e,t){return t.concat([e])}function xn(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 cu(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 QC(e)}}function QC(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as KC}from"child_process";function ys(e){let t=KC(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?`:
706
- ${n}`:""}`)}return JSON.parse(t.stdout)}function lu(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ye(e){return e+1}function ue(e,t){return`${ye(e)}-${ye(t)}`}function se(e,t,n){return`${e}:${ue(t,n)}`}var _={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(o),r=o),console.log(t(i))}},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 r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(i)}};var XC=YC(import.meta.url),{version:ai}=nR(),ci="__health-phase",li="__diff-impact-batch",ZC=10,eR=75e3,tR=5e3,uu=2500;function nR(){for(let e of["../package.json","../../package.json"])try{return XC(e)}catch{}return{version:"0.0.0"}}function or(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
707
- `)}function du(e,t,n){let r=Ne(e);return r.symbols>=eR||r.documents>=tR?n?(console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(console.error(`Large index detected; ${t} will scan the highest-priority ${uu} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:uu,semantic:!1}):{semantic:!0}}function pu(e){let t=ir.map(n=>rR(n,e));return rs(t)}function rR(e,t){let n=process.argv[1]??mu(import.meta.url),r=[e];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),ys({cliPath:n,command:ci,args:r,label:`Health phase "${e}"`})}function fu(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
704
+ `;function tu(e,t,n){let r=HC(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function HC(e,t){if(!t||t===".")return null;if(!eu(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=eu(t)?t:$C(e,t),r=OC(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as qC,writeFileSync as VC,existsSync as ru,mkdirSync as WC}from"fs";import{join as Ht,resolve as nu}from"path";import{createHash as UC}from"crypto";import{homedir as GC}from"os";var iu=".scipquery.json",JC={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]};function bn(e){let t=Ht(e,iu);if(!ru(t))return{};try{let n=qC(t,"utf-8");return JSON.parse(n)}catch{return{}}}function ou(e){return{...JC,...e.watch}}function zC(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return fs(n);if(t?.dbPath)return fs(nu(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||Ht(GC(),".cache"),o=UC("sha256").update(nu(e)).digest("hex").slice(0,12),s=Ht(i,"scip-query","projects",o);return fs(s)}function Sn(e,t){let n=zC(e,t);return{cacheDir:n,dbPath:Ht(n,"index.db"),indexPath:Ht(n,"index.scip"),metaPath:Ht(n,"meta.json")}}function su(e,t){let n=Ht(e,iu);return ru(n)||VC(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
705
+ `),n}function fs(e){return WC(e,{recursive:!0}),e}function He(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function si(e=He()){let t=bn(e),n=Sn(e,t),r=process.env.SCIP_QUERY_INDEX_DB??(au(n.dbPath)?n.dbPath:QC(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function gs(e){return si(e).dbPath}function KC(){let{projectRoot:e,config:t,paths:n,dbPath:r}=si();au(r)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let i={dbPath:r,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic},o=yn(e);return new oi(i,o)}function Xe(e){let t=KC();try{return e(t)}finally{t.close()}}function hs(e,t){return t.concat([e])}function xn(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 cu(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 YC(e)}}function YC(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as XC}from"child_process";function ys(e){let t=XC(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?`:
706
+ ${n}`:""}`)}return JSON.parse(t.stdout)}function lu(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ye(e){return e+1}function ue(e,t){return`${ye(e)}-${ye(t)}`}function se(e,t,n){return`${e}:${ue(t,n)}`}var _={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(o),r=o),console.log(t(i))}},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 r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(i)}};var eR=ZC(import.meta.url),{version:ai}=iR(),ci="__health-phase",li="__diff-impact-batch",tR=10,nR=75e3,rR=5e3,uu=2500;function iR(){for(let e of["../package.json","../../package.json"])try{return eR(e)}catch{}return{version:"0.0.0"}}function or(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
707
+ `)}function du(e,t,n){let r=Ne(e);return r.symbols>=nR||r.documents>=rR?n?(console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(console.error(`Large index detected; ${t} will scan the highest-priority ${uu} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:uu,semantic:!1}):{semantic:!0}}function pu(e){let t=ir.map(n=>oR(n,e));return rs(t)}function oR(e,t){let n=process.argv[1]??mu(import.meta.url),r=[e];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),ys({cliPath:n,command:ci,args:r,label:`Health phase "${e}"`})}function fu(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
708
708
  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)
709
709
  `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${xn(e.overview.indexSizeBytes)}
710
710
  `),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let r of e.warnings)console.log(` ${r}`);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.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${n.wrappers}`),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(`
711
711
  Prioritized Actions (highest impact + lowest effort first):`);for(let r=0;r<e.actions.length;r++){let i=e.actions[r],o=i.locRecoverable>0?` (~${i.locRecoverable} LOC recoverable)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
712
- Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(iR(e),e.scoreBreakdown.length>0){console.log(`
712
+ Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(sR(e),e.scoreBreakdown.length>0){console.log(`
713
713
  Score Breakdown (100 minus the following):`);for(let r of e.scoreBreakdown)console.log(` -${String(r.points).padStart(2)} ${r.axis}: ${r.detail}`)}e.actions.length===0&&console.log(`
714
- No issues found. Codebase is clean.`)}function iR(e){let t=e.axes;if(console.log(`
715
- Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.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 r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.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 r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`)}}function gu(e){return Ye(t=>{let n=fn(t,{base:e.base});if(n.note)return pn(t,{base:e.base});if(n.changedFiles.length===0)return pn(t,{base:e.base});let r=[];for(let i of lu(n.changedFiles,ZC))r.push(oR(i,e));return Xr(n.changedFiles,r)})}function oR(e,t){let n=process.argv[1]??mu(import.meta.url),r=[];return t.base&&r.push("--base",t.base),ys({cliPath:n,command:li,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function hu(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:"),_.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
716
- Affected consumer files:`),_.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var yu=hs,R=(e=>parseInt(e,10)),ui=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),sr=parseFloat,bs=parseInt;function g(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function x(e,t=[]){return{category:e,examples:t}}import{existsSync as Rs,mkdirSync as mR,symlinkSync as dR,readlinkSync as pR,unlinkSync as fR}from"fs";import{join as ar,dirname as Cu,resolve as Is}from"path";import{homedir as vs,platform as gR}from"os";import{fileURLToPath as hR}from"url";import{execFileSync as bu}from"child_process";import{platform as Ss,arch as lR}from"os";import{execFileSync as sR}from"child_process";import{platform as aR}from"os";var cR=aR()==="win32";function De(e){let t=cR?"where":"which";try{return sR(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Su="v0.7.0";function xs(){return De("scip")}function uR(){let e=Ss(),t=lR(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;case"win32":n="windows",i="zip";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${Su}/${o}`,filename:o}}function Cs(){let e=uR();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Ss()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
714
+ No issues found. Codebase is clean.`)}function sR(e){let t=e.axes;if(console.log(`
715
+ Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.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 r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.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 r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`)}}function gu(e){return Xe(t=>{let n=fn(t,{base:e.base});if(n.note)return pn(t,{base:e.base});if(n.changedFiles.length===0)return pn(t,{base:e.base});let r=[];for(let i of lu(n.changedFiles,tR))r.push(aR(i,e));return Xr(n.changedFiles,r)})}function aR(e,t){let n=process.argv[1]??mu(import.meta.url),r=[];return t.base&&r.push("--base",t.base),ys({cliPath:n,command:li,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function hu(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:"),_.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
716
+ Affected consumer files:`),_.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var yu=hs,R=(e=>parseInt(e,10)),ui=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),sr=parseFloat,bs=parseInt;function g(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function x(e,t=[]){return{category:e,examples:t}}import{existsSync as Rs,mkdirSync as pR,symlinkSync as fR,readlinkSync as gR,unlinkSync as hR}from"fs";import{join as ar,dirname as Cu,resolve as Is}from"path";import{homedir as vs,platform as yR}from"os";import{fileURLToPath as bR}from"url";import{execFileSync as bu}from"child_process";import{platform as Ss,arch as mR}from"os";import{execFileSync as cR}from"child_process";import{platform as lR}from"os";var uR=lR()==="win32";function De(e){let t=uR?"where":"which";try{return cR(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Su="v0.7.0";function xs(){return De("scip")}function dR(){let e=Ss(),t=mR(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;case"win32":n="windows",i="zip";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${Su}/${o}`,filename:o}}function Cs(){let e=dR();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Ss()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
717
717
  `),console.log("Or download manually:")):console.log("Download from:"),console.log(e?` ${e.url}
718
718
  `:` https://github.com/sourcegraph/scip/releases/tag/${Su}
719
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function xu(e){if(Ss()==="darwin"&&De("brew")){e("Installing scip CLI via Homebrew...");try{if(bu("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),De("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(De("go")){e("Installing scip CLI via go install...");try{if(bu("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),De("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 yR=gR()==="win32",Ds=["concrete-plan","scip-ai-cleanup","scip-explore","scip-debloat","scip-maintainability","scip-verify","scip-language-playbook"];function Ru(e={}){let t=e.quiet?()=>{}:console.log,n=hR(import.meta.url),r=Is(Cu(n),"..","skills"),i=[ar(vs(),".claude","skills"),ar(vs(),".codex","skills"),ar(vs(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=Cu(s);if(!Rs(a))continue;mR(s,{recursive:!0});let c=bR(s);for(let l of Ds){let u=ar(r,l),m=ar(s,l);if(!Rs(u)){o.skipped.push(`${c}/${l}`);continue}if(Rs(m)){try{let d=pR(m);if(Is(d)===Is(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}fR(m)}dR(u,m,yR?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function bR(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as Dm}from"fs";import{execFileSync as kv}from"child_process";import{closeSync as Pv,existsSync as qs,mkdirSync as pm,mkdtempSync as Fv,openSync as Tv,readFileSync as Av,renameSync as Vs,rmSync as Ws,writeFileSync as fm}from"fs";import{basename as bi,dirname as Vt,extname as Mv,join as Xe}from"path";import SR from"better-sqlite3";import{execFileSync as xR}from"child_process";import{existsSync as CR,readdirSync as RR,readFileSync as IR}from"fs";import{extname as mi,join as Iu}from"path";function pt(e){let t=new Set((e.extensions??ec).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!CR(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=yn(e.projectRoot),r=vR(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new SR(e.dbPath);try{let o=NR(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
720
- VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let m=0;for(let d of u){if(o.has(d))continue;let p=IR(Iu(e.projectRoot,d),"utf-8"),h=s.run(LR(d),d,p);m+=Number(h.changes)}return m})(r),l={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{i.close()}}function vR(e,t){let n=DR(e,t);if(n)return n;let r=[],i=o=>{let s=o?Iu(e,o):e,a;try{a=RR(s,{withFileTypes:!0})}catch{return}for(let c of a){if(zi.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(mi(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function DR(e,t){try{return xR("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
721
- `).filter(r=>r&&t.has(mi(r).toLowerCase())).sort()}catch{return null}}function NR(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),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 LR(e){return mi(e).toLowerCase()===".vue"?"vue":mi(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as _R}from"child_process";import{existsSync as wR,readdirSync as Du}from"fs";import{extname as Nu,join as Lu}from"path";var ER=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),kR=[{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 Ht(e){let t=[],n=PR(e),r=MR(e);for(let i of kR){if(FR(e,i.files)){t.push(i.language);continue}if(TR(n,i.globs)){t.push(i.language);continue}$R(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&vu(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&vu(t,"c"),t}function PR(e){try{return Du(e)}catch{return[]}}function FR(e,t){return t?.length?t.some(n=>wR(Lu(e,n))):!1}function TR(e,t){return t?.length?e.some(n=>t.some(r=>AR(n,r))):!1}function AR(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function MR(e){let t=OR(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=Du(i,{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=Lu(i,s.name);if(s.isDirectory()){ER.has(s.name)||r.push(a);continue}let c=Nu(s.name).toLowerCase();c&&n.add(c)}}return n}function OR(e){try{let t=_R("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
722
- `)){if(!r)continue;let i=Nu(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function $R(e,t){return t?.length?t.some(n=>e.has(n)):!1}function vu(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as _u,readdirSync as jR}from"fs";import{join as Ns}from"path";var BR={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let r=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},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",wu(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",wu(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=Ns(e,"vendor","bin","scip-php"),r=Ns(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",_u(r)?r:_u(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function di(e){return BR[e]}function wu(e,t){let n;try{n=jR(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return Ns(e,r);return null}import{readFileSync as HR,writeFileSync as qR}from"fs";import{create as Ls}from"@bufbuild/protobuf";import{deserializeSCIP as VR,serializeSCIP as WR,DocumentSchema as UR,IndexSchema as GR,SymbolInformationSchema as JR}from"@c4312/scip";function zR(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=QR(e),n=KR(e.flatMap(i=>i.documents??[])),r=ku(e.flatMap(i=>i.externalSymbols??[]));return Ls(GR,{metadata:t,documents:n,externalSymbols:r})}function Eu(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>VR(HR(i))),r=zR(n);return qR(t,Buffer.from(WR(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function QR(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function KR(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Ls(UR,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:ku([...r.symbols,...n.symbols]),text:XR(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ku(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Ls(JR,{symbol:r.symbol,documentation:ZR([...r.documentation,...n.documentation]),relationships:YR([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function YR(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function XR(e,t){return e?t?e.length>=t.length?e:t:e:t}function ZR(e){return[...new Set(e)]}import{execFileSync as eI}from"child_process";import{createHash as tI}from"crypto";import{readdirSync as nI,readFileSync as rI}from"fs";import{join as Pu}from"path";function iI(e){return(oI(e)??sI(e)).filter(t=>t&&!Fu(t)).sort()}function pi(e){return iI(e).map(t=>{let n=Pu(e,t);try{let r=rI(n);return{path:t,size:r.byteLength,hash:tI("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function oI(e){try{return eI("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
723
- `).filter(Boolean)}catch{return null}}function sI(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Pu(e,r):e,o;try{o=nI(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Fu(a)||n.push(a);continue}t.push(a)}}return t}function Fu(e){return e.split("/").some(n=>aI.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var aI=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as cI,writeFileSync as lI}from"fs";import{create as Tu}from"@bufbuild/protobuf";import{deserializeSCIP as uI,DocumentSchema as mI,IndexSchema as dI,serializeSCIP as pI,SymbolRole as fI}from"@c4312/scip";function Au(e){let t;try{t=uI(cI(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=gI(t);return n.removedDefinitionOccurrences>0&&lI(e,Buffer.from(pI(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function gI(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,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&fI.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Tu(mI,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Tu(dI,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFile as hI}from"child_process";import{existsSync as fi,renameSync as ws,rmSync as Es}from"fs";import{cpus as yI}from"os";import{join as Mu}from"path";function bI(e,t,n){if(!e.defaultOutputPath)return;let r=Mu(t,e.defaultOutputPath);n!==r&&fi(r)&&ws(r,n)}function SI(e,t,n){if(!e.defaultOutputPath)return null;let r=Mu(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Es(i,{force:!0}),fi(r)?(ws(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function xI(e){e&&(Es(e.defaultOutputPath,{force:!0}),e.backupPath&&fi(e.backupPath)&&ws(e.backupPath,e.defaultOutputPath))}function CI(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,yI().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function Ou(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=CI(o.length,r),c=await II(o,a,l=>_s(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(m=>m.skipped)){let m=o.find(d=>d.language===u.language);m&&(n(`Retrying ${m.language} indexer serially after parallel failure...`),l.set(m.language,await _s(m,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of i)s.push(await _s(l,t,n));return s.sort((l,u)=>e.findIndex(m=>m.language===l.language)-e.findIndex(m=>m.language===u.language))}async function _s(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),Es(e.scipPath,{force:!0});let r=SI(e.config,t,e.scipPath);try{await RI(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),bI(e.config,t,e.scipPath)}catch(i){let o=i instanceof Error?i.message:String(i),s=`${e.resolvedBinary} indexer failed: ${o.split(`
724
- `)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{xI(r)}if(!fi(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${i}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:i}}}return{language:e.language,scipPath:e.scipPath}}function RI(e,t,n){return new Promise((r,i)=>{hI(e,[...t],n,o=>{o?i(o):r()})})}async function II(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(s),r}import{execFileSync as Ps}from"child_process";import{existsSync as ks,readFileSync as vI}from"fs";import{createRequire as DI}from"module";import{platform as NI}from"os";import{dirname as $u,join as gi}from"path";var LI=DI(import.meta.url);function Fs(e){return[e.indexerBinary,...e.binaryAliases??[]]}function hi(e){let t=Fs(e);return t.length===1?t[0]:t.join(" or ")}function Cn(e){for(let t of Fs(e))if(De(t))return t;return wI(e)}function ju(e){return Cn(e)!==null||_I(e)}function _I(e){return Bu(e)!==null}function wI(e){let t=Bu(e);if(!t)return null;let r=JSON.parse(vI(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return gi($u(t),r);for(let i of Fs(e)){let o=r[i];if(o)return gi($u(t),o)}return null}function Bu(e){if(!e.bundledNpmPackage)return null;try{return LI.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Ts(e,t){for(let n of e.projectLocalBinaries??[]){let r=gi(t,n);if(ks(r))return r}return null}function EI(e,t){return Ts(e,t)??Cn(e)}function Hu(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||As(n,t))return t;let r=Wu(n,t);return r?{...t,DOTNET_ROOT:r}:t}function qu(e,t){let n=hi(e),r=t?EI(e,t):Cn(e);if(!r)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:r};let i=kI(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Vu(e,t){let n=e.installMethods,r=hi(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(De(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Ps(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Cn(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${s}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function kI(e){if(As(e,process.env))return{runnable:!0};let t=Wu(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Uu(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 Wu(e,t){for(let n of Uu(t))if(As(e,{...t,DOTNET_ROOT:n}))return n;return null}function Uu(e){let t=[],n=e.DOTNET_ROOT;if(n&&ks(n)&&t.push(n),NI()==="darwin"&&De("brew"))try{let r=Ps("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=gi(r,"libexec");ks(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function As(e,t){try{return Ps(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import mv from"better-sqlite3";import{existsSync as dv,readFileSync as pv,writeFileSync as fv}from"fs";import{dirname as gv,join as hv,resolve as yv}from"path";import{readFileSync as PI,rmSync as FI,statSync as TI,mkdtempSync as AI}from"fs";import{cpus as MI,tmpdir as OI}from"os";import{join as Ms}from"path";import{Worker as $I}from"worker_threads";function Gu(e){return e.length>=8&&zu(e.length)>1}function Ju(e){let t=zu(e.vueFiles.length),n=BI(e.vueFiles),r=qI(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=AI(Ms(OI(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=jI(),l=Date.now();try{for(let m=0;m<r.length;m++)new $I(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:Ms(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.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=r.map((m,d)=>{let p=JSON.parse(PI(Ms(o,`${d}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(m=>m.occurrences),skippedReferences:u.reduce((m,d)=>m+d.skippedReferences,0)}}finally{FI(o,{recursive:!0,force:!0})}}function zu(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,MI().length-1));return Math.max(1,Math.min(e,n))}function jI(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function BI(e){let t=HI(),n=[];for(let r of e){let i=Qu(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({fileName:r,startOffset:Math.floor(i*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(s+1)/o),countFileSkip:s===0})}return n}function HI(){return Number.POSITIVE_INFINITY}function qI(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:VI(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function VI(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Qu(e.fileName)-e.startOffset)}function Qu(e){try{return TI(e).size}catch{return 1}}import{createRequire as WI}from"module";import{existsSync as UI,readFileSync as $s}from"fs";import{dirname as Ku,extname as GI,join as Yu,relative as JI,resolve as zI}from"path";import{pathToFileURL as QI}from"url";function KI(e){e.transaction(()=>{e.prepare(`
719
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function xu(e){if(Ss()==="darwin"&&De("brew")){e("Installing scip CLI via Homebrew...");try{if(bu("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),De("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(De("go")){e("Installing scip CLI via go install...");try{if(bu("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),De("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 SR=yR()==="win32",Ds=["concrete-plan","scip-ai-cleanup","scip-explore","scip-debloat","scip-doc-reconcile","scip-maintainability","scip-verify","scip-language-playbook"];function Ru(e={}){let t=e.quiet?()=>{}:console.log,n=bR(import.meta.url),r=Is(Cu(n),"..","skills"),i=[ar(vs(),".claude","skills"),ar(vs(),".codex","skills"),ar(vs(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=Cu(s);if(!Rs(a))continue;pR(s,{recursive:!0});let c=xR(s);for(let l of Ds){let u=ar(r,l),m=ar(s,l);if(!Rs(u)){o.skipped.push(`${c}/${l}`);continue}if(Rs(m)){try{let d=gR(m);if(Is(d)===Is(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}hR(m)}fR(u,m,SR?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function xR(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as Dm}from"fs";import{execFileSync as Fv}from"child_process";import{closeSync as Av,existsSync as qs,mkdirSync as pm,mkdtempSync as Tv,openSync as Mv,readFileSync as Ov,renameSync as Vs,rmSync as Ws,writeFileSync as fm}from"fs";import{basename as bi,dirname as Wt,extname as $v,join as Ze}from"path";import CR from"better-sqlite3";import{execFileSync as RR}from"child_process";import{existsSync as IR,readdirSync as vR,readFileSync as DR}from"fs";import{extname as mi,join as Iu}from"path";function ft(e){let t=new Set((e.extensions??ec).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!IR(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=yn(e.projectRoot),r=NR(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new CR(e.dbPath);try{let o=_R(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
720
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let m=0;for(let d of u){if(o.has(d))continue;let p=DR(Iu(e.projectRoot,d),"utf-8"),h=s.run(wR(d),d,p);m+=Number(h.changes)}return m})(r),l={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{i.close()}}function NR(e,t){let n=LR(e,t);if(n)return n;let r=[],i=o=>{let s=o?Iu(e,o):e,a;try{a=vR(s,{withFileTypes:!0})}catch{return}for(let c of a){if(zi.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(mi(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function LR(e,t){try{return RR("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
721
+ `).filter(r=>r&&t.has(mi(r).toLowerCase())).sort()}catch{return null}}function _R(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),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 wR(e){return mi(e).toLowerCase()===".vue"?"vue":mi(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as ER}from"child_process";import{existsSync as kR,readdirSync as Du}from"fs";import{extname as Nu,join as Lu}from"path";var PR=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),FR=[{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 qt(e){let t=[],n=AR(e),r=$R(e);for(let i of FR){if(TR(e,i.files)){t.push(i.language);continue}if(MR(n,i.globs)){t.push(i.language);continue}BR(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&vu(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&vu(t,"c"),t}function AR(e){try{return Du(e)}catch{return[]}}function TR(e,t){return t?.length?t.some(n=>kR(Lu(e,n))):!1}function MR(e,t){return t?.length?e.some(n=>t.some(r=>OR(n,r))):!1}function OR(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function $R(e){let t=jR(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=Du(i,{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=Lu(i,s.name);if(s.isDirectory()){PR.has(s.name)||r.push(a);continue}let c=Nu(s.name).toLowerCase();c&&n.add(c)}}return n}function jR(e){try{let t=ER("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
722
+ `)){if(!r)continue;let i=Nu(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function BR(e,t){return t?.length?t.some(n=>e.has(n)):!1}function vu(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as _u,readdirSync as HR}from"fs";import{join as Ns}from"path";var qR={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let r=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},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",wu(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",wu(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=Ns(e,"vendor","bin","scip-php"),r=Ns(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",_u(r)?r:_u(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function di(e){return qR[e]}function wu(e,t){let n;try{n=HR(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return Ns(e,r);return null}import{readFileSync as VR,writeFileSync as WR}from"fs";import{create as Ls}from"@bufbuild/protobuf";import{deserializeSCIP as UR,serializeSCIP as GR,DocumentSchema as JR,IndexSchema as zR,SymbolInformationSchema as QR}from"@c4312/scip";function KR(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=YR(e),n=XR(e.flatMap(i=>i.documents??[])),r=ku(e.flatMap(i=>i.externalSymbols??[]));return Ls(zR,{metadata:t,documents:n,externalSymbols:r})}function Eu(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>UR(VR(i))),r=KR(n);return WR(t,Buffer.from(GR(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function YR(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function XR(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Ls(JR,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:ku([...r.symbols,...n.symbols]),text:eI(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ku(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Ls(QR,{symbol:r.symbol,documentation:tI([...r.documentation,...n.documentation]),relationships:ZR([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function ZR(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function eI(e,t){return e?t?e.length>=t.length?e:t:e:t}function tI(e){return[...new Set(e)]}import{execFileSync as nI}from"child_process";import{createHash as rI}from"crypto";import{readdirSync as iI,readFileSync as oI}from"fs";import{join as Pu}from"path";function sI(e){return(aI(e)??cI(e)).filter(t=>t&&!Fu(t)).sort()}function pi(e){return sI(e).map(t=>{let n=Pu(e,t);try{let r=oI(n);return{path:t,size:r.byteLength,hash:rI("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function aI(e){try{return nI("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
723
+ `).filter(Boolean)}catch{return null}}function cI(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Pu(e,r):e,o;try{o=iI(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Fu(a)||n.push(a);continue}t.push(a)}}return t}function Fu(e){return e.split("/").some(n=>lI.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var lI=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as uI,writeFileSync as mI}from"fs";import{create as Au}from"@bufbuild/protobuf";import{deserializeSCIP as dI,DocumentSchema as pI,IndexSchema as fI,serializeSCIP as gI,SymbolRole as hI}from"@c4312/scip";function Tu(e){let t;try{t=dI(uI(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=yI(t);return n.removedDefinitionOccurrences>0&&mI(e,Buffer.from(gI(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function yI(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,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&hI.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Au(pI,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Au(fI,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFile as bI}from"child_process";import{existsSync as fi,renameSync as ws,rmSync as Es}from"fs";import{cpus as SI}from"os";import{join as Mu}from"path";function xI(e,t,n){if(!e.defaultOutputPath)return;let r=Mu(t,e.defaultOutputPath);n!==r&&fi(r)&&ws(r,n)}function CI(e,t,n){if(!e.defaultOutputPath)return null;let r=Mu(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Es(i,{force:!0}),fi(r)?(ws(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function RI(e){e&&(Es(e.defaultOutputPath,{force:!0}),e.backupPath&&fi(e.backupPath)&&ws(e.backupPath,e.defaultOutputPath))}function II(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,SI().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function Ou(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=II(o.length,r),c=await DI(o,a,l=>_s(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(m=>m.skipped)){let m=o.find(d=>d.language===u.language);m&&(n(`Retrying ${m.language} indexer serially after parallel failure...`),l.set(m.language,await _s(m,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of i)s.push(await _s(l,t,n));return s.sort((l,u)=>e.findIndex(m=>m.language===l.language)-e.findIndex(m=>m.language===u.language))}async function _s(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),Es(e.scipPath,{force:!0});let r=CI(e.config,t,e.scipPath);try{await vI(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),xI(e.config,t,e.scipPath)}catch(i){let o=i instanceof Error?i.message:String(i),s=`${e.resolvedBinary} indexer failed: ${o.split(`
724
+ `)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{RI(r)}if(!fi(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${i}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:i}}}return{language:e.language,scipPath:e.scipPath}}function vI(e,t,n){return new Promise((r,i)=>{bI(e,[...t],n,o=>{o?i(o):r()})})}async function DI(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(s),r}import{execFileSync as Ps}from"child_process";import{existsSync as ks,readFileSync as NI}from"fs";import{createRequire as LI}from"module";import{platform as _I}from"os";import{dirname as $u,join as gi}from"path";var wI=LI(import.meta.url);function Fs(e){return[e.indexerBinary,...e.binaryAliases??[]]}function hi(e){let t=Fs(e);return t.length===1?t[0]:t.join(" or ")}function Cn(e){for(let t of Fs(e))if(De(t))return t;return kI(e)}function ju(e){return Cn(e)!==null||EI(e)}function EI(e){return Bu(e)!==null}function kI(e){let t=Bu(e);if(!t)return null;let r=JSON.parse(NI(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return gi($u(t),r);for(let i of Fs(e)){let o=r[i];if(o)return gi($u(t),o)}return null}function Bu(e){if(!e.bundledNpmPackage)return null;try{return wI.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function As(e,t){for(let n of e.projectLocalBinaries??[]){let r=gi(t,n);if(ks(r))return r}return null}function PI(e,t){return As(e,t)??Cn(e)}function Hu(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Ts(n,t))return t;let r=Wu(n,t);return r?{...t,DOTNET_ROOT:r}:t}function qu(e,t){let n=hi(e),r=t?PI(e,t):Cn(e);if(!r)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:r};let i=FI(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Vu(e,t){let n=e.installMethods,r=hi(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(De(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Ps(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Cn(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${s}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function FI(e){if(Ts(e,process.env))return{runnable:!0};let t=Wu(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Uu(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 Wu(e,t){for(let n of Uu(t))if(Ts(e,{...t,DOTNET_ROOT:n}))return n;return null}function Uu(e){let t=[],n=e.DOTNET_ROOT;if(n&&ks(n)&&t.push(n),_I()==="darwin"&&De("brew"))try{let r=Ps("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=gi(r,"libexec");ks(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Ts(e,t){try{return Ps(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import pv from"better-sqlite3";import{existsSync as fv,readFileSync as gv,writeFileSync as hv}from"fs";import{dirname as yv,join as bv,resolve as Sv}from"path";import{readFileSync as AI,rmSync as TI,statSync as MI,mkdtempSync as OI}from"fs";import{cpus as $I,tmpdir as jI}from"os";import{join as Ms}from"path";import{Worker as BI}from"worker_threads";function Gu(e){return e.length>=8&&zu(e.length)>1}function Ju(e){let t=zu(e.vueFiles.length),n=qI(e.vueFiles),r=WI(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=OI(Ms(jI(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=HI(),l=Date.now();try{for(let m=0;m<r.length;m++)new BI(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:Ms(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.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=r.map((m,d)=>{let p=JSON.parse(AI(Ms(o,`${d}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(m=>m.occurrences),skippedReferences:u.reduce((m,d)=>m+d.skippedReferences,0)}}finally{TI(o,{recursive:!0,force:!0})}}function zu(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,$I().length-1));return Math.max(1,Math.min(e,n))}function HI(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function qI(e){let t=VI(),n=[];for(let r of e){let i=Qu(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({fileName:r,startOffset:Math.floor(i*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(s+1)/o),countFileSkip:s===0})}return n}function VI(){return Number.POSITIVE_INFINITY}function WI(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:UI(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function UI(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Qu(e.fileName)-e.startOffset)}function Qu(e){try{return MI(e).size}catch{return 1}}import{createRequire as GI}from"module";import{existsSync as JI,readFileSync as $s}from"fs";import{dirname as Ku,extname as zI,join as Yu,relative as QI,resolve as KI}from"path";import{pathToFileURL as YI}from"url";function XI(e){e.transaction(()=>{e.prepare(`
725
725
  DELETE FROM mentions
726
726
  WHERE chunk_id IN (
727
727
  SELECT c.id
@@ -741,7 +741,7 @@ Affected consumer files:`),_.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
741
741
  FROM documents
742
742
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
743
743
  ORDER BY relative_path
744
- `).all().map(r=>zI(t,r.relativePath))}function Zu(e,t){let{vueCore:n,ts:r,volarTs:i}=YI(e),{parsed:o,vueOptions:s}=XI(n,r,t),a=Ku(t),c=n.createVueLanguagePlugin(r,o.options,s,p=>p),l=ZI(n,r,c),u=ev(a,o),{languageServiceHost:m}=i.createLanguageServiceHost(r,r.sys,l,p=>p,u),d=r.createLanguageService(m);return{ts:r,language:l,languageService:d,fileNames:o.fileNames,configDir:a}}function YI(e){let t=WI(QI(Yu(e,"package.json")).href);return{vueCore:Os(t,"@vue/language-core",e),ts:Os(t,"typescript",e),volarTs:Os(t,"@volar/typescript",e)}}function XI(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.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(r.config,t.sys,Ku(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function ZI(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!UI(o))return;let s=$s(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??sv(o))});return r.current=i,i}function ev(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Os(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.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:r}):r}}function em(e,t,n){let r=tv(e);return i=>{let o=qt(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:nv(c.starts,a.line,2)}}function tv(e){let t=e.prepare(`
744
+ `).all().map(r=>KI(t,r.relativePath))}function Zu(e,t){let{vueCore:n,ts:r,volarTs:i}=ZI(e),{parsed:o,vueOptions:s}=ev(n,r,t),a=Ku(t),c=n.createVueLanguagePlugin(r,o.options,s,p=>p),l=tv(n,r,c),u=nv(a,o),{languageServiceHost:m}=i.createLanguageServiceHost(r,r.sys,l,p=>p,u),d=r.createLanguageService(m);return{ts:r,language:l,languageService:d,fileNames:o.fileNames,configDir:a}}function ZI(e){let t=GI(YI(Yu(e,"package.json")).href);return{vueCore:Os(t,"@vue/language-core",e),ts:Os(t,"typescript",e),volarTs:Os(t,"@volar/typescript",e)}}function ev(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.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(r.config,t.sys,Ku(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function tv(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!JI(o))return;let s=$s(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??cv(o))});return r.current=i,i}function nv(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Os(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.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:r}):r}}function em(e,t,n){let r=rv(e);return i=>{let o=Vt(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:iv(c.starts,a.line,2)}}function rv(e){let t=e.prepare(`
745
745
  SELECT
746
746
  d.relative_path AS relativePath,
747
747
  der.start_line AS startLine,
@@ -750,22 +750,22 @@ Affected consumer files:`),_.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
750
750
  FROM defn_enclosing_ranges der
751
751
  JOIN documents d ON d.id = der.document_id
752
752
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
753
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,r.symbolId)}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function nv(e,t,n){let r=0,i=e.length-1;for(;r<=i;){let s=Math.floor((r+i)/2);e[s].line<t?r=s+1:i=s-1}let o=null;for(let s of[i,r]){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 tm(e,t,n){let r=lv(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
753
+ `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,r.symbolId)}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function iv(e,t,n){let r=0,i=e.length-1;for(;r<=i;){let s=Math.floor((r+i)/2);e[s].line<t?r=s+1:i=s-1}let o=null;for(let s of[i,r]){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 tm(e,t,n){let r=mv(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
754
754
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
755
755
  VALUES (?, ?, ?, ?)
756
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=qt(t,l),m=um(r.name,r.version,u);o.run(m,"default",7,`Vue component|${u}`);let d=uv(i,r,t,l);d&&(s++,a.set(l,d))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function nm(e,t,n,r,i){return e.transaction(()=>(KI(e),rv(e,t,n,r),iv(e,i)))()}function rv(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
756
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Vt(t,l),m=um(r.name,r.version,u);o.run(m,"default",7,`Vue component|${u}`);let d=dv(i,r,t,l);d&&(s++,a.set(l,d))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function nm(e,t,n,r,i){return e.transaction(()=>(XI(e),ov(e,t,n,r),sv(e,i)))()}function ov(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
757
757
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
758
758
  VALUES (?, ?, ?, ?, X'00')
759
759
  `),s=e.prepare(`
760
760
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
761
761
  VALUES (?, ?, 1)
762
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=qt(t,a),u=i.get(l);if(!u)continue;let m=o.run(u.id,-1,0,0);s.run(Number(m.lastInsertRowid),c)}}function rm(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(js(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function im(e){let t=new Set,n=[];for(let r of e){let i=om(r);t.has(i)||(t.add(i),n.push(r))}return n}function om(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function iv(e,t){let n=cv(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
762
+ `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Vt(t,a),u=i.get(l);if(!u)continue;let m=o.run(u.id,-1,0,0);s.run(Number(m.lastInsertRowid),c)}}function rm(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(js(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function im(e){let t=new Set,n=[];for(let r of e){let i=om(r);t.has(i)||(t.add(i),n.push(r))}return n}function om(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function sv(e,t){let n=uv(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
763
763
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
764
764
  VALUES (?, ?, ?, ?, X'00')
765
765
  `),i=e.prepare(`
766
766
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
767
767
  VALUES (?, ?, 0)
768
- `),o=new Set,s=0,a=0;for(let c of t){let l=om(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let m=r.run(u,a++,c.sourceLine,c.sourceLine),d=i.run(Number(m.lastInsertRowid),c.symbolId);s+=Number(d.changes)}return s}function*sm(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"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function am(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function js(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function ov(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function cm(e,t){return qt(e,t).startsWith("node_modules/")}function qt(e,t){return JI(e,t).replaceAll("\\","/")}function sv(e){switch(GI(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 lm(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=$s(t,"utf-8"),r={text:n,lineStarts:av(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:ov}}function av(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function cv(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),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 lv(e){try{let t=JSON.parse($s(Yu(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 uv(e,t,n,r){let i=qt(n,r),o=um(t.name,t.version,i);return e.get(o)?.id??null}function um(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Bs(e){pt({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=yv(e.projectRoot,e.tsconfig);if(!dv(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new mv(e.dbPath);try{let r=Xu(n,e.projectRoot),i=hv(gv(e.dbPath),"augment-vue-meta.json"),o=mm(n,e.projectRoot,e.tsconfig),s=bv(i,o,e.onStatus);if(s)return s;let a=Sv({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return Rv(i,mm(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function bv(e,t,n){let r=Cv(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function Sv(e){let t=tm(e.db,e.projectRoot,e.vueFiles),n=xv(e,t),r=im(n.occurrences),i=nm(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,insertedMentions:i,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function xv(e,t){if(Gu(e.vueFiles))return Ju({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Iv({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return vv({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Cv(e,t){try{let n=JSON.parse(pv(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function Rv(e,t,n){fv(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
768
+ `),o=new Set,s=0,a=0;for(let c of t){let l=om(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let m=r.run(u,a++,c.sourceLine,c.sourceLine),d=i.run(Number(m.lastInsertRowid),c.symbolId);s+=Number(d.changes)}return s}function*sm(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"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function am(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function js(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function av(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function cm(e,t){return Vt(e,t).startsWith("node_modules/")}function Vt(e,t){return QI(e,t).replaceAll("\\","/")}function cv(e){switch(zI(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 lm(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=$s(t,"utf-8"),r={text:n,lineStarts:lv(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:av}}function lv(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function uv(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),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 mv(e){try{let t=JSON.parse($s(Yu(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 dv(e,t,n,r){let i=Vt(n,r),o=um(t.name,t.version,i);return e.get(o)?.id??null}function um(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Bs(e){ft({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=Sv(e.projectRoot,e.tsconfig);if(!fv(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new pv(e.dbPath);try{let r=Xu(n,e.projectRoot),i=bv(yv(e.dbPath),"augment-vue-meta.json"),o=mm(n,e.projectRoot,e.tsconfig),s=xv(i,o,e.onStatus);if(s)return s;let a=Cv({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return vv(i,mm(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function xv(e,t,n){let r=Iv(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function Cv(e){let t=tm(e.db,e.projectRoot,e.vueFiles),n=Rv(e,t),r=im(n.occurrences),i=nm(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,insertedMentions:i,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Rv(e,t){if(Gu(e.vueFiles))return Ju({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Dv({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Nv({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Iv(e,t){try{let n=JSON.parse(gv(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function vv(e,t,n){hv(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
769
769
  `)}function mm(e,t,n){let r=e.prepare(`
770
770
  SELECT
771
771
  (SELECT COUNT(*) FROM documents) AS documents,
@@ -775,108 +775,108 @@ Affected consumer files:`),_.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
775
775
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
776
776
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
777
777
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
778
- `).get();return{version:2,tsconfig:n,files:pi(t),db:r}}function Iv(e){let t=lm();return{projectRoot:e.projectRoot,context:Zu(e.projectRoot,e.configPath),symbolLookup:em(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function vv(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Dv(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function Dv(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceReader.get(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(r,n),s=qt(e.projectRoot,t.fileName),a=[...sm(i.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:_v(a),processedStarts:new Set};return Nv({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:c})}function Nv(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=am(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(c=>!cm(e.projectRoot,c.fileName));if(!s){n++;continue}let a=rm(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}dm(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),Lv(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function Lv(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of wv(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(dm(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function dm(e,t,n,r,i,o){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,symbolId:o})}function _v(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function wv(e,t,n,r,i,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=Ev(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function Ev(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=js(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function gm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Ov(e),s=Date.now();pm(Vt(o.outputScip),{recursive:!0}),pm(Vt(o.outputDb),{recursive:!0});let a=e.languages??Ht(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.");r(`Detected languages: ${a.join(", ")}`);let c=Zv(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=Yv(Xe(Vt(o.outputDb),"index.lock")),u=null;try{let m=$v({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r});if(m)return m;Vv(i,r);let d=jv(o);return u=d.runDir,await Bv({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:d,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&Ws(u,{recursive:!0,force:!0}),l()}}function Ov(e){let t=e.outputScip??Xe(e.projectRoot,"index.scip"),n=e.outputDb??Xe(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:Xe(Vt(n),"meta.json")}}function $v(e){if(e.opts.skipIfUnchanged===!1||!qs(e.paths.outputScip)||!qs(e.paths.outputDb)||!eD(e.paths.metaPath,e.fingerprint))return null;pt({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 jv(e){let t=Fv(Xe(Vt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:Xe(t,bi(e.outputScip)),tempOutputDb:Xe(t,bi(e.outputDb)),tempMetaPath:Xe(t,bi(e.metaPath))}}async function Bv(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await Hv(e,t);qv(e,t,n,r);let i=Date.now()-e.start;return e.onStatus(`Done in ${(i/1e3).toFixed(1)}s`),{languages:n.map(o=>o.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!1,skipped:r}}async function Hv(e,t){let{preparedRuns:n,skippedLanguages:r}=Wv({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await Ou(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:o}=Gv(i,r);return Jv(o,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:o,skippedLanguages:r}}function qv(e,t,n,r){zv(n,e.tempPaths.tempOutputScip,e.onStatus),Qv(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),pt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),tD(e.tempPaths.tempMetaPath,{version:2,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,requestedLanguages:e.languages,indexedLanguages:n.map(i=>i.language),skipped:[...r]}),Xv({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 Vv(e,t){if(!De("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
778
+ `).get();return{version:2,tsconfig:n,files:pi(t),db:r}}function Dv(e){let t=lm();return{projectRoot:e.projectRoot,context:Zu(e.projectRoot,e.configPath),symbolLookup:em(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Nv(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Lv(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function Lv(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceReader.get(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(r,n),s=Vt(e.projectRoot,t.fileName),a=[...sm(i.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:Ev(a),processedStarts:new Set};return _v({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:c})}function _v(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=am(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(c=>!cm(e.projectRoot,c.fileName));if(!s){n++;continue}let a=rm(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}dm(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),wv(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function wv(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of kv(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(dm(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function dm(e,t,n,r,i,o){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,symbolId:o})}function Ev(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function kv(e,t,n,r,i,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=Pv(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function Pv(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=js(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function gm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=jv(e),s=Date.now();pm(Wt(o.outputScip),{recursive:!0}),pm(Wt(o.outputDb),{recursive:!0});let a=e.languages??qt(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.");r(`Detected languages: ${a.join(", ")}`);let c=tD(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=Zv(Ze(Wt(o.outputDb),"index.lock")),u=null;try{let m=Bv({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r});if(m)return m;Uv(i,r);let d=Hv(o);return u=d.runDir,await qv({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:d,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&Ws(u,{recursive:!0,force:!0}),l()}}function jv(e){let t=e.outputScip??Ze(e.projectRoot,"index.scip"),n=e.outputDb??Ze(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:Ze(Wt(n),"meta.json")}}function Bv(e){if(e.opts.skipIfUnchanged===!1||!qs(e.paths.outputScip)||!qs(e.paths.outputDb)||!nD(e.paths.metaPath,e.fingerprint))return null;ft({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 Hv(e){let t=Tv(Ze(Wt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:Ze(t,bi(e.outputScip)),tempOutputDb:Ze(t,bi(e.outputDb)),tempMetaPath:Ze(t,bi(e.metaPath))}}async function qv(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await Vv(e,t);Wv(e,t,n,r);let i=Date.now()-e.start;return e.onStatus(`Done in ${(i/1e3).toFixed(1)}s`),{languages:n.map(o=>o.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!1,skipped:r}}async function Vv(e,t){let{preparedRuns:n,skippedLanguages:r}=Gv({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await Ou(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:o}=zv(i,r);return Qv(o,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:o,skippedLanguages:r}}function Wv(e,t,n,r){Kv(n,e.tempPaths.tempOutputScip,e.onStatus),Yv(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),ft({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),rD(e.tempPaths.tempMetaPath,{version:2,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,requestedLanguages:e.languages,indexedLanguages:n.map(i=>i.language),skipped:[...r]}),eD({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 Uv(e,t){if(!De("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
779
779
  Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!xu(t))throw new Error(`The scip CLI is required but could not be installed.
780
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Wv(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?Kv(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=Uv({...e,language:i,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function Uv(e){let t=di(e.language),n=hi(t),r=Ts(t,e.projectRoot);if(!r&&!ju(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...`),!Vu(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 i=r??Cn(t);if(!i){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:i});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:i,binary:o,args:s,env:Hu(t,e.env,i)}}}function Gv(e,t){let n=[];for(let r of e)r.skipped?t.push(r.skipped):n.push({language:r.language,scipPath:r.scipPath});return{indexedOutputs:n}}function Jv(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
780
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Gv(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?Xv(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=Jv({...e,language:i,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function Jv(e){let t=di(e.language),n=hi(t),r=As(t,e.projectRoot);if(!r&&!ju(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...`),!Vu(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 i=r??Cn(t);if(!i){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:i});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:i,binary:o,args:s,env:Hu(t,e.env,i)}}}function zv(e,t){let n=[];for(let r of e)r.skipped?t.push(r.skipped):n.push({language:r.language,scipPath:r.scipPath});return{indexedOutputs:n}}function Qv(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
781
781
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
782
782
  `+o)}if(t.length!==0&&(i(`Indexed ${e.length} of ${n.length} languages; skipped ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
783
783
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
784
- `))}function zv(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Eu(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&Vs(e[0].scipPath,t)}function Qv(e,t,n,r){if(r("Converting to SQLite..."),!qs(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=Au(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),kv("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:i})}}function Kv(e,t,n){let r=Mv(e)||".scip",i=bi(e,r);return Xe(Vt(e),`${i}.${n+1}.${t}${r}`)}function Yv(e){let t;try{t=Tv(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 ${Vt(e)}.`,{cause:n}):n}return fm(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
785
- `),()=>{try{Pv(t)}finally{Ws(e,{force:!0})}}}function Xv(e){Hs(e.tempOutputScip,e.outputScip),Hs(e.tempOutputDb,e.outputDb),Hs(e.tempMetaPath,e.metaPath)}function Hs(e,t){Ws(`${t}.tmp-replace`,{force:!0}),Vs(e,`${t}.tmp-replace`),Vs(`${t}.tmp-replace`,t)}function Zv(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:pi(e)}}function eD(e,t){try{let n=JSON.parse(Av(e,"utf-8"));return n.version===2&&n.status==="complete"&&yi(n.fingerprint)===yi(t)&&yi([...n.indexedLanguages??[]].sort())===yi(t.languages)}catch{return!1}}function tD(e,t){fm(e,`${JSON.stringify(t,null,2)}
786
- `)}function yi(e){return JSON.stringify(e)}import{createRequire as nD}from"module";var rD=nD(import.meta.url);function hm(e,t=[]){let n=iD(),r=no(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function iD(){try{return rD.resolve("ts-morph"),!0}catch{return!1}}function Us(e,t){let n=t.languages??Ht(e),r=n.map(o=>{let s=qu(di(o),e);return{...s,language:o,resolvedBinary:s.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...hm(e,t.semantic?.typescript?.tsconfigs)}:void 0;return{languages:n,indexers:r,semantic:i}}import{watch as oD}from"fs";import{existsSync as ym,renameSync as bm}from"fs";import{join as sD,relative as aD}from"path";import{fork as cD}from"child_process";import lD from"ignore";var Si=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=ou(t.config),this.indexPaths=Sn(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=yn(t.projectRoot),this.extraIgnore=lD(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=oD(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});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=aD(this.projectRoot,sD(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 r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),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 r=this.watchConfig.cooldownMs-t;this.dirty=!0;let i=Date.now()+r;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,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(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",o=uD(this.indexPaths.indexPath),s=cD(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:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{ym(i)&&bm(i,this.indexPaths.dbPath),ym(o)&&bm(o,this.indexPaths.indexPath),t(Date.now()-r)}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 uD(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}function q(e){return(...t)=>{let{args:n,opts:r}=mD(t);Ye(i=>e({db:i,args:n,opts:r}))}}function X(e,t){return q(n=>{let r=du(n.db,e,j(n.opts,"full"));t({...n,budget:r})})}function Sm(e){return q(t=>Rn(t,e,{kind:"list"}))}function xm(e){return q(t=>Rn(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function Cm(e){return q(t=>Rn(t,e,{kind:"grouped",key:e.key}))}function Wt(e){return q(t=>Gs(t,e))}function Rm(e){return Wt({query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>_.sectionedReport(e.sections(t,n)),after:e.after})}function cr(e,t){return X(e,n=>Gs(n,t))}function Im(e,t){return cr(e,{query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>_.sectionedReport(t.sections(n,r)),after:t.after})}function Ze(e,t){return X(e,n=>Rn(n,t,{kind:"list"}))}function xi(e,t){return X(e,n=>Rn(n,t,{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Ci(e,t){return X(e,n=>Rn(n,t,{kind:"grouped",key:t.key}))}function M(e,t){return String(e[t])}function He(e,t){let n=e[t];return typeof n=="string"?n:void 0}function k(e,t){let n=e[t];return typeof n=="string"?n:void 0}function ft(e,t){let n=e[t];return typeof n=="number"?n:void 0}function j(e,t){return!!e[t]}function vm(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function S(e,t,n){return ft(e,t)??n}function Rn(e,t,n){Gs(e,{query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?_.list(r,o=>t.format(o,i)):n.kind==="table"?_.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):_.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},after:t.after})}function Gs(e,t){let n=t.query(e),r=t.emptyMessage?.(n,e);if(r){_.empty(r);return}t.heuristicLabel&&or(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function mD(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:et(t)}}function et(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return n&&typeof n=="object"?n:{}}return e}var dD=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function pD(e){return e.filter(t=>dD.has(t))}async function Nm(e){let t=et(e),n=Be(),r=bn(n),i=Sn(n,r);try{let o=pD(vm(t,"language")),s=await gm({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:j(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!j(t,"force"),allowPartial:j(t,"allowPartial"),indexerConcurrency:ft(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 Lm(){let e=Be(),t=gs(e);try{let n=pt({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});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 _m(e){let t=et(e),n=Be(),r=gs(n);try{let i=Bs({projectRoot:n,dbPath:r,tsconfig:k(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function wm(e){let t=et(e);Ye(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=fn(n,{base:k(t,"base")}),o=Yr(n,r,i.changedFiles);console.log(JSON.stringify(o))})}function Em(e){let t=et(e);try{hu(gu({base:k(t,"base")}))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function km(e,t){let n=et(t);Ye(r=>{ir.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let i=ns(r,e,{scope:k(n,"scope"),full:j(n,"full")});console.log(JSON.stringify(i))})}function Pm(e){let t=et(e);if(j(t,"writeBaseline")||j(t,"baseline")){fD(t);return}try{let n=pu({scope:k(t,"scope"),full:j(t,"full"),json:j(t,"json")});fu(n,j(t,"json"))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function fD(e){let t=k(e,"scope");Ye(n=>{if(j(e,"writeBaseline")){let i=Yo(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Zn(n,{scope:t});if(r.fixedFindings.length>0&&console.log(`${r.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),r.newFindings.length===0){console.log(`OK: no new findings vs baseline (${r.baselineCount} baselined, ${r.current.length} current).`);return}console.log(`FAIL: ${r.newFindings.length} new finding(s) vs ${r.baselinePath}:`);for(let i of r.newFindings)console.log(` + ${i}`);process.exitCode=1})}function Fm(){let e=Ru(),t=e.installed.length+e.alreadyLinked.length;console.log(`
787
- ${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 Tm(){let e=!1;xs()?console.log("scip CLI: installed"):(Cs(),e=!0);let t=Be(),n=bn(t),r=Us(t,n);if(r.languages.length===0){console.log(`
784
+ `))}function Kv(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Eu(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&Vs(e[0].scipPath,t)}function Yv(e,t,n,r){if(r("Converting to SQLite..."),!qs(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=Tu(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),Fv("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:i})}}function Xv(e,t,n){let r=$v(e)||".scip",i=bi(e,r);return Ze(Wt(e),`${i}.${n+1}.${t}${r}`)}function Zv(e){let t;try{t=Mv(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 ${Wt(e)}.`,{cause:n}):n}return fm(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
785
+ `),()=>{try{Av(t)}finally{Ws(e,{force:!0})}}}function eD(e){Hs(e.tempOutputScip,e.outputScip),Hs(e.tempOutputDb,e.outputDb),Hs(e.tempMetaPath,e.metaPath)}function Hs(e,t){Ws(`${t}.tmp-replace`,{force:!0}),Vs(e,`${t}.tmp-replace`),Vs(`${t}.tmp-replace`,t)}function tD(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:pi(e)}}function nD(e,t){try{let n=JSON.parse(Ov(e,"utf-8"));return n.version===2&&n.status==="complete"&&yi(n.fingerprint)===yi(t)&&yi([...n.indexedLanguages??[]].sort())===yi(t.languages)}catch{return!1}}function rD(e,t){fm(e,`${JSON.stringify(t,null,2)}
786
+ `)}function yi(e){return JSON.stringify(e)}import{createRequire as iD}from"module";var oD=iD(import.meta.url);function hm(e,t=[]){let n=sD(),r=no(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function sD(){try{return oD.resolve("ts-morph"),!0}catch{return!1}}function Us(e,t){let n=t.languages??qt(e),r=n.map(o=>{let s=qu(di(o),e);return{...s,language:o,resolvedBinary:s.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...hm(e,t.semantic?.typescript?.tsconfigs)}:void 0;return{languages:n,indexers:r,semantic:i}}import{watch as aD}from"fs";import{existsSync as ym,renameSync as bm}from"fs";import{join as cD,relative as lD}from"path";import{fork as uD}from"child_process";import mD from"ignore";var Si=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=ou(t.config),this.indexPaths=Sn(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=yn(t.projectRoot),this.extraIgnore=mD(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=aD(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});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=lD(this.projectRoot,cD(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 r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),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 r=this.watchConfig.cooldownMs-t;this.dirty=!0;let i=Date.now()+r;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,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(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",o=dD(this.indexPaths.indexPath),s=uD(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:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{ym(i)&&bm(i,this.indexPaths.dbPath),ym(o)&&bm(o,this.indexPaths.indexPath),t(Date.now()-r)}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 dD(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}function q(e){return(...t)=>{let{args:n,opts:r}=pD(t);Xe(i=>e({db:i,args:n,opts:r}))}}function X(e,t){return q(n=>{let r=du(n.db,e,j(n.opts,"full"));t({...n,budget:r})})}function Sm(e){return q(t=>Rn(t,e,{kind:"list"}))}function xm(e){return q(t=>Rn(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function Cm(e){return q(t=>Rn(t,e,{kind:"grouped",key:e.key}))}function Ut(e){return q(t=>Gs(t,e))}function Rm(e){return Ut({query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>_.sectionedReport(e.sections(t,n)),after:e.after})}function cr(e,t){return X(e,n=>Gs(n,t))}function Im(e,t){return cr(e,{query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>_.sectionedReport(t.sections(n,r)),after:t.after})}function et(e,t){return X(e,n=>Rn(n,t,{kind:"list"}))}function xi(e,t){return X(e,n=>Rn(n,t,{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Ci(e,t){return X(e,n=>Rn(n,t,{kind:"grouped",key:t.key}))}function M(e,t){return String(e[t])}function qe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function k(e,t){let n=e[t];return typeof n=="string"?n:void 0}function gt(e,t){let n=e[t];return typeof n=="number"?n:void 0}function j(e,t){return!!e[t]}function vm(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function S(e,t,n){return gt(e,t)??n}function Rn(e,t,n){Gs(e,{query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?_.list(r,o=>t.format(o,i)):n.kind==="table"?_.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):_.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},after:t.after})}function Gs(e,t){let n=t.query(e),r=t.emptyMessage?.(n,e);if(r){_.empty(r);return}t.heuristicLabel&&or(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function pD(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:tt(t)}}function tt(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return n&&typeof n=="object"?n:{}}return e}var fD=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function gD(e){return e.filter(t=>fD.has(t))}async function Nm(e){let t=tt(e),n=He(),r=bn(n),i=Sn(n,r);try{let o=gD(vm(t,"language")),s=await gm({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:j(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!j(t,"force"),allowPartial:j(t,"allowPartial"),indexerConcurrency:gt(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 Lm(){let e=He(),t=gs(e);try{let n=ft({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});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 _m(e){let t=tt(e),n=He(),r=gs(n);try{let i=Bs({projectRoot:n,dbPath:r,tsconfig:k(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function wm(e){let t=tt(e);Xe(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=fn(n,{base:k(t,"base")}),o=Yr(n,r,i.changedFiles);console.log(JSON.stringify(o))})}function Em(e){let t=tt(e);try{hu(gu({base:k(t,"base")}))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function km(e,t){let n=tt(t);Xe(r=>{ir.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let i=ns(r,e,{scope:k(n,"scope"),full:j(n,"full")});console.log(JSON.stringify(i))})}function Pm(e){let t=tt(e);if(j(t,"writeBaseline")||j(t,"baseline")){hD(t);return}try{let n=pu({scope:k(t,"scope"),full:j(t,"full"),json:j(t,"json")});fu(n,j(t,"json"))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function hD(e){let t=k(e,"scope");Xe(n=>{if(j(e,"writeBaseline")){let i=Yo(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Zn(n,{scope:t});if(r.fixedFindings.length>0&&console.log(`${r.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),r.newFindings.length===0){console.log(`OK: no new findings vs baseline (${r.baselineCount} baselined, ${r.current.length} current).`);return}console.log(`FAIL: ${r.newFindings.length} new finding(s) vs ${r.baselinePath}:`);for(let i of r.newFindings)console.log(` + ${i}`);process.exitCode=1})}function Fm(){let e=Ru(),t=e.installed.length+e.alreadyLinked.length;console.log(`
787
+ ${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 Am(){let e=!1;xs()?console.log("scip CLI: installed"):(Cs(),e=!0);let t=He(),n=bn(t),r=Us(t,n);if(r.languages.length===0){console.log(`
788
788
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
789
789
  Detected languages: ${r.languages.join(", ")}`),console.log(`
790
790
  Indexer readiness:`);for(let i of r.indexers){let o=i.runnable?" OK":i.installed?" WARN":" MISSING",s=i.resolvedBinary?` (${i.resolvedBinary})`:"";console.log(`${o} ${i.language}: ${i.binaryLabel}${s}`),i.note&&console.log(` ${i.note}`),!i.installed&&i.installUrl&&console.log(` install: ${i.installUrl}`),i.runnable||(e=!0)}if(r.semantic){let i=r.semantic,o=i.available?" OK":i.dependencyAvailable?" WARN":" MISSING",s=i.tsconfigPaths&&i.tsconfigPaths.length>1?` (${i.tsconfigPaths.length} tsconfigs)`:i.tsconfigPath?` (${i.tsconfigPath})`:"";console.log(`
791
- Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function Am(){let e=Be(),t=Ht(e),n=su(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Mm(e){let t=et(e),n=Be(),r=bn(n),i=ft(t,"debounce"),o=ft(t,"cooldown");i&&((r.watch??={}).debounceMs=i),o&&((r.watch??={}).cooldownMs=o);let s=new Si({projectRoot:n,config:r,languages:r.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${cu(a)}`)},onReindexComplete:a=>{console.log(`
791
+ Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function Tm(){let e=He(),t=qt(e),n=su(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Mm(e){let t=tt(e),n=He(),r=bn(n),i=gt(t,"debounce"),o=gt(t,"cooldown");i&&((r.watch??={}).debounceMs=i),o&&((r.watch??={}).cooldownMs=o);let s=new Si({projectRoot:n,config:r,languages:r.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${cu(a)}`)},onReindexComplete:a=>{console.log(`
792
792
  Reindex complete in ${(a/1e3).toFixed(1)}s`)},onError:a=>{console.error(`
793
793
  Watch error: ${a.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${r.watch?.debounceMs??3e4}ms | Cooldown: ${r.watch?.cooldownMs??6e4}ms`),console.log(`Press Ctrl+C to stop.
794
794
  `),s.start(),process.on("SIGINT",()=>{s.stop(),console.log(`
795
- Stopped.`),process.exit(0)})}function Om(){let{projectRoot:e,config:t,paths:n,dbPath:r}=si(),i=Us(e,t);if(console.log(`Project: ${e}`),console.log(`DB path: ${r}`),r!==n.dbPath&&console.log(`Config: ${n.dbPath} (fallback to project root index.db)`),i.semantic){let o=i.semantic.available?"available":"fallback",s=i.semantic.tsconfigPaths&&i.semantic.tsconfigPaths.length>1?` (${i.semantic.tsconfigPaths.length} tsconfigs)`:i.semantic.tsconfigPath?` (${i.semantic.tsconfigPath})`:"";console.log(`TS sem: ${o}${s}`),i.semantic.reason&&console.log(`TS note: ${i.semantic.reason}`)}console.log(`Exists: ${Dm(r)?"yes":"no"}`),Dm(r)&&Ye(o=>{let s=Ne(o);if(console.log(`Symbols: ${s.symbols}`),console.log(`Files: ${s.documents}`),console.log(`Size: ${xn(s.indexSizeBytes)}`),s.lastBuilt){let a=Math.round((Date.now()-s.lastBuilt.getTime())/1e3);console.log(`Built: ${a}s ago`)}})}import{execFileSync as Js,spawnSync as hD}from"child_process";import{existsSync as Ut,mkdtempSync as yD,readFileSync as bD,readdirSync as SD,rmSync as xD,symlinkSync as CD,writeFileSync as RD}from"fs";import{tmpdir as ID}from"os";import{join as tt}from"path";var vD=3e5,DD=12;function Bm(e,t,n={}){let r=LD(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let i=ND(t,r),o=n.timeoutMs??vD,s=wD(e,t),a=yD(tt(ID(),"scip-cleanup-verify-")),c=[],l=0;try{Js("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),ED(e,a);let u=new Set;for(let m of r)for(let d of jm(m,a,o).errorKeys)u.add(d);l=u.size;for(let m of t.batches){kD(a,m);let d=[];for(let p of r){let h=jm(p,a,o);d.push(...h.rawErrors.filter(f=>!u.has(Hm(f))))}if(d.length===0)c.push({depth:m.depth,status:"verified"});else{c.push({depth:m.depth,status:"failed",errors:d.slice(0,DD)});break}}}finally{try{Js("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{xD(a,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:l,dirtyOverlap:s,batches:c}}function ND(e,t){let n=new Set(t.flatMap(i=>i.coversExtensions));return[...new Set(e.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>{let o=i.slice(i.lastIndexOf("."));return!n.has(o)}).sort()}function Hm(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var $m=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function LD(e){let t=[];if(Ut(tt(e,"tsconfig.json"))){let n=tt(e,"node_modules",".bin","tsc");t.push(Ut(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:$m}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:$m})}for(let n of _D(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:tt(e,n,"..","target")}});return t}function _D(e){let t=[];if(Ut(tt(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n=[];try{n=SD(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||Ut(tt(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function wD(e,t){let n;try{n=Js("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let r=new Set(n.split(`
796
- `).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>r.has(o)).sort()}function ED(e,t){for(let n of["node_modules"]){let r=tt(e,n),i=tt(t,n);if(Ut(r)&&!Ut(i))try{CD(r,i,"junction")}catch{}}}function kD(e,t){let n=new Map;for(let r of t.entries){let i=n.get(r.file)??[];i.push({start:r.startLine,end:r.endLine}),n.set(r.file,i)}for(let[r,i]of n){let o=tt(e,r);Ut(o)&&RD(o,PD(bD(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function PD(e,t,n={}){let r=e.split(`
797
- `),i=(n.rust===!0?FD(e):It(e)).split(`
798
- `),o=new Set;for(let s of t){let a=TD(r,s.start),c=MD(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
799
- `)}function FD(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 TD(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var AD=200;function MD(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>AD)break}return n}function jm(e,t,n){let r=hD(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(r.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${r.stdout??""}
795
+ Stopped.`),process.exit(0)})}function Om(){let{projectRoot:e,config:t,paths:n,dbPath:r}=si(),i=Us(e,t);if(console.log(`Project: ${e}`),console.log(`DB path: ${r}`),r!==n.dbPath&&console.log(`Config: ${n.dbPath} (fallback to project root index.db)`),i.semantic){let o=i.semantic.available?"available":"fallback",s=i.semantic.tsconfigPaths&&i.semantic.tsconfigPaths.length>1?` (${i.semantic.tsconfigPaths.length} tsconfigs)`:i.semantic.tsconfigPath?` (${i.semantic.tsconfigPath})`:"";console.log(`TS sem: ${o}${s}`),i.semantic.reason&&console.log(`TS note: ${i.semantic.reason}`)}console.log(`Exists: ${Dm(r)?"yes":"no"}`),Dm(r)&&Xe(o=>{let s=Ne(o);if(console.log(`Symbols: ${s.symbols}`),console.log(`Files: ${s.documents}`),console.log(`Size: ${xn(s.indexSizeBytes)}`),s.lastBuilt){let a=Math.round((Date.now()-s.lastBuilt.getTime())/1e3);console.log(`Built: ${a}s ago`)}})}import{execFileSync as Js,spawnSync as Hm}from"child_process";import{existsSync as nt,mkdtempSync as bD,readFileSync as SD,readdirSync as xD,rmSync as CD,symlinkSync as RD,writeFileSync as ID}from"fs";import{tmpdir as vD}from"os";import{join as Fe}from"path";var DD=3e5,ND=12;function qm(e,t,n={}){let r=_D(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let i=LD(t,r),o=n.timeoutMs??DD,s=kD(e,t),a=bD(Fe(vD(),"scip-cleanup-verify-")),c=[],l=0;try{Js("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),PD(e,a);let u=new Set;for(let m of r)for(let d of Bm(m,a,o).errorKeys)u.add(d);l=u.size;for(let m of t.batches){FD(a,m);let d=[];for(let p of r){let h=Bm(p,a,o);d.push(...h.rawErrors.filter(f=>!u.has(Vm(f))))}if(d.length===0)c.push({depth:m.depth,status:"verified"});else{c.push({depth:m.depth,status:"failed",errors:d.slice(0,ND)});break}}}finally{try{Js("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{CD(a,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:l,dirtyOverlap:s,batches:c}}function LD(e,t){let n=new Set(t.flatMap(i=>i.coversExtensions));return[...new Set(e.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>{let o=i.slice(i.lastIndexOf("."));return!n.has(o)}).sort()}function Vm(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var $m=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function _D(e){let t=[];if(nt(Fe(e,"tsconfig.json"))){let n=Fe(e,"node_modules",".bin","tsc");t.push(nt(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:$m}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:$m})}if(nt(Fe(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>nt(Fe(e,n)))){let n=wD();n&&t.push(n)}for(let n of ED(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:Fe(e,n,"..","target")}});return t}function wD(){return jm("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:jm("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function jm(e){try{return Hm(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function ED(e){let t=[];if(nt(Fe(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n=[];try{n=xD(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||nt(Fe(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function kD(e,t){let n;try{n=Js("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let r=new Set(n.split(`
796
+ `).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>r.has(o)).sort()}function PD(e,t){for(let n of["node_modules"]){let r=Fe(e,n),i=Fe(t,n);if(nt(r)&&!nt(i))try{RD(r,i,"junction")}catch{}}}function FD(e,t){let n=new Map;for(let r of t.entries){let i=n.get(r.file)??[];i.push({start:r.startLine,end:r.endLine}),n.set(r.file,i)}for(let[r,i]of n){let o=Fe(e,r);nt(o)&&ID(o,AD(SD(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function AD(e,t,n={}){let r=e.split(`
797
+ `),i=(n.rust===!0?TD(e):vt(e)).split(`
798
+ `),o=new Set;for(let s of t){let a=MD(r,s.start),c=$D(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
799
+ `)}function TD(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 MD(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var OD=200;function $D(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>OD)break}return n}function Bm(e,t,n){let r=Hm(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(r.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${r.stdout??""}
800
800
  ${r.stderr??""}`.split(`
801
- `).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return r.error&&o.length===0&&o.push(String(r.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(Hm))}}function qe({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,...o}){return{...o,renderShape:"list",handler:Sm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i})}}function Ri({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s,...a}){return{...a,renderShape:"table",handler:xm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function qm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){return{...s,renderShape:"grouped-by-file",handler:Cm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}function Vm({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){return{...s,renderShape:"sectioned-report",handler:Rm({query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function Ii({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){return{...s,budget:s.budget??"semantic",renderShape:"sectioned-report",handler:Im(s.id,{query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}var OD=X("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:He(t,0)||void 0,minLoc:S(n,"minLoc",1),includeTests:j(n,"includeTests"),skipBarrels:j(n,"skipBarrels"),includeMembers:j(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=Je(e,i),s=o.symbols.filter(f=>f.kind==="dead-code"),a=o.symbols.filter(f=>f.kind!=="dead-code"),c=!j(n,"onlyInternal"),l=!j(n,"onlyDead"),u=c?s:[],m=l?a:[];if(u.length===0&&m.length===0){_.empty("No matching dead-code symbols found.");return}let d=u.reduce((f,y)=>f+y.loc,0),p=m.reduce((f,y)=>f+y.loc,0);u.length>0&&Wm(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
802
- Safe to delete.`,d),m.length>0&&(u.length>0&&console.log(""),Wm(m,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
801
+ `).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return r.error&&o.length===0&&o.push(String(r.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(Vm))}}function Ve({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,...o}){return{...o,renderShape:"list",handler:Sm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i})}}function Ri({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s,...a}){return{...a,renderShape:"table",handler:xm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function Wm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){return{...s,renderShape:"grouped-by-file",handler:Cm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}function Um({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){return{...s,renderShape:"sectioned-report",handler:Rm({query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function Ii({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){return{...s,budget:s.budget??"semantic",renderShape:"sectioned-report",handler:Im(s.id,{query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}var jD=X("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:qe(t,0)||void 0,minLoc:S(n,"minLoc",1),includeTests:j(n,"includeTests"),skipBarrels:j(n,"skipBarrels"),includeMembers:j(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=ze(e,i),s=o.symbols.filter(f=>f.kind==="dead-code"),a=o.symbols.filter(f=>f.kind!=="dead-code"),c=!j(n,"onlyInternal"),l=!j(n,"onlyDead"),u=c?s:[],m=l?a:[];if(u.length===0&&m.length===0){_.empty("No matching dead-code symbols found.");return}let d=u.reduce((f,y)=>f+y.loc,0),p=m.reduce((f,y)=>f+y.loc,0);u.length>0&&Gm(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
802
+ Safe to delete.`,d),m.length>0&&(u.length>0&&console.log(""),Gm(m,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
803
803
  single-use helper, an abstraction-in-progress, or a callback registered
804
804
  through a framework path that static analysis cannot trace (signal
805
805
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
806
806
  review case by case.`,p));let h=[];c&&h.push(`${u.length} dead code (${d} LOC)`),l&&h.push(`${m.length} file-internal (${p} LOC)`),console.log(`
807
- \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+m.length} symbols \u2014 ${h.join(" + ")}`)});function Wm(e,t,n,r){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${r} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let i=new Map;for(let a of e){let c=i.get(a.relativePath)??[];c.push(a),i.set(a.relativePath,c)}let o=[...i.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(` ${ue(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var $D=Ze("unused-imports",{query:({db:e,args:t,budget:n})=>xo(e,M(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
808
- ${e.length} unused import(s)`)}),jD=Ci("isolated",{query:({db:e,opts:t,budget:n})=>kt(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ue(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
809
- ${e.length} isolated symbol(s)`)}),BD=X("extract-candidates",({db:e,opts:t,budget:n})=>{let r=Pt(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",10),minCallees:S(t,"minCallees",6),limit:S(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return _.empty("No extraction candidates found.");or("extraction candidates");for(let i of r){console.log(`
807
+ \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+m.length} symbols \u2014 ${h.join(" + ")}`)});function Gm(e,t,n,r){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${r} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let i=new Map;for(let a of e){let c=i.get(a.relativePath)??[];c.push(a),i.set(a.relativePath,c)}let o=[...i.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(` ${ue(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var BD=et("unused-imports",{query:({db:e,args:t,budget:n})=>xo(e,M(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
808
+ ${e.length} unused import(s)`)}),HD=Ci("isolated",{query:({db:e,opts:t,budget:n})=>Pt(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ue(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
809
+ ${e.length} isolated symbol(s)`)}),qD=X("extract-candidates",({db:e,opts:t,budget:n})=>{let r=Ft(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",10),minCallees:S(t,"minCallees",6),limit:S(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return _.empty("No extraction candidates found.");or("extraction candidates");for(let i of r){console.log(`
810
810
  ${se(i.relativePath,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC, ${i.totalCallees} callees)`);for(let o=0;o<i.clusters.length;o++){let s=i.clusters[o];console.log(` Cluster ${o+1} (${Math.round(s.isolation*100)}% isolated, ${s.callees.length} callees):`);for(let a of s.callees)console.log(` ${a}`)}}console.log(`
811
- ${r.length} extraction candidate(s) found.`)}),HD=Ze("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>jt(e,{scope:k(t,"scope"),maxLoc:S(t,"maxLoc",15),limit:S(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
811
+ ${r.length} extraction candidate(s) found.`)}),VD=et("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Bt(e,{scope:k(t,"scope"),maxLoc:S(t,"maxLoc",15),limit:S(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
812
812
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn})`,emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
813
- ${e.length} wrapper candidate(s).`)}),qD=Ze("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Ot(e,{scope:k(t,"scope"),maxLoc:S(t,"maxLoc",15),limit:S(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
813
+ ${e.length} wrapper candidate(s).`)}),WD=et("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>$t(e,{scope:k(t,"scope"),maxLoc:S(t,"maxLoc",15),limit:S(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
814
814
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile})`,emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
815
- ${e.length} passthrough candidate(s).`)}),VD=Ze("stale-abstractions",{query:({db:e,opts:t,budget:n})=>$t(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",3),limit:S(t,"limit",30),includeLowConfidence:j(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}] ${se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
815
+ ${e.length} passthrough candidate(s).`)}),UD=et("stale-abstractions",{query:({db:e,opts:t,budget:n})=>jt(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",3),limit:S(t,"limit",30),includeLowConfidence:j(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}] ${se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
816
816
  ${e.reason}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
817
- ${e.length} stale abstraction(s).`)}),WD=xi("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>rr(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",10),limit:S(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]}),UD=cr("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=He(t,0);return i?{mode:"target",rows:Gn(e,i,{minSimilarity:S(n,"minSimilarity",.4),limit:S(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:ze(e,{minSimilarity:S(n,"minSimilarity",.4),limit:S(n,"limit",20),scope:k(n,"scope"),minCallees:S(n,"minCallees",4),crossFileOnly:j(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.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"){_.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
817
+ ${e.length} stale abstraction(s).`)}),GD=xi("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>rr(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",10),limit:S(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]}),JD=cr("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=qe(t,0);return i?{mode:"target",rows:Gn(e,i,{minSimilarity:S(n,"minSimilarity",.4),limit:S(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Qe(e,{minSimilarity:S(n,"minSimilarity",.4),limit:S(n,"limit",20),scope:k(n,"scope"),minCallees:S(n,"minCallees",4),crossFileOnly:j(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.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"){_.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
818
818
  ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
819
819
  `)});return}_.list(e.rows,t=>`
820
820
  ${Math.round(t.similarity*100)}% similar:
821
821
  A: ${t.shortNameA} (${t.fileA})
822
822
  B: ${t.shortNameB} (${t.fileB})
823
823
  Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
824
- ${e.rows.length} similar pair(s) found.`)}}),GD=Wt({query:({db:e,args:t,opts:n})=>Oo(e,{minSimilarity:S(n,"minSimilarity",.5),limit:S(n,"limit",20),scope:k(n,"scope"),minDeps:ft(n,"minDeps"),filePattern:He(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{_.list(e,t=>{let n=[`
824
+ ${e.rows.length} similar pair(s) found.`)}}),zD=Ut({query:({db:e,args:t,opts:n})=>Oo(e,{minSimilarity:S(n,"minSimilarity",.5),limit:S(n,"limit",20),scope:k(n,"scope"),minDeps:gt(n,"minDeps"),filePattern:qe(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{_.list(e,t=>{let n=[`
825
825
  ${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(`
826
826
  `)}),console.log(`
827
- ${e.length} similar pair(s) found.`)}}),JD=Wt({query:({db:e,opts:t})=>$o(e,{minSimilarity:S(t,"minSimilarity",.5),limit:S(t,"limit",15),scope:k(t,"scope"),minChainLength:S(t,"minLength",3),maxChainLength:S(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(`
827
+ ${e.length} similar pair(s) found.`)}}),QD=Ut({query:({db:e,opts:t})=>$o(e,{minSimilarity:S(t,"minSimilarity",.5),limit:S(t,"limit",15),scope:k(t,"scope"),minChainLength:S(t,"minLength",3),maxChainLength:S(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(`
828
828
  \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 r of n.divergencePoints)console.log(` [${r.index}] ${r.nodeA} \u2194 ${r.nodeB}`)}console.log(`
829
- ${e.length} similar chain pair(s) found.`)}}),zD=cr("drift",{query:({db:e,args:t,opts:n,budget:r})=>Mt(e,{scope:He(t,0),minDeviation:S(n,"minDeviation",5),semantic:r.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),_.groupedByFile(e.results,t=>{let r=` [${t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${t.description}`;return t.detail?`${r}
829
+ ${e.length} similar chain pair(s) found.`)}}),KD=cr("drift",{query:({db:e,args:t,opts:n,budget:r})=>Ot(e,{scope:qe(t,0),minDeviation:S(n,"minDeviation",5),semantic:r.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),_.groupedByFile(e.results,t=>{let r=` [${t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${t.description}`;return t.detail?`${r}
830
830
  ${t.detail}`:r},t=>t.file),console.log(`
831
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),QD=cr("convergence",{query:({db:e,args:t,budget:n})=>os(e,M(t,0),M(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
831
+ ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),YD=cr("convergence",{query:({db:e,args:t,budget:n})=>os(e,M(t,0),M(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
832
832
  ${Math.round(e.similarity*100)}% callee overlap
833
833
  `),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)
834
834
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
835
835
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
836
836
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
837
- Strategy: ${e.consolidationStrategy}`)}}}),KD=Ze("similar-signatures",{query:({db:e,opts:t,budget:n})=>us(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",3),limit:S(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
837
+ Strategy: ${e.consolidationStrategy}`)}}}),XD=et("similar-signatures",{query:({db:e,opts:t,budget:n})=>us(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",3),limit:S(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
838
838
  Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(r=>` ${se(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
839
839
  `);return`${t}
840
840
  ${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
841
- ${e.length} group(s) found.`)});function Ve(e){return{docs:x("Cleanup"),...e}}function nt({heuristicLabel:e,...t}){return Ve({...t,heuristic:{label:e}})}var YD=X("cleanup-plan",({db:e,opts:t,budget:n})=>{let r=Bo(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",1),maxDepth:S(t,"maxDepth",5),scanLimit:n.scanLimit});if(r.batches.length===0)return _.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");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.
841
+ ${e.length} group(s) found.`)});function We(e){return{docs:x("Cleanup"),...e}}function rt({heuristicLabel:e,...t}){return We({...t,heuristic:{label:e}})}var ZD=X("cleanup-plan",({db:e,opts:t,budget:n})=>{let r=Bo(e,{scope:k(t,"scope"),minLoc:S(t,"minLoc",1),maxDepth:S(t,"maxDepth",5),scanLimit:n.scanLimit});if(r.batches.length===0)return _.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");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.
842
842
  `);for(let i of r.batches){let o=i.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${i.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${i.depth}: dead once batch ${i.depth-1} lands (cascade, ${i.loc} LOC) \u2500\u2500`;console.log(o);for(let s of i.entries)console.log(` ${s.file}:${s.startLine+1}-${s.endLine+1} ${s.shortName} (${s.loc} LOC)`);i.filesEmptied.length>0&&console.log(` -> empties: ${i.filesEmptied.join(", ")}`),console.log("")}if(r.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let i of r.blocked)console.log(` ${i.shortName} (${i.file}) blocked by ${i.blockingFiles.join(", ")}`)}if(j(t,"verify")){console.log(`
843
- Verifying batches against the project checker (throwaway worktree at HEAD)...`);let i=Bm(Be(),r);if(i.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let o of i.checkers)console.log(` Checker: ${o}`);i.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${i.uncoveredFiles.join(", ")}`),i.baselineErrors>0&&console.log(` Baseline has ${i.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),i.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${i.dirtyOverlap.join(", ")}`);for(let o of i.batches)if(o.status==="verified")console.log(` Batch ${o.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${o.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let s of o.errors??[])console.log(` ${s}`)}}}),XD=X("recent-duplicates",({db:e,opts:t,budget:n})=>{let r=Zo(e,{windowCommits:S(t,"window",100),minSimilarity:ft(t,"minSimilarity")??.7,limit:S(t,"limit",30),scope:k(t,"scope"),scanLimit:n.scanLimit,semantic:n.semantic});if(!r.available)return _.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return _.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
843
+ Verifying batches against the project checker (throwaway worktree at HEAD)...`);let i=qm(He(),r);if(i.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let o of i.checkers)console.log(` Checker: ${o}`);i.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${i.uncoveredFiles.join(", ")}`),i.baselineErrors>0&&console.log(` Baseline has ${i.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),i.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${i.dirtyOverlap.join(", ")}`);for(let o of i.batches)if(o.status==="verified")console.log(` Batch ${o.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${o.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let s of o.errors??[])console.log(` ${s}`)}}}),eN=X("recent-duplicates",({db:e,opts:t,budget:n})=>{let r=Zo(e,{windowCommits:S(t,"window",100),minSimilarity:gt(t,"minSimilarity")??.7,limit:S(t,"limit",30),scope:k(t,"scope"),scanLimit:n.scanLimit,semantic:n.semantic});if(!r.available)return _.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return _.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
844
844
  `);for(let i of r.findings)i.kind==="echo"?(console.log(` ${Math.round(i.similarity*100)}% ECHO ${i.echoFile} ${i.echoSymbol} (added ${i.echoAgeCommits} commits ago)`),console.log(` duplicates established ${i.establishedFile} ${i.establishedSymbol}`)):(console.log(` ${Math.round(i.similarity*100)}% TWIN ${i.echoFile} ${i.echoSymbol}`),console.log(` and ${i.establishedFile} ${i.establishedSymbol} (both new \u2014 consolidate before they diverge)`));console.log(`
845
- ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),ZD=q(({db:e,args:t,opts:n})=>{let r=Jo(e,{doc:t[0]===void 0?void 0:M(t,0),limit:S(n,"limit",20),minCoupling:S(n,"minCoupling",3)});if(!r.available)return _.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return _.empty(`No drifting docs found across ${r.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 (${r.docsScanned} docs scanned, ${r.commitsAnalyzed} commits analyzed):
845
+ ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),tN=q(({db:e,args:t,opts:n})=>{let r=Jo(e,{doc:t[0]===void 0?void 0:M(t,0),limit:S(n,"limit",20),minCoupling:S(n,"minCoupling",3)});if(!r.available)return _.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return _.empty(`No drifting docs found across ${r.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 (${r.docsScanned} docs scanned, ${r.commitsAnalyzed} commits analyzed):
846
846
  `);for(let i of r.findings){console.log(` staleness ${i.staleness} ${i.doc}`);for(let o of i.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${o} \u2014 that file no longer exists`);for(let o of i.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})`)}}console.log(`
847
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),eN=Ze("unused-params",{query:({db:e,opts:t,budget:n})=>er(e,{scope:k(t,"scope"),limit:S(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${se(e.file,e.startLine,e.endLine)} ${e.shortName}
847
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),nN=et("unused-params",{query:({db:e,opts:t,budget:n})=>er(e,{scope:k(t,"scope"),limit:S(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${se(e.file,e.startLine,e.endLine)} ${e.shortName}
848
848
  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(`
849
- ${e.length} function(s) with trailing unused parameters.`)}),Um=[Ve({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Maximum findings",R,30),g("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:x("Cleanup",["scip-query unused-params -s src/services"]),handler:eN}),Ve({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Only include symbols >= N lines",R,1),g("--max-depth <n>","Maximum cascade depth",R,5),g("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),g("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:x("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:YD}),Ve({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established code",options:[g("--window <n>",'How many commits back counts as "recent"',R,100),g("--min-similarity <n>","Minimum similarity (0-1)",sr,.7),g("-n, --limit <n>","Maximum findings",R,30),g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:x("Cleanup",["scip-query recent-duplicates --window 50"]),handler:XD}),Ve({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:[g("-n, --limit <n>","Maximum docs to report",R,20),g("--min-coupling <n>","Minimum historical co-changes to track a subject",R,3)],heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:x("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:ZD}),Ve({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:[g("--min-loc <n>","Only show symbols >= N lines",R,1),g("--include-tests","Include test files"),g("--skip-barrels","Ignore refs from barrel re-export files"),g("--include-members","Include class members"),g("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),g("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:x("Cleanup",["scip-query dead --min-loc 10"]),handler:OD}),Ve({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",handler:$D}),Ve({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum lines of code",R,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"grouped-by-file",handler:jD}),nt({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",sr,.4),g("-n, --limit <n>","Number of results",R,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-callees <n>","Minimum callees to consider",R,4),g("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:UD}),nt({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",sr,.5),g("-n, --limit <n>","Number of results",R,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-deps <n>","Minimum dependencies to consider",R)],heuristicLabel:"similar file candidates",renderShape:"custom",handler:GD}),nt({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:[g("--min-similarity <n>","Minimum chain similarity (0-1)",sr,.5),g("-n, --limit <n>","Number of results",R,15),g("-s, --scope <path>","Limit to files matching path"),g("--min-length <n>","Minimum chain length",R,3),g("--max-length <n>","Maximum chain length",R,8)],heuristicLabel:"similar chain candidates",renderShape:"custom",handler:JD}),nt({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum function LOC",R,10),g("--min-callees <n>","Minimum callees to analyze",R,6),g("-n, --limit <n>","Number of results",R,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:BD}),nt({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:[g("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",ui,5),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:zD}),nt({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",R,15),g("-n, --limit <n>","Number of results",R,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:HD}),nt({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",R,15),g("-n, --limit <n>","Number of results",R,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:qD}),nt({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",R,3),g("-n, --limit <n>","Number of results",R,30),g("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:VD}),nt({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",R,10),g("-n, --limit <n>","Number of results",R,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:WD}),Ve({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",handler:QD}),qm({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",R,30)],docs:x("Cleanup"),query:({db:e,opts:t})=>as(e,{scope:k(t,"scope"),limit:S(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
849
+ ${e.length} function(s) with trailing unused parameters.`)}),Jm=[We({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Maximum findings",R,30),g("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:x("Cleanup",["scip-query unused-params -s src/services"]),handler:nN}),We({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Only include symbols >= N lines",R,1),g("--max-depth <n>","Maximum cascade depth",R,5),g("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),g("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:x("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:ZD}),We({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established code",options:[g("--window <n>",'How many commits back counts as "recent"',R,100),g("--min-similarity <n>","Minimum similarity (0-1)",sr,.7),g("-n, --limit <n>","Maximum findings",R,30),g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:x("Cleanup",["scip-query recent-duplicates --window 50"]),handler:eN}),We({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:[g("-n, --limit <n>","Maximum docs to report",R,20),g("--min-coupling <n>","Minimum historical co-changes to track a subject",R,3)],heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:x("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:tN}),We({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:[g("--min-loc <n>","Only show symbols >= N lines",R,1),g("--include-tests","Include test files"),g("--skip-barrels","Ignore refs from barrel re-export files"),g("--include-members","Include class members"),g("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),g("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:x("Cleanup",["scip-query dead --min-loc 10"]),handler:jD}),We({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",handler:BD}),We({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum lines of code",R,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"grouped-by-file",handler:HD}),rt({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",sr,.4),g("-n, --limit <n>","Number of results",R,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-callees <n>","Minimum callees to consider",R,4),g("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:JD}),rt({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",sr,.5),g("-n, --limit <n>","Number of results",R,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-deps <n>","Minimum dependencies to consider",R)],heuristicLabel:"similar file candidates",renderShape:"custom",handler:zD}),rt({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:[g("--min-similarity <n>","Minimum chain similarity (0-1)",sr,.5),g("-n, --limit <n>","Number of results",R,15),g("-s, --scope <path>","Limit to files matching path"),g("--min-length <n>","Minimum chain length",R,3),g("--max-length <n>","Maximum chain length",R,8)],heuristicLabel:"similar chain candidates",renderShape:"custom",handler:QD}),rt({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum function LOC",R,10),g("--min-callees <n>","Minimum callees to analyze",R,6),g("-n, --limit <n>","Number of results",R,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:qD}),rt({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:[g("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",ui,5),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:KD}),rt({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",R,15),g("-n, --limit <n>","Number of results",R,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:VD}),rt({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",R,15),g("-n, --limit <n>","Number of results",R,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:WD}),rt({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",R,3),g("-n, --limit <n>","Number of results",R,30),g("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:UD}),rt({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",R,10),g("-n, --limit <n>","Number of results",R,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:GD}),We({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",handler:YD}),Wm({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",R,30)],docs:x("Cleanup"),query:({db:e,opts:t})=>as(e,{scope:k(t,"scope"),limit:S(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
850
850
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s)`,key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
851
- ${e.length} redundant re-export(s).`)}),Ve({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC per function",R,3),g("-n, --limit <n>","Number of groups",R,20),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"list",handler:KD})];var tN=q(({db:e})=>{let t=Ne(e);console.log(`Documents: ${t.documents}`),console.log(`Symbols: ${t.symbols}`),console.log(`Definitions: ${t.definitions}`),console.log(`References: ${t.references}`),console.log(`Index size: ${xn(t.indexSizeBytes)}`),t.lastBuilt&&console.log(`Last built: ${t.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Gm=[{id:"stats",command:"stats",description:"Show index statistics",renderShape:"custom",docs:x("Core"),handler:tN}];var nN=xi("bottlenecks",{headers:["score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>wo(e,{limit:S(t,"limit",20),scope:k(t,"scope"),minFanIn:S(t,"minFanIn",2),minFanOut:S(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),rN=q(({db:e,args:t,opts:n})=>{let r=He(t,0);if(r){let i=Io(e,r);if(i.length===0)return _.empty(`No fan-in for ${r}.`);_.list(i,o=>` ${String(o.count).padStart(4)} files ${o.name}`);return}_.table(["files","symbol"],Do(e,{limit:S(n,"limit",30),scope:k(n,"scope")}).map(i=>` ${String(i.count).padStart(5)} ${i.name}`))}),iN=q(({db:e,args:t,opts:n})=>{let r=He(t,0);if(r){let i=vo(e,r);if(i.length===0)return _.empty(`No fan-out for ${r}.`);_.list(i,o=>` ${String(o.count).padStart(4)} symbols ${o.name}`);return}_.table(["symbols","file"],No(e,{limit:S(n,"limit",30),scope:k(n,"scope")}).map(i=>` ${String(i.count).padStart(7)} ${i.name}`))}),oN=q(({db:e,args:t,opts:n})=>{let r=He(t,0),i=He(t,1);if(r&&i){let o=Lo(e,r,i);console.log(`${o.file1} \u2194 ${o.file2}: ${o.sharedSymbols} shared symbols`);return}_.table(["shared","file1 \u2192 file2"],_o(e,{limit:S(n,"limit",20),scope:k(n,"scope")}).map(o=>` ${String(o.sharedSymbols).padStart(6)} ${o.file1} \u2192 ${o.file2}`))}),sN=Wt({query:({db:e,opts:t})=>Et(e,{scope:k(t,"scope"),maxDepth:S(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(r=>r.kind==="real"),n=e.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
851
+ ${e.length} redundant re-export(s).`)}),We({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC per function",R,3),g("-n, --limit <n>","Number of groups",R,20),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"list",handler:XD})];var rN=q(({db:e})=>{let t=Ne(e);console.log(`Documents: ${t.documents}`),console.log(`Symbols: ${t.symbols}`),console.log(`Definitions: ${t.definitions}`),console.log(`References: ${t.references}`),console.log(`Index size: ${xn(t.indexSizeBytes)}`),t.lastBuilt&&console.log(`Last built: ${t.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),zm=[{id:"stats",command:"stats",description:"Show index statistics",renderShape:"custom",docs:x("Core"),handler:rN}];var iN=xi("bottlenecks",{headers:["score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>wo(e,{limit:S(t,"limit",20),scope:k(t,"scope"),minFanIn:S(t,"minFanIn",2),minFanOut:S(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),oN=q(({db:e,args:t,opts:n})=>{let r=qe(t,0);if(r){let i=Io(e,r);if(i.length===0)return _.empty(`No fan-in for ${r}.`);_.list(i,o=>` ${String(o.count).padStart(4)} files ${o.name}`);return}_.table(["files","symbol"],Do(e,{limit:S(n,"limit",30),scope:k(n,"scope")}).map(i=>` ${String(i.count).padStart(5)} ${i.name}`))}),sN=q(({db:e,args:t,opts:n})=>{let r=qe(t,0);if(r){let i=vo(e,r);if(i.length===0)return _.empty(`No fan-out for ${r}.`);_.list(i,o=>` ${String(o.count).padStart(4)} symbols ${o.name}`);return}_.table(["symbols","file"],No(e,{limit:S(n,"limit",30),scope:k(n,"scope")}).map(i=>` ${String(i.count).padStart(7)} ${i.name}`))}),aN=q(({db:e,args:t,opts:n})=>{let r=qe(t,0),i=qe(t,1);if(r&&i){let o=Lo(e,r,i);console.log(`${o.file1} \u2194 ${o.file2}: ${o.sharedSymbols} shared symbols`);return}_.table(["shared","file1 \u2192 file2"],_o(e,{limit:S(n,"limit",20),scope:k(n,"scope")}).map(o=>` ${String(o.sharedSymbols).padStart(6)} ${o.file1} \u2192 ${o.file2}`))}),cN=Ut({query:({db:e,opts:t})=>kt(e,{scope:k(t,"scope"),maxDepth:S(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(r=>r.kind==="real"),n=e.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
852
852
  Cycle ${r+1} (${t[r].path.length-1} files):`);for(let i=0;i<t[r].path.length;i++){let o=i<t[r].path.length-1?" \u2192":" (cycle)";console.log(` ${t[r].path[i]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
853
- ${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.)`)}}),aN=Wt({query:({db:e,opts:t})=>To(e,{limit:S(t,"limit",10),scope:k(t,"scope"),minDepth:S(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(`
854
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`)}}}),Jm=[Ri({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[g("-n, --limit <n>","Number of results",R,30),g("-s, --scope <path>","Limit to files matching path")],docs:x("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>yo(e,{limit:S(t,"limit",30),scope:k(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:[g("-n, --limit <n>","Number of results for top mode",R,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Graph"),handler:rN},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:[g("-n, --limit <n>","Number of results for top mode",R,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Graph"),handler:iN},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:[g("-n, --limit <n>","Number of results for top mode",R,20),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Graph"),handler:oN},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-depth <n>","Maximum cycle depth",R,10)],renderShape:"custom",docs:x("Graph"),handler:sN},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:[g("-n, --limit <n>","Number of results",R,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-fan-in <n>","Minimum fan-in",R,2),g("--min-fan-out <n>","Minimum fan-out",R,2),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"table",docs:x("Graph"),handler:nN},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:[g("-n, --limit <n>","Number of chains to show",R,10),g("-s, --scope <path>","Limit to files matching path"),g("--min-depth <n>","Minimum chain depth",R,3)],renderShape:"custom",docs:x("Graph"),handler:aN},Ii({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:x("Graph"),query:({db:e,args:t,budget:n})=>qn(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
855
- `)},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 cN=X("complexity",({db:e,args:t,budget:n})=>{let r=tr(e,M(t,0),{semantic:n.semantic});if(!r)return _.empty("Symbol not found.");console.log(`${se(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
856
- `),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}`)}),lN=q(({db:e,opts:t})=>{let n=ls(e,{samples:S(t,"samples",50),scope:k(t,"scope")});if(!n.available)return _.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${n.sampleSize} symbols; oracle answered ${Math.round(n.oracleCoverage*100)}%.
853
+ ${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.)`)}}),lN=Ut({query:({db:e,opts:t})=>Ao(e,{limit:S(t,"limit",10),scope:k(t,"scope"),minDepth:S(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(`
854
+ Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`)}}}),Qm=[Ri({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[g("-n, --limit <n>","Number of results",R,30),g("-s, --scope <path>","Limit to files matching path")],docs:x("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>yo(e,{limit:S(t,"limit",30),scope:k(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:[g("-n, --limit <n>","Number of results for top mode",R,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Graph"),handler:oN},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:[g("-n, --limit <n>","Number of results for top mode",R,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Graph"),handler:sN},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:[g("-n, --limit <n>","Number of results for top mode",R,20),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Graph"),handler:aN},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-depth <n>","Maximum cycle depth",R,10)],renderShape:"custom",docs:x("Graph"),handler:cN},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:[g("-n, --limit <n>","Number of results",R,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-fan-in <n>","Minimum fan-in",R,2),g("--min-fan-out <n>","Minimum fan-out",R,2),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"table",docs:x("Graph"),handler:iN},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:[g("-n, --limit <n>","Number of chains to show",R,10),g("-s, --scope <path>","Limit to files matching path"),g("--min-depth <n>","Minimum chain depth",R,3)],renderShape:"custom",docs:x("Graph"),handler:lN},Ii({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:x("Graph"),query:({db:e,args:t,budget:n})=>qn(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
855
+ `)},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 uN=X("complexity",({db:e,args:t,budget:n})=>{let r=tr(e,M(t,0),{semantic:n.semantic});if(!r)return _.empty("Symbol not found.");console.log(`${se(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
856
+ `),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}`)}),mN=q(({db:e,opts:t})=>{let n=ls(e,{samples:S(t,"samples",50),scope:k(t,"scope")});if(!n.available)return _.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${n.sampleSize} symbols; oracle answered ${Math.round(n.oracleCoverage*100)}%.
857
857
  `),console.log("Agreement with compiler semantics (file-level):");for(let r of n.scores){let i=r.precision===null?`unverified ${r.unverified} (oracle partial \u2014 no precision claim)`:`precision ${r.precision}`;console.log(` ${r.question.padEnd(11)} ${i} recall ${r.recall} (${r.comparedSymbols} symbols)`)}if(n.topDisagreements.length>0){console.log(`
858
- Top disagreements (debugging targets):`);for(let r of n.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(", ")}`)}}),zm=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:[g("--samples <n>","Number of symbols to sample",R,50),g("-s, --scope <path>","Limit sampling to files matching path")],renderShape:"custom",docs:x("Health",["scip-query self-audit --samples 100"]),handler:lN},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Health"),handler:cN}];var uN=q(({db:e,args:t,opts:n})=>{let r=Jn(e,M(t,0),{maxDepth:S(n,"maxDepth",5),scope:k(n,"scope")});if(r.length===0)return _.empty("No affected symbols found.");let i=-1;for(let o of r)o.depth!==i&&(console.log(`
858
+ Top disagreements (debugging targets):`);for(let r of n.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(", ")}`)}}),Km=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:[g("--samples <n>","Number of symbols to sample",R,50),g("-s, --scope <path>","Limit sampling to files matching path")],renderShape:"custom",docs:x("Health",["scip-query self-audit --samples 100"]),handler:mN},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Health"),handler:uN}];var dN=q(({db:e,args:t,opts:n})=>{let r=Jn(e,M(t,0),{maxDepth:S(n,"maxDepth",5),scope:k(n,"scope")});if(r.length===0)return _.empty("No affected symbols found.");let i=-1;for(let o of r)o.depth!==i&&(console.log(`
859
859
  \u2500\u2500 Depth ${o.depth} \u2500\u2500`),i=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
860
- ${r.length} affected symbol(s) across ${new Set(r.map(o=>o.file)).size} files.`)}),mN=q(({db:e,args:t,opts:n})=>{let r=t[0]===void 0?void 0:M(t,0),i=Tt(e,r,{minTogether:S(n,"minTogether",4),limit:S(n,"limit",30),includeLinked:n.all===!0});if(!i.available)return _.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return _.empty(r?`No co-change partners found for ${r} in ${i.commitsAnalyzed} commits.`:`No hidden coupling found in ${i.commitsAnalyzed} commits.`);console.log(r?`Co-change partners (${i.commitsAnalyzed} commits analyzed):
860
+ ${r.length} affected symbol(s) across ${new Set(r.map(o=>o.file)).size} files.`)}),pN=q(({db:e,args:t,opts:n})=>{let r=t[0]===void 0?void 0:M(t,0),i=Tt(e,r,{minTogether:S(n,"minTogether",4),limit:S(n,"limit",30),includeLinked:n.all===!0});if(!i.available)return _.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return _.empty(r?`No co-change partners found for ${r} in ${i.commitsAnalyzed} commits.`:`No hidden coupling found in ${i.commitsAnalyzed} commits.`);console.log(r?`Co-change partners (${i.commitsAnalyzed} commits analyzed):
861
861
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${i.commitsAnalyzed} commits analyzed):
862
862
  `);for(let o of i.findings){let s=o.structurallyLinked?" [dep edge]":"";console.log(` ${o.together}x (${Math.round(o.confidence*100)}%) ${o.fileA} <-> ${o.fileB}${s}`)}console.log(`
863
- ${i.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)}),dN=X("change-surface",({db:e,args:t,budget:n})=>{let r=zn(e,M(t,0),{semantic:n.semantic});if(!r)return _.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
864
- `),_.list(r.symbols,i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${ue(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}`})}),pN=q(({db:e,opts:t})=>{let n=Xo(e,{base:k(t,"base"),minTogether:S(t,"minTogether",6),maxEchoChecks:S(t,"maxEchoChecks",10)});if(n.changedFiles.length===0)return _.empty(n.note??`No changes vs ${n.base}.`);console.log(`Diff gate vs ${n.base}: ${n.changedFiles.length} file(s), ${n.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${n.checksRun.join(", ")}
863
+ ${i.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)}),fN=X("change-surface",({db:e,args:t,budget:n})=>{let r=zn(e,M(t,0),{semantic:n.semantic});if(!r)return _.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
864
+ `),_.list(r.symbols,i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${ue(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}`})}),gN=q(({db:e,opts:t})=>{let n=Xo(e,{base:k(t,"base"),minTogether:S(t,"minTogether",6),maxEchoChecks:S(t,"maxEchoChecks",10)});if(n.changedFiles.length===0)return _.empty(n.note??`No changes vs ${n.base}.`);console.log(`Diff gate vs ${n.base}: ${n.changedFiles.length} file(s), ${n.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${n.checksRun.join(", ")}
865
865
  `);for(let r of n.skipped)console.log(` skipped ${r.check}: ${r.reason}`);if(n.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}for(let r of n.findings)console.log(` [${r.check}] ${r.message}`),console.log(` -> ${r.remediation}`);console.log(`
866
- FAIL: ${n.findings.length} finding(s). Fix or knowingly accept before merging.`),process.exitCode=1}),Qm=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:[g("--max-depth <n>","Maximum traversal depth",R,5),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Impact"),handler:uN},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:x("Impact"),handler:dN},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[g("--base <ref>","Git ref to diff against (default: HEAD)"),g("--min-together <n>","Minimum historical co-changes for the partner check",R,6),g("--max-echo-checks <n>","Maximum changed symbols to test for echoes",R,10)],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:x("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:pN},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:[g("--min-together <n>","Minimum commits where both files changed",R,4),g("-n, --limit <n>","Maximum pairs to report",R,30),g("--all","Include pairs that already have a dependency edge")],heuristic:{label:"co-change candidates"},renderShape:"custom",docs:x("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:mN}];function fN(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${se(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
866
+ FAIL: ${n.findings.length} finding(s). Fix or knowingly accept before merging.`),process.exitCode=1}),Ym=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:[g("--max-depth <n>","Maximum traversal depth",R,5),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:x("Impact"),handler:dN},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:x("Impact"),handler:fN},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[g("--base <ref>","Git ref to diff against (default: HEAD)"),g("--min-together <n>","Minimum historical co-changes for the partner check",R,6),g("--max-echo-checks <n>","Maximum changed symbols to test for echoes",R,10)],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:x("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:gN},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:[g("--min-together <n>","Minimum commits where both files changed",R,4),g("-n, --limit <n>","Maximum pairs to report",R,30),g("--all","Include pairs that already have a dependency edge")],heuristic:{label:"co-change candidates"},renderShape:"custom",docs:x("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:pN}];function hN(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${se(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
867
867
  `).map((s,a)=>` ${ye(i.startLine+a)} ${s}`).join(`
868
- `))}let n=[],r="";for(let i of e.referencedBy)i.relativePath!==r&&(r&&n.push(""),n.push(` ${i.relativePath}`),r=i.relativePath),n.push(` line ${ye(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var gN=q(({db:e,args:t,opts:n})=>{let r=M(t,0),i=j(n,"signatures"),o=Co(e,r);if(o.length===0)return _.empty(`No symbols found for "${r}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),m=i&&l.signature?` - ${hN(l.signature)}`:"";console.log(`${u}${ue(l.startLine,l.endLine)} ${l.shortName}${m}`),s(l.children,c+1)}}s(o,0)});function hN(e){return e.length>120?`${e.slice(0,117)}...`:e}var yN=Ze("imports",{query:({db:e,args:t,budget:n})=>bo(e,M(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)."}),bN=Ci("refs",{query:({db:e,args:t,budget:n})=>uo(e,M(t,0),{semantic:n.semantic}),format:e=>` line ${ye(e.line)}`}),SN=q(({db:e,args:t,opts:n})=>{let r=ss(e,M(t,0),{context:S(n,"context",0)});if(!r)return _.empty("Symbol not found or file unreadable.");console.log(`${se(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
868
+ `))}let n=[],r="";for(let i of e.referencedBy)i.relativePath!==r&&(r&&n.push(""),n.push(` ${i.relativePath}`),r=i.relativePath),n.push(` line ${ye(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var yN=q(({db:e,args:t,opts:n})=>{let r=M(t,0),i=j(n,"signatures"),o=Co(e,r);if(o.length===0)return _.empty(`No symbols found for "${r}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),m=i&&l.signature?` - ${bN(l.signature)}`:"";console.log(`${u}${ue(l.startLine,l.endLine)} ${l.shortName}${m}`),s(l.children,c+1)}}s(o,0)});function bN(e){return e.length>120?`${e.slice(0,117)}...`:e}var SN=et("imports",{query:({db:e,args:t,budget:n})=>bo(e,M(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)."}),xN=Ci("refs",{query:({db:e,args:t,budget:n})=>uo(e,M(t,0),{semantic:n.semantic}),format:e=>` line ${ye(e.line)}`}),CN=q(({db:e,args:t,opts:n})=>{let r=ss(e,M(t,0),{context:S(n,"context",0)});if(!r)return _.empty("Symbol not found or file unreadable.");console.log(`${se(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
869
869
  `);let i=r.source.split(`
870
- `);for(let o=0;o<i.length;o++)console.log(` ${String(ye(r.startLine+o)).padStart(4)} ${i[o]}`)}),xN=X("dataflow",({db:e,args:t,budget:n})=>{let r=nr(e,M(t,0),{semantic:n.semantic});if(!r)return _.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
870
+ `);for(let o=0;o<i.length;o++)console.log(` ${String(ye(r.startLine+o)).padStart(4)} ${i[o]}`)}),RN=X("dataflow",({db:e,args:t,budget:n})=>{let r=nr(e,M(t,0),{semantic:n.semantic});if(!r)return _.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
871
871
  `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let i of r.definitionSites)console.log(` ${i.file}:${ye(i.line)}`)}if(r.usageSites.length>0){console.log(`
872
872
  \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let i of r.usageSites)console.log(` ${i.file}:${ye(i.line)} in ${i.enclosingShort}`)}if(r.producers.length>0){console.log(`
873
873
  \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let i of r.producers)console.log(` ${i.file} ${i.shortName}`)}if(r.consumers.length>0){console.log(`
874
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let i of r.consumers)console.log(` ${i.file} ${i.shortName}`)}}),CN=X("slice",({db:e,args:t,opts:n,budget:r})=>{let i=j(n,"forward")?"forward":"backward",o=gn(e,M(t,0),{direction:i,maxDepth:S(n,"depth",3),semantic:r.semantic});if(!o)return _.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
874
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let i of r.consumers)console.log(` ${i.file} ${i.shortName}`)}}),IN=X("slice",({db:e,args:t,opts:n,budget:r})=>{let i=j(n,"forward")?"forward":"backward",o=gn(e,M(t,0),{direction:i,maxDepth:S(n,"depth",3),semantic:r.semantic});if(!o)return _.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
875
875
  `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}_.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
876
876
  ${s.relationship}`),console.log(`
877
- ${o.connectedSymbols.length} connected symbol(s).`)}),Km=[qe({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:x("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Ni(e,M(t,0)),format:e=>e.relativePath}),qe({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:x("Navigation"),query:({db:e,args:t})=>lo(e,M(t,0)),format:e=>` ${ue(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"grouped-by-file",docs:x("Navigation",["scip-query refs login"]),handler:bN},Ii({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:x("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Mn(e,M(t,0),{semantic:n.semantic}),sections:fN}),qe({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:x("Navigation"),query:({db:e,args:t})=>On(e,M(t,0)),format:e=>e.relativePath}),qe({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:x("Navigation"),query:({db:e,args:t})=>$n(e,M(t,0)),format:e=>e.relativePath}),Vm({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:x("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>jn(e,M(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ue(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}`)}]}),qe({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:x("Navigation"),query:({db:e,args:t})=>Bn(e,M(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:x("Navigation"),handler:yN},qe({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:x("Navigation"),query:({db:e,args:t})=>So(e,M(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:[g("--signatures","Show trimmed symbol signatures")],renderShape:"custom",docs:x("Navigation"),handler:gN},qe({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:x("Navigation"),query:({db:e,args:t})=>Ro(e,M(t,0)),format:e=>` ${ue(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),qe({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",R,100)],docs:x("Navigation"),query:({db:e,args:t,opts:n})=>Po(e,M(t,0),{scope:k(n,"scope"),limit:S(n,"limit",100)}),format:e=>` ${se(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${M(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
878
- ${e.length} symbol(s)`)}),Ri({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[g("-s, --scope <path>","Limit to files matching path")],docs:x("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Fo(e,{scope:k(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),qe({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:x("Navigation"),query:({db:e,args:t})=>Ao(e,M(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:[g("-C, --context <n>","Extra lines of context above/below",R,0)],renderShape:"custom",docs:x("Navigation"),handler:SN},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Navigation"),handler:xN},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:[g("--forward","Forward slice (what does this affect). Default is backward."),g("--depth <n>","Max transitive depth for backward slice",R,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Navigation"),handler:CN}];var RN=X("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=S(n,"limit",20),o=es(e,M(t,0),{semantic:r.semantic,impactDepth:S(n,"impactDepth",3),sliceDepth:S(n,"sliceDepth",3),scope:k(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target.")return _.empty(o.warnings[0]);let s=[{title:"TARGET",rows:IN(o)},{title:"DEFINITIONS",rows:vN(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:DN(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:NN(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:LN(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:_N(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:wN(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:EN(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:kN(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:PN(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:FN(o),skipIfEmpty:!0}];_.sectionedReport(s)}),Ym=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:[g("--impact-depth <n>","Maximum affected traversal depth",R,3),g("--slice-depth <n>","Maximum backward slice depth",R,3),g("-s, --scope <path>","Limit downstream impact to files matching path"),g("-n, --limit <n>","Rows per section",R,20),g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Planning",["scip-query plan-context parseSymbol"]),handler:RN}];function IN(e){return[`Target: ${e.target}`,`Matched: symbol=${zs(e.matched.symbol)} file=${zs(e.matched.file)} module=${zs(e.matched.module)}`]}function vN(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${se(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
879
- `).map((o,s)=>` ${String(ye(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ue(r.startLine,r.endLine)} ${r.shortName}`)),gt(n,t).rows}function DN(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${ye(r.line)} in ${r.enclosingShort}`);return Gt(gt(n,t))}function NN(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(i=>` caller ${i.file} ${i.shortName}`),r=e.callGraph.callees.map(i=>` callee ${i.file} ${i.shortName}`);return Gt(gt([...n,...r],t))}function LN(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),r=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),i=e.dataflow.usageSites.map(o=>` usage ${o.file}:${ye(o.line)} in ${o.enclosingShort}`);return Gt(gt([...n,...r,...i],t))}function _N(e,t){let n=[...e.deps.map(r=>` file depends on ${r.relativePath}`),...e.rdeps.map(r=>` file depended on by ${r.relativePath}`),...e.system.dependsOn.map(r=>` module depends on ${r}`),...e.system.dependedOnBy.map(r=>` module used by ${r}`)];return Gt(gt(n,t))}function wN(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ue(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Gt(gt(n,t))}function EN(e,t){let n=[],r=-1;for(let i of e.affected)i.depth!==r&&(n.push(` -- Depth ${i.depth} --`),r=i.depth),n.push(` ${i.file} ${i.shortName}`);return Gt(gt(n,t))}function kN(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(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${ue(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${se(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}`)),Gt(gt(n,t))}function PN(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let r=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${r}`)}for(let r of t.coChangePartners)n.push(` Usually changes with: ${r.file} (${r.together}x, ${Math.round(r.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function FN(e){let t=e.warnings.map(r=>` ${r}`);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(r=>r.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 gt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Gt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function zs(e){return e?"yes":"no"}var Xm=["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","similar-chains","extract-candidates","affected","change-surface","cleanup-plan","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],TN=[Gm,Km,Jm,Um,Qm,Ym,zm],Zm=TN.flat(),ed=new Map(Zm.map(e=>[e.id,e])),KB=Xm.map(e=>{let t=ed.get(e);if(!t)throw new Error(`Missing query command descriptor: ${e}`);return t});for(let e of Zm)if(!Xm.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function D(e){let t=ed.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var td=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[g("-l, --language <lang>","Index only this language (can be repeated)",yu,[]),g("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),g("--force","Rebuild even if source inputs are unchanged"),g("--allow-partial","Write an incomplete index when one or more detected languages fail"),g("--indexer-concurrency <n>","Number of language indexers to run at once",ui)],renderShape:"custom",docs:x("Indexing",["scip-query reindex"]),handler:Nm},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:x("Indexing"),handler:Lm},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[g("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:x("Indexing"),handler:_m},D("stats"),D("files"),D("methods"),D("refs"),D("trace"),D("deps"),D("rdeps"),D("system"),D("surface"),D("dead"),D("hotspots"),D("imports"),D("imported-by"),D("unused-imports"),D("outline"),D("members"),D("fan-in"),D("fan-out"),D("coupling"),D("cycles"),D("bottlenecks"),D("isolated"),D("by-kind"),D("kind-counts"),D("deep-chains"),D("hierarchy"),D("call-graph"),D("similar"),D("similar-files"),D("similar-chains"),D("extract-candidates"),D("affected"),D("change-surface"),D("cleanup-plan"),D("co-change"),D("recent-duplicates"),D("doc-drift"),D("unused-params"),D("diff-gate"),D("plan-context"),{id:li,command:li,description:"Internal diff-impact batch worker",hidden:!0,options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:wm},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",docs:x("Impact"),handler:Em},D("drift"),D("wrapper-candidates"),D("passthrough-candidates"),D("stale-abstractions"),D("complexity-hotspots"),D("self-audit"),{id:ci,command:ci,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:km},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes"),g("--json","Output as JSON for programmatic consumption"),g("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),g("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:x("Health",["scip-query health --json","scip-query health --baseline"]),handler:Pm},D("convergence"),D("code"),D("complexity"),D("dataflow"),D("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${Ds.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:x("Maintenance"),handler:Fm},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:x("Maintenance"),handler:Tm},D("redundant-reexports"),D("similar-signatures"),{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:x("Maintenance"),handler:Am},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[g("--debounce <ms>","Ms to wait after last change (default: 30000)",bs),g("--cooldown <ms>","Min ms between reindexes (default: 60000)",bs)],renderShape:"custom",docs:x("Maintenance"),handler:Mm},{id:"status",command:"status",description:"Show index status for this project",renderShape:"custom",docs:x("Maintenance"),handler:Om}];function nd(e,t){return t.map(n=>{let r=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);r.description(n.description);for(let i of n.arguments??[])r.argument(i.name);for(let i of n.options??[])i.parser&&Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.parser,i.defaultValue):i.parser?r.option(i.flags,i.description,i.parser):Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.defaultValue):r.option(i.flags,i.description);return r.action((...i)=>n.handler(...i)),{descriptor:n,command:r}})}import{existsSync as AN,mkdirSync as MN,readFileSync as ON,writeFileSync as $N}from"fs";import{homedir as jN}from"os";import{join as vi}from"path";var BN=1440*60*1e3,id="update-check.json",HN="https://registry.npmjs.org/scip-query/latest";async function od(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??WN(t),r=e.now??Date.now(),i=e.currentVersion??ai,o=UN(n),s=o&&r-o.checkedAt<BN?o.latestVersion:await GN(n,e.fetchLatestVersion??zN,r);if(!s||!VN(s,i))return;(e.writeNotice??(c=>console.error(c)))(qN(i,s))}function qN(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
880
- `)}function VN(e,t){let n=rd(e),r=rd(t);if(!n||!r)return e!==t;for(let i=0;i<n.length;i++){let o=n[i]-r[i];if(o>0)return!0;if(o<0)return!1}return!1}function WN(e){let t=e.XDG_CACHE_HOME||vi(jN(),".cache");return vi(t,"scip-query")}function UN(e){let t=vi(e,id);if(!AN(t))return null;try{let n=JSON.parse(ON(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 GN(e,t,n){let r;try{r=await t()}catch{r=null}return JN(e,{checkedAt:n,latestVersion:r}),r}function JN(e,t){try{MN(e,{recursive:!0}),$N(vi(e,id),`${JSON.stringify(t,null,2)}
881
- `)}catch{}}async function zN(){let e=await fetch(HN,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function rd(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}Di.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(ai);nd(Di,td);Di.hook("preAction",async()=>{await od()});KN()&&await Di.parseAsync();function KN(){if(!process.argv[1])return!1;let e=QN(import.meta.url);try{return sd(e)===sd(process.argv[1])}catch{return e===process.argv[1]}}export{Di as program,or as renderHeuristicNotice};
877
+ ${o.connectedSymbols.length} connected symbol(s).`)}),Xm=[Ve({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:x("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Ni(e,M(t,0)),format:e=>e.relativePath}),Ve({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:x("Navigation"),query:({db:e,args:t})=>lo(e,M(t,0)),format:e=>` ${ue(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"grouped-by-file",docs:x("Navigation",["scip-query refs login"]),handler:xN},Ii({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:x("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Mn(e,M(t,0),{semantic:n.semantic}),sections:hN}),Ve({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:x("Navigation"),query:({db:e,args:t})=>On(e,M(t,0)),format:e=>e.relativePath}),Ve({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:x("Navigation"),query:({db:e,args:t})=>$n(e,M(t,0)),format:e=>e.relativePath}),Um({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:x("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>jn(e,M(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ue(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}`)}]}),Ve({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:x("Navigation"),query:({db:e,args:t})=>Bn(e,M(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:x("Navigation"),handler:SN},Ve({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:x("Navigation"),query:({db:e,args:t})=>So(e,M(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:[g("--signatures","Show trimmed symbol signatures")],renderShape:"custom",docs:x("Navigation"),handler:yN},Ve({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:x("Navigation"),query:({db:e,args:t})=>Ro(e,M(t,0)),format:e=>` ${ue(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),Ve({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",R,100)],docs:x("Navigation"),query:({db:e,args:t,opts:n})=>Po(e,M(t,0),{scope:k(n,"scope"),limit:S(n,"limit",100)}),format:e=>` ${se(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${M(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
878
+ ${e.length} symbol(s)`)}),Ri({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[g("-s, --scope <path>","Limit to files matching path")],docs:x("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Fo(e,{scope:k(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Ve({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:x("Navigation"),query:({db:e,args:t})=>To(e,M(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:[g("-C, --context <n>","Extra lines of context above/below",R,0)],renderShape:"custom",docs:x("Navigation"),handler:CN},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Navigation"),handler:RN},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:[g("--forward","Forward slice (what does this affect). Default is backward."),g("--depth <n>","Max transitive depth for backward slice",R,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Navigation"),handler:IN}];var vN=X("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=S(n,"limit",20),o=es(e,M(t,0),{semantic:r.semantic,impactDepth:S(n,"impactDepth",3),sliceDepth:S(n,"sliceDepth",3),scope:k(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target.")return _.empty(o.warnings[0]);let s=[{title:"TARGET",rows:DN(o)},{title:"DEFINITIONS",rows:NN(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:LN(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:_N(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:wN(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:EN(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:kN(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:PN(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:FN(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:AN(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:TN(o),skipIfEmpty:!0}];_.sectionedReport(s)}),Zm=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:[g("--impact-depth <n>","Maximum affected traversal depth",R,3),g("--slice-depth <n>","Maximum backward slice depth",R,3),g("-s, --scope <path>","Limit downstream impact to files matching path"),g("-n, --limit <n>","Rows per section",R,20),g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:x("Planning",["scip-query plan-context parseSymbol"]),handler:vN}];function DN(e){return[`Target: ${e.target}`,`Matched: symbol=${zs(e.matched.symbol)} file=${zs(e.matched.file)} module=${zs(e.matched.module)}`]}function NN(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${se(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
879
+ `).map((o,s)=>` ${String(ye(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ue(r.startLine,r.endLine)} ${r.shortName}`)),ht(n,t).rows}function LN(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${ye(r.line)} in ${r.enclosingShort}`);return Gt(ht(n,t))}function _N(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(i=>` caller ${i.file} ${i.shortName}`),r=e.callGraph.callees.map(i=>` callee ${i.file} ${i.shortName}`);return Gt(ht([...n,...r],t))}function wN(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),r=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),i=e.dataflow.usageSites.map(o=>` usage ${o.file}:${ye(o.line)} in ${o.enclosingShort}`);return Gt(ht([...n,...r,...i],t))}function EN(e,t){let n=[...e.deps.map(r=>` file depends on ${r.relativePath}`),...e.rdeps.map(r=>` file depended on by ${r.relativePath}`),...e.system.dependsOn.map(r=>` module depends on ${r}`),...e.system.dependedOnBy.map(r=>` module used by ${r}`)];return Gt(ht(n,t))}function kN(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ue(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Gt(ht(n,t))}function PN(e,t){let n=[],r=-1;for(let i of e.affected)i.depth!==r&&(n.push(` -- Depth ${i.depth} --`),r=i.depth),n.push(` ${i.file} ${i.shortName}`);return Gt(ht(n,t))}function FN(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(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${ue(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${se(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}`)),Gt(ht(n,t))}function AN(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let r=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${r}`)}for(let r of t.coChangePartners)n.push(` Usually changes with: ${r.file} (${r.together}x, ${Math.round(r.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function TN(e){let t=e.warnings.map(r=>` ${r}`);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(r=>r.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 ht(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Gt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function zs(e){return e?"yes":"no"}var ed=["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","similar-chains","extract-candidates","affected","change-surface","cleanup-plan","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],MN=[zm,Xm,Qm,Jm,Ym,Zm,Km],td=MN.flat(),nd=new Map(td.map(e=>[e.id,e])),XB=ed.map(e=>{let t=nd.get(e);if(!t)throw new Error(`Missing query command descriptor: ${e}`);return t});for(let e of td)if(!ed.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function D(e){let t=nd.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var rd=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[g("-l, --language <lang>","Index only this language (can be repeated)",yu,[]),g("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),g("--force","Rebuild even if source inputs are unchanged"),g("--allow-partial","Write an incomplete index when one or more detected languages fail"),g("--indexer-concurrency <n>","Number of language indexers to run at once",ui)],renderShape:"custom",docs:x("Indexing",["scip-query reindex"]),handler:Nm},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:x("Indexing"),handler:Lm},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[g("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:x("Indexing"),handler:_m},D("stats"),D("files"),D("methods"),D("refs"),D("trace"),D("deps"),D("rdeps"),D("system"),D("surface"),D("dead"),D("hotspots"),D("imports"),D("imported-by"),D("unused-imports"),D("outline"),D("members"),D("fan-in"),D("fan-out"),D("coupling"),D("cycles"),D("bottlenecks"),D("isolated"),D("by-kind"),D("kind-counts"),D("deep-chains"),D("hierarchy"),D("call-graph"),D("similar"),D("similar-files"),D("similar-chains"),D("extract-candidates"),D("affected"),D("change-surface"),D("cleanup-plan"),D("co-change"),D("recent-duplicates"),D("doc-drift"),D("unused-params"),D("diff-gate"),D("plan-context"),{id:li,command:li,description:"Internal diff-impact batch worker",hidden:!0,options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:wm},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",docs:x("Impact"),handler:Em},D("drift"),D("wrapper-candidates"),D("passthrough-candidates"),D("stale-abstractions"),D("complexity-hotspots"),D("self-audit"),{id:ci,command:ci,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:km},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes"),g("--json","Output as JSON for programmatic consumption"),g("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),g("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:x("Health",["scip-query health --json","scip-query health --baseline"]),handler:Pm},D("convergence"),D("code"),D("complexity"),D("dataflow"),D("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${Ds.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:x("Maintenance"),handler:Fm},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:x("Maintenance"),handler:Am},D("redundant-reexports"),D("similar-signatures"),{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:x("Maintenance"),handler:Tm},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[g("--debounce <ms>","Ms to wait after last change (default: 30000)",bs),g("--cooldown <ms>","Min ms between reindexes (default: 60000)",bs)],renderShape:"custom",docs:x("Maintenance"),handler:Mm},{id:"status",command:"status",description:"Show index status for this project",renderShape:"custom",docs:x("Maintenance"),handler:Om}];function id(e,t){return t.map(n=>{let r=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);r.description(n.description);for(let i of n.arguments??[])r.argument(i.name);for(let i of n.options??[])i.parser&&Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.parser,i.defaultValue):i.parser?r.option(i.flags,i.description,i.parser):Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.defaultValue):r.option(i.flags,i.description);return r.action((...i)=>n.handler(...i)),{descriptor:n,command:r}})}import{existsSync as ON,mkdirSync as $N,readFileSync as jN,writeFileSync as BN}from"fs";import{homedir as HN}from"os";import{join as vi}from"path";var qN=1440*60*1e3,sd="update-check.json",VN="https://registry.npmjs.org/scip-query/latest";async function ad(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??GN(t),r=e.now??Date.now(),i=e.currentVersion??ai,o=JN(n),s=o&&r-o.checkedAt<qN?o.latestVersion:await zN(n,e.fetchLatestVersion??KN,r);if(!s||!UN(s,i))return;(e.writeNotice??(c=>console.error(c)))(WN(i,s))}function WN(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
880
+ `)}function UN(e,t){let n=od(e),r=od(t);if(!n||!r)return e!==t;for(let i=0;i<n.length;i++){let o=n[i]-r[i];if(o>0)return!0;if(o<0)return!1}return!1}function GN(e){let t=e.XDG_CACHE_HOME||vi(HN(),".cache");return vi(t,"scip-query")}function JN(e){let t=vi(e,sd);if(!ON(t))return null;try{let n=JSON.parse(jN(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 zN(e,t,n){let r;try{r=await t()}catch{r=null}return QN(e,{checkedAt:n,latestVersion:r}),r}function QN(e,t){try{$N(e,{recursive:!0}),BN(vi(e,sd),`${JSON.stringify(t,null,2)}
881
+ `)}catch{}}async function KN(){let e=await fetch(VN,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function od(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}Di.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(ai);id(Di,rd);Di.hook("preAction",async()=>{await ad()});XN()&&await Di.parseAsync();function XN(){if(!process.argv[1])return!1;let e=YN(import.meta.url);try{return cd(e)===cd(process.argv[1])}catch{return e===process.argv[1]}}export{Di as program,or as renderHeuristicNotice};
882
882
  //# sourceMappingURL=cli.js.map